package org.springblade.face.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springblade.face.entity.LoginRecord;
import org.springblade.face.service.ILoginRecordService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class LoginStatusTiming {


	@Autowired
	private ILoginRecordService loginRecordService;

	@Autowired
	private IUserService userService;


    /**
     * 自动更新账号登录状态
     * cron = "0 0 0 * * ?" 00:00
     * cron = "0 * * * * ? *" 每分钟
	 * cron = "0 0 * * * ? *"  每小时
     */
//    @Scheduled(cron = "0 0 * * * ?")
    public void VipInfoTiming() {
        log.info("自动更新账号登录状态定时任务开始 ====== ");
        try {
			List<User> list = userService.list(new LambdaQueryWrapper<User>()
				.eq(User::getIsDeleted, 0)
			);

			Date date = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = new GregorianCalendar();
			c.setTime(date);
			c.set(Calendar.DAY_OF_MONTH,1);
			String beginTime = format.format(c.getTime());

			c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
			String endTime = format.format(c.getTime());

			for (User user : list) {
				List<LoginRecord> loginRecordList = loginRecordService.list(new LambdaQueryWrapper<LoginRecord>()
					.eq(LoginRecord::getUserId, user.getId())
					.ge(LoginRecord::getLoginTime, beginTime)
					.le(LoginRecord::getLoginTime, endTime)
				);
				if(loginRecordList != null && !loginRecordList.isEmpty()){
					Map<String, List<LoginRecord>> ipGroup = loginRecordList.stream().collect(Collectors.groupingBy(LoginRecord::getLoginIp));
					Map<String, List<LoginRecord>> addressGroup = loginRecordList.stream().collect(Collectors.groupingBy(LoginRecord::getLoginAddress));
					if(ipGroup.size() >= 5 && addressGroup.size() >=3 && user.getLoginStatus() != 2){
						user.setLoginStatus(2);
						userService.updateById(user);
					}else if(ipGroup.size() >= 3 && ipGroup.size() < 5 && addressGroup.size() < 3 && user.getLoginStatus() == 0){
						user.setLoginStatus(1);
						userService.updateById(user);
					}else if(user.getLoginStatus() == null){
						user.setLoginStatus(0);
						userService.updateById(user);
					}
				}
			}
            log.info("自动更新账号登录状态定时任务结束 ====== ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


	/**
	 * 月初重置所有账号异常登录状态
	 */
//	@Scheduled(cron = "0 0 0 1 * ?")
	public void resetTiming() {
		log.info("自动重置账号登录状态定时任务开始 ====== ");
		try {
			List<User> list = userService.list(new LambdaQueryWrapper<User>()
				.eq(User::getIsDeleted, 0)
			);
			for (User user : list) {
				user.setLoginStatus(0);
			}
			userService.updateBatchById(list);
			log.info("自动重置账号登录状态定时任务结束 ====== ");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
