package com.bonus.job.task;

import com.bonus.common.core.utils.DateUtils;
import com.bonus.job.mapper.SysJobMapper;
import com.bonus.system.api.domain.SysUser;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度测试
 * 
 * @author bonus
 */
@Component("sysTask")
public class SysTask
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 3个月
     */
    final static int LAST_LOGIN_TIME_INTERVAL = 90*24*60;
    @Resource
    private SysJobMapper mapper;

    /**
     *如果用户超过3个月未登录，则修改为停用状态
     */
    public void checkUserLastLoginTime(){
        try{
            SysUser user = new SysUser();
            user.setStatus("0");
            List<SysUser> sysUsers = mapper.selectUserList(user);
            sysUsers.forEach(item -> {
                Date loginDate = item.getLoginDate();
                if (ObjectUtils.isEmpty(item.getLoginDate())){
                    loginDate = item.getCreateTime();
                }
                long minutes = DateUtils.minutesBetween(loginDate, DateUtils.getNowDate());
                if (minutes >= LAST_LOGIN_TIME_INTERVAL){
                    int i = mapper.updateUser(item.getUserId());
                    if (i>0){
                        logger.error("修改用户状态,用户id为：{},用户名为：{}",item.getUserId(),item.getUserName());
                    }else {
                        logger.error("修改用户状态失败,用户id为：{},用户名为：{}",item.getUserId(),item.getUserName());
                    }
                }
            });
        }
        catch (Exception e){
            logger.error("修改用户状态异常，{}",e.getMessage());
        }
    }

    /**
     *临时用户有时间限制，自创建起三个月则修改为停用状态
     */
    public void checkUserPermanent(){
        try{
            SysUser user = new SysUser();
            user.setIsPermanent("0");
            List<SysUser> sysUsers = mapper.selectUserList(user);
            sysUsers.forEach(item -> {
                long minutes = DateUtils.minutesBetween(item.getCreateTime(), DateUtils.getNowDate());
                if (minutes >= LAST_LOGIN_TIME_INTERVAL){
                    int i = mapper.updateUser(item.getUserId());
                    if (i>0){
                        logger.error("修改用户状态,用户id为：{},用户名为：{}",item.getUserId(),item.getUserName());
                    }else {
                        logger.error("修改用户状态失败,用户id为：{},用户名为：{}",item.getUserId(),item.getUserName());
                    }
                }
            });
        }
        catch (Exception e){
            logger.error("修改用户状态异常，{}",e.getMessage());
        }
    }



}
