package com.ruoyi.framework.task;

import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.thread.sai.SaiApplyDueMailThread;
import com.ruoyi.common.thread.sai.SaiApplyMailThread;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.production.controller.vo.SaiApplyQueryVO;
import com.ruoyi.project.production.domain.TSaiApply;
import com.ruoyi.project.production.mapper.TSaiApplyMapper;
import com.ruoyi.project.production.service.ITSaiApplyService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务 - SAI
 *
 * @author Wang Zi Wen
 * @email wangggziwen@163.com
 * @date 2023/04/19 13:16:26
 */
@Component("saiTask")
public class SaiTask extends BaseController {
    @Autowired
    private TSaiApplyMapper saiApplyMapper ;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IMailService mailService;

    /**
     * 检查即将到期的SAI
     *
     * 定义：1申请状态为“进行中”，2预计完成时间距离当前时间小于3天
     * 处理：针对每项即将到期的SAI，分别在到期前3天和到期前1天发送邮件提醒
     */
    public void checkDueSai() {
        SaiApplyQueryVO tSaiApply = new SaiApplyQueryVO();
        tSaiApply.setApplyStatus(2L);//申请状态为“进行中”
        List<TSaiApply> executingApplies = saiApplyMapper.selectTSaiApplyList(tSaiApply);//申请状态为“进行中”的SAI
        if (executingApplies == null) {//SAI列表判空
            return;
        }
        List<TSaiApply> dueApplies = new ArrayList<>();//申请状态为“进行中”并且即将到期的SAI
        long now = new Date().getTime();//当前时间
        for (TSaiApply apply : executingApplies) {//时间差小于1天
            long estimateFinishTime = apply.getEstimateFinishDate().getTime();//预计完成时间
            long diff = estimateFinishTime - now;//时间差（ms）
            if (diff > 0 && diff <= 1 * 24 * 60 * 60 * 1000) {
                dueApplies.add(apply);
            }
        }
        for (TSaiApply apply : executingApplies) {//时间差小于3天
            long estimateFinishTime = apply.getEstimateFinishDate().getTime();//预计完成时间
            long diff = estimateFinishTime - now;//时间差（ms）
            if (diff > 0 && diff <= 3 * 24 * 60 * 60 * 1000) {
                dueApplies.add(apply);
            }
        }
        dueApplies = dueApplies.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TSaiApply::getSaiApplyId))), ArrayList::new));
        for (TSaiApply dueApply : dueApplies) {
            String executor = dueApply.getExecutor();//整改负责人
            SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(executor));
            SaiApplyDueMailThread mailThread = new SaiApplyDueMailThread(mailService, dueApply, sysUser);//邮件线程
            Thread thread = new Thread(mailThread);
            thread.start();
        }
    }
}
