package com.smppw.modaq.application.task;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.smppw.modaq.application.service.EmailParseApiService;
import com.smppw.modaq.common.conts.EmailTypeConst;
import com.smppw.modaq.domain.entity.TaskRecordDO;
import com.smppw.modaq.domain.service.TaskRecordService;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class ParseSchedulerTask {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final EmailParseApiService emailParseApiService;
    private final TaskRecordService taskRecordService;

    public ParseSchedulerTask(EmailParseApiService emailParseApiService, TaskRecordService taskRecordService) {
        this.emailParseApiService = emailParseApiService;
        this.taskRecordService = taskRecordService;
    }

    @PostConstruct
    public void executeOnStartup() {
//        try {
//            // 定期报告从 其他文件夹/报告公告 文件夹获取邮件
//            this.emailParseApiService.parseEmail(
//                    DateUtil.parseDateTime("2025-06-03 18:40:00"),
//                    DateUtil.parseDateTime("2025-06-03 19:56:00"),
//                    ListUtil.of("其他文件夹/报告公告"), EmailTypeConst.REPORT_EMAIL_TYPES);
//        } catch (Exception e) {
//            logger.error(ExceptionUtil.getMessage(e));
//        }
//
//        try {
//            // 确认函从 INBOX 文件夹获取邮件
//            this.emailParseApiService.parseEmail(
//                    DateUtil.parseDateTime("2025-06-03 18:50:00"),
//                    DateUtil.parseDateTime("2025-06-03 19:56:00"),
//                    null, ListUtil.of(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE));
//        } catch (Exception e) {
//            logger.error(ExceptionUtil.getMessage(e));
//        }
    }

    /**
     * 定时任务每11分钟执行一次
     */
    @Scheduled(cron = "0 */11 * * * ?")
    public void letter() {
        String taskKey = "mo_email_parse_letter_task";
        TaskRecordDO task = this.taskRecordService.getTaskRecord(taskKey, 11 * 2 * 60);
        if (task == null) {
            return;
        }
        long start = System.currentTimeMillis();
        Date now = new Date();
        try {
            // 尽可能往前找11分钟覆盖可能遗漏的邮件
            Date startTime = DateUtil.offsetMinute(task.getStartTime(), -11);
            // 确认单从 INBOX 默认文件夹获取邮件
            this.emailParseApiService.parseEmail(startTime, now,
                    null, ListUtil.of(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE));
            task.setStatus(1);
        } catch (Exception e) {
            task.setStatus(2);
            task.setErrMsg(ExceptionUtil.stacktraceToString(e));
            this.logger.error("任务{} 执行错误：{}", taskKey, ExceptionUtil.stacktraceToString(e));
        } finally {
            task.setEndTime(now);
            this.taskRecordService.updateStatus(task);
            if (this.logger.isInfoEnabled()) {
                this.logger.info("任务{} 执行完成，耗时：{}ms", taskKey, System.currentTimeMillis() - start);
            }
        }
    }

    /**
     * 定时任务每小时的15分和45分执行一次
     */
    @Scheduled(cron = "0 15,45 * * * ?")
    public void report() {
        String taskKey = "mo_email_parser_report_task";
        TaskRecordDO task = this.taskRecordService.getTaskRecord(taskKey, 60 * 2 * 60);
        if (task == null) {
            return;
        }
        long start = System.currentTimeMillis();
        Date now = new Date();
        try {
            // 尽可能往前找60分钟覆盖可能遗漏的邮件
            Date startTime = DateUtil.offsetMinute(task.getStartTime(), -60);
            // 定期报告从 我的文件夹.报告公告 文件夹获取邮件
            this.emailParseApiService.parseEmail(startTime, now,
                    ListUtil.of("其他文件夹/报告公告"), EmailTypeConst.REPORT_EMAIL_TYPES);
            task.setStatus(1);
        } catch (Exception e) {
            task.setStatus(2);
            task.setErrMsg(ExceptionUtil.stacktraceToString(e));
            this.logger.error("定期报告解析任务{} 执行错误：{}", taskKey, ExceptionUtil.stacktraceToString(e));
        } finally {
            task.setEndTime(now);
            this.taskRecordService.updateStatus(task);
            if (this.logger.isInfoEnabled()) {
                this.logger.info("定期报告解析任务{} 执行完成，耗时：{}ms", taskKey, System.currentTimeMillis() - start);
            }
        }
    }
}
