package com.cico.nest.lcdp.boot.core.system.service.logger;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cico.nest.lcdp.boot.api.system.logger.dto.LoginLogCreateReqDTO;
import com.cico.nest.lcdp.boot.core.system.controller.admin.logger.vo.loginlog.LoginLogPageReqVO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.logger.LoginLogDO;
import com.cico.nest.lcdp.boot.core.system.dal.mysql.logger.LoginLogMapper;
import com.cico.nest.lcdp.framework.common.pojo.PageResult;
import com.cico.nest.lcdp.framework.common.util.object.BeanUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 登录日志 Service 实现
 */
@Service
@Validated
public class LoginLogServiceImpl implements LoginLogService {

    @Resource
    private LoginLogMapper loginLogMapper;

    @Override
    public PageResult<LoginLogDO> getLoginLogPage(LoginLogPageReqVO pageReqVO) {
        return loginLogMapper.selectPage(pageReqVO);
    }

    @Override
    public void createLoginLog(LoginLogCreateReqDTO reqDTO) {
        LoginLogDO loginLog = BeanUtils.toBean(reqDTO, LoginLogDO.class);
        loginLogMapper.insert(loginLog);
    }

    @Override
    public Map<Long, Long> countLoginNumsByUsers(List<Long> userIds) {
        QueryWrapper<LoginLogDO> queryWrapper = Wrappers.<LoginLogDO>query()
                .select("user_id as userId,count(*) as loginNum")
                .groupBy("user_id")
                .lt("log_type",200) //小于200表示登录日志类型
                .in("user_id",userIds);

        List<Map<String, Object>> userLoginNumList = loginLogMapper.selectMaps(queryWrapper);
        Map<Long, Long> userLoginMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userLoginNumList)){
            for(Map<String, Object> map : userLoginNumList){
                Long userId = (Long) map.getOrDefault("userId","0");
                Long num = (Long) map.getOrDefault("loginNum","0");
                userLoginMap.put(userId,num);
            }
        }
        return userLoginMap;
    }

}
