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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.base.pojo.enums.GameCategoryEnum;
import com.zanxiang.game.module.manage.pojo.dto.GameDTO;
import com.zanxiang.game.module.manage.pojo.dto.GameUserRoleDTO;
import com.zanxiang.game.module.manage.pojo.params.UserLoginLogParam;
import com.zanxiang.game.module.manage.pojo.vo.UserRoleLoginVO;
import com.zanxiang.game.module.manage.service.IGameService;
import com.zanxiang.game.module.manage.service.IGameUserRoleService;
import com.zanxiang.game.module.manage.service.IUserLoginLogService;
import com.zanxiang.game.module.mybatis.entity.UserLoginLog;
import com.zanxiang.game.module.mybatis.mapper.UserLoginLogMapper;
import com.zanxiang.module.util.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

    @Autowired
    private IGameUserRoleService gameUserRoleService;

    @Autowired
    private IGameService gameService;

    @Override
    public IPage<UserRoleLoginVO> loginList(UserLoginLogParam param) {
        //执行查询
        return page(param.toPage(), new QueryWrapper<UserLoginLog>().lambda()
                .eq(UserLoginLog::getUserId, param.getUserId())
                .orderByDesc(UserLoginLog::getCreateTime)
        ).convert(this::toVo);
    }

    private UserRoleLoginVO toVo(UserLoginLog userLoginLog) {
        UserRoleLoginVO roleLoginVO = BeanUtil.copy(userLoginLog, UserRoleLoginVO.class);
        if (userLoginLog == null) {
            return null;
        }
        roleLoginVO.setLoginIp(userLoginLog.getIp());
        roleLoginVO.setLoginTime(userLoginLog.getCreateTime());
        //查询角色名称
        GameUserRoleDTO gameUserRoleDTO = gameUserRoleService.getByRoleId(userLoginLog.getUserId(),
                userLoginLog.getGameId(), userLoginLog.getRoleId());
        if (gameUserRoleDTO != null) {
            roleLoginVO.setRoleName(gameUserRoleDTO.getRoleName());
        }
        //设置游戏名称
        GameDTO gameDTO = gameService.getById(userLoginLog.getGameId());
        if (gameDTO != null) {
            roleLoginVO.setGameCategoryName(GameCategoryEnum.getNameByCategory(gameDTO.getCategory()));
            roleLoginVO.setGameName(gameDTO.getName());
        }
        return roleLoginVO;
    }
}
