package com.zanxiang.game.module.sdk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.mybatis.entity.UserLoginLog;
import com.zanxiang.game.module.mybatis.mapper.UserLoginLogMapper;
import com.zanxiang.game.module.sdk.constant.RedisKeyConstant;
import com.zanxiang.game.module.sdk.enums.LoginTypeEnum;
import com.zanxiang.game.module.sdk.pojo.param.GameUserRoleUpdateParam;
import com.zanxiang.game.module.sdk.pojo.param.UserData;
import com.zanxiang.game.module.sdk.service.IUserLoginLogService;
import com.zanxiang.game.module.sdk.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author : lingfeng
 * @time : 2022-06-13
 * @description : 用户登录日志
 */
@Slf4j
@Service
public class UserLoginLogServiceImpl extends ServiceImpl<UserLoginLogMapper, UserLoginLog> implements IUserLoginLogService {

    @Autowired
    private RedisUtil<String> redisUtil;

    @Override
    public Boolean createRoleLoginLog(UserData userData, GameUserRoleUpdateParam param, LoginTypeEnum loginTypeEnum) {
        UserLoginLog loginLog = UserLoginLog.builder()
                .userId(userData.getUserId())
                .gameId(userData.getGameId())
                .serverId(param.getServerId())
                .roleId(param.getRoleId())
                .roleName(param.getRoleName())
                .os(userData.getDeviceSystem())
                .ip(userData.getIp())
                .deviceType(userData.getDeviceType())
                .type(loginTypeEnum.getLoginType())
                .createTime(LocalDateTime.now())
                .build();
        boolean result = super.save(loginLog);
        if (result) {
            redisUtil.addToSet(RedisKeyConstant.IP_DATA_ASSAY_QUEUE,
                    "LOGIN:" + loginLog.getId() + ":" + loginLog.getIp());
        }
        return result;
    }

    @Override
    public Boolean createUserLoginLog(UserData userData, LoginTypeEnum loginTypeEnum) {
        UserLoginLog loginLog = UserLoginLog.builder()
                .userId(userData.getUserId())
                .gameId(userData.getGameId())
                .os(userData.getDeviceSystem())
                .ip(userData.getIp())
                .deviceType(userData.getDeviceType())
                .type(loginTypeEnum.getLoginType())
                .createTime(LocalDateTime.now())
                .build();
        boolean result = super.save(loginLog);
        if (result) {
            redisUtil.addToSet(RedisKeyConstant.IP_DATA_ASSAY_QUEUE,
                    "LOGIN:" + loginLog.getId() + ":" + loginLog.getIp());
        }
        return result;
    }
}
