package com.jiayue.ssi.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.mapper.SysUserMapper;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.service.SysUserService;
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.List;

/**
* 系统定时扫描未使用的账号
*
* @author xsl
* @since 2023/04/06
*/
@Service
@EnableScheduling
@Slf4j
public class AutoScanAccount {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysPolicyService sysPolicyService;
    @Autowired
    SysUserMapper sysUserMapper;

    /**
     * 每10分钟执行一次扫描
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void scanNotUsedAccount() throws Exception{
        SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
        int autoScanAccount = sysPolicy.getScanAccount();
        if (autoScanAccount>0){
//            log.info("自动扫描长期未使用的账号开始。。。");
            // 进行扫描
            List<SysUser> sysUsers = sysUserService.queryAllUsers();
            for (SysUser sysUser:sysUsers){
                Calendar calendar = Calendar.getInstance();
                if (sysUser.getLoginDate()==null){
                    calendar.setTime(sysUser.getCreateTime());
                }
                else{
                    calendar.setTime(sysUser.getLoginDate());
                }
                calendar.add(Calendar.MONTH, autoScanAccount);
                if (calendar.getTimeInMillis()<System.currentTimeMillis()){
                    // 上次登录后N月没有使用，锁定账号
                    // 设置用户离线状态
                    LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
                    updateWrapper.eq(SysUser::getId, sysUser.getId()).set(SysUser::getStatus, "1").set(SysUser::getLockTime,0);
                    int i = sysUserMapper.update(new SysUser(), updateWrapper);

                    if (i<=0){
                        log.info("账号："+sysUser.getUsername()+",超过"+autoScanAccount+"个月未使用,锁定账号失败!");
                    }
                    else{
                        log.info("账号："+sysUser.getUsername()+",超过"+autoScanAccount+"个月未使用,锁定账号成功!");
                    }
                }
            }
//            log.info("自动扫描长期未使用的账号完成");
        }
    }
}
