package com.zcloud.safetyDutyList.command.tasklist;

import com.zcloud.safetyDutyList.command.query.tasklist.MessageNoticeExe;
import com.zcloud.safetyDutyList.domain.config.MessageTemplateConfig;
import com.zcloud.safetyDutyList.domain.enums.TaskStatusEnum;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.*;
import com.zcloud.safetyDutyList.domain.model.tasklist.*;
import com.zcloud.safetyDutyList.domain.util.FeedbackCycleUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务2：反馈异常检测
 * <p>
 * 执行周期：每月1日0时
 * <p>
 * 实现逻辑：
 *   1. 获取所有 task_status=1 的任务执行记录，获取其反馈周期类型 feedback_cycle_type
 *   2. 根据反馈周期类型判断上一阶段是否有反馈记录，无记录则判定为异常
 *   判定规则：
 *     feedback_cycle_type=1（每月）：每个月都需要反馈至少一次
 *     feedback_cycle_type=2（每季度）：每个季度（自然月划分）都需要反馈至少一次
 *     feedback_cycle_type=3（每半年）：每半年（以自然月6月划分）都需要反馈至少一次
 *     feedback_cycle_type=4（年）：一年内必须反馈至少一次
 */
@Slf4j
@Component
@AllArgsConstructor
public class SendTodoMessageExe {
    private final TaskListIssueGateway taskListIssueGateway;
    private final TaskExecutionGateway taskExecutionGateway;
    private final TaskDetailGateway taskDetailGateway;
    private final TaskListGateway taskListGateway;
    private final FeedbackGateway feedbackGateway;
    private final MessageNoticeExe messageNoticeExe;
    private final MessageTemplateConfig messageTemplateConfig;

    @Scheduled(cron = "0 0 0 1 * ?")
    @Transactional(rollbackFor = Exception.class)
    public void execute() {
        log.info("【定时任务3】开始发送待办消息...");
        List<TaskListIssueE> issuedList = taskListIssueGateway.listIssuedWithPeriod();
        if (issuedList == null || issuedList.isEmpty()) {
            log.info("【定时任务3】无下发记录需要发送待办");
            return;
        }

        for (TaskListIssueE issueE : issuedList) {
            List<TaskExecutionE> executionList = taskExecutionGateway.listByTaskIssueId(issueE.getTaskIssueId());
            if (executionList == null) continue;

            TaskListE taskListE = taskListGateway.getInfoByTaskListId(issueE.getTaskListId());
            String taskListName = "";
            if (taskListE != null) {
                taskListName = taskListE.getTaskListName();
            }

            Boolean isSendMessage = false;
            for (TaskExecutionE executionE : executionList) {

                // 不是进行中就返回
                if (!TaskStatusEnum.IN_PROGRESS.getCode().equals(executionE.getTaskStatus())) continue;


                // 获取任务详情
                TaskDetailE detailE = taskDetailGateway.getByTaskDetailId(executionE.getTaskDetailId());
                if (detailE == null || detailE.getFeedbackCycleType() == null) continue;

                // 反馈周期枚举： 1（每月） 2（每季度） 3（每半年） 4（年）
                Integer feedbackCycleType = detailE.getFeedbackCycleType();

                // 首周期判断：如果当前仍处于清单的首个反馈周期内，跳过检测
                if (!FeedbackCycleUtil.isFirstCycle(feedbackCycleType, issueE.getPeriodStartTime())) {
                    continue;
                }

                // 当前周期标识
                String currentCycleFlag = FeedbackCycleUtil.generatePeriodFlag(feedbackCycleType, LocalDateTime.now());

                // 检查阶段内是否有反馈记录
                List<FeedbackE> feedbackList = feedbackGateway.listByTaskExecutionIdAndPeriodFlag(
                        executionE.getTaskExecutionId(), currentCycleFlag);
                if (feedbackList != null && !feedbackList.isEmpty()) {
                    // 周期内存在反馈
                    continue;
                }

                isSendMessage = true;
                break;
            }

            if (isSendMessage) {
                // 发送消息提醒
                Map<String, Object> sendParams = new HashMap <>();
                sendParams.put("listName", taskListName);
                messageNoticeExe.messageNotice(issueE.getExecuteUserId(), messageTemplateConfig.getFirstDayOfCycleSendMsgTodo(), sendParams);

                // 发送待办消息
                messageNoticeExe.sendMessageAddEvent(
                        issueE.getExecuteUserId(),
                        "您有一条任务清单待反馈，清单名称：【" + taskListName + "】",
                        "待反馈",
                        issueE.getId(),
                        issueE.getId());
            }
        }
        log.info("【定时任务3】待办消息发送完成");
    }
}
