package com.pqs9900.task;

import com.njcn.mapper.configuration.SysMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.pojo.configuration.SysSet;
import com.njcn.sso.pojo.user.User;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;

public class LockUserState implements Job {
    @Autowired
    UserMapper userMapper;
    @Autowired
    SysMapper sm;

    public void getLockUserState() {
        List<User> list = userMapper.getAllUser();
        List<SysSet> sysset = sm.selectAll();

        if (sysset == null || sysset.size() == 0) {
            return;
        }

        for (User user : list) {
            if (user.getFirstErrorTime() == null) {
                continue;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(user.getFirstErrorTime());
            calendar.add(Calendar.HOUR, 24);
            Calendar now = Calendar.getInstance();

            if (now.after(calendar) && user.getLoginErrorTimes() > 0 && user.getState() != 2) {//24小时，如果密码错误次数不为0且未锁定的用户统计次数置为0
                userMapper.updateLockState(user.getState(), user.getUserIndex());
            }

            Calendar calendar1 = Calendar.getInstance();
            if (user.getLockTime() == null) {
                continue;
            }
            calendar1.setTime(user.getLockTime());
            calendar1.add(Calendar.MINUTE, sysset.get(0).getLockTime());

            if (now.after(calendar1) && user.getState() == 2) { //锁定的用户自动解锁并将统计次数置为0
                userMapper.updateLockState(1, user.getUserIndex());
            }
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        getLockUserState();
    }
}
