package cn.iocoder.byzs.module.system.service.logger;

import cn.iocoder.byzs.framework.common.pojo.PageResult;
import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.byzs.module.system.controller.admin.logger.vo.loginlog.LoginLogPageReqVO;
import cn.iocoder.byzs.module.system.dal.dataobject.logger.LoginLogDO;
import cn.iocoder.byzs.module.system.dal.mysql.logger.LoginLogMapper;
import cn.iocoder.byzs.module.system.enums.logger.LoginResultEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 登录日志 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 Set<String> selectIpListByUserId(Long userId) {
        List<LoginLogDO> loginLogDOS = loginLogMapper.selectList(new LambdaQueryWrapper<LoginLogDO>()
                .select(LoginLogDO::getUserIp)
                .eq(LoginLogDO::getUserId, userId)
                .eq(LoginLogDO::getResult, LoginResultEnum.SUCCESS.getResult()));
        if (loginLogDOS == null || loginLogDOS.isEmpty()) {
            return Collections.emptySet();
        }
        return loginLogDOS.stream()
                .map(LoginLogDO::getUserIp)
                .collect(Collectors.toSet());
    }

}
