package com.jiayue.ssi.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.constant.Constants;
import com.jiayue.ssi.constant.LoginConstants;
import com.jiayue.ssi.dto.UserVisitInfoDto;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.factory.LoginFactory;
import com.jiayue.ssi.service.SysLogininforService;
import com.jiayue.ssi.service.SysOperLogService;
import com.jiayue.ssi.service.SysPolicyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;

/**
* 自动检测并发会话数是否存在超时
*
* @author xsl
* @since 2023/06/28
*/
@Service
@EnableScheduling
@Slf4j
public class AutoCheckSessionMap {
    @Autowired
    SysPolicyService sysPolicyService;

    /**
     * 每分钟执行
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void auditBak() throws Exception{
        SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
        // 非活动登出时间（分钟）
        int inactiveLogout = sysPolicy.getInactiveLogout();

        long iil = inactiveLogout * 1000 * 60;

        Iterator<Map.Entry<String, UserVisitInfoDto>> entries = LoginConstants.sessionMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, UserVisitInfoDto> entry = entries.next();
            // 判断会话连接里失效的用户
            UserVisitInfoDto userVisitInfoDto = entry.getValue();
            Long userTime = userVisitInfoDto.getVtime();
            if (System.currentTimeMillis()> userTime + iil){
                // 踢用户
                LoginConstants.sessionMap.remove(entry.getKey());
                // 记录用户退出日志
                LoginFactory.autoRecordLogininfor(userVisitInfoDto, Constants.LOGIN_SUCCESS, "超时登出");
            }
        }
    }
}
