package com.zcloud.safetyDutyList.command.tasklist;

import com.zcloud.safetyDutyList.domain.enums.TaskStatusEnum;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskExecutionGateway;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskListIssueGateway;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskExecutionE;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskListIssueE;
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.List;

/**
 * 定时任务1：清单下发记录状态更新
 * <p>
 * 定时扫描已下发且周期已结束的下发记录，将其状态更新为已完成，
 * 同时将其下所有进行中的任务执行记录也更新为已完成。
 */
@Slf4j
@Component
@AllArgsConstructor
public class TaskListStatusUpdateExe {
    private final TaskListIssueGateway taskListIssueGateway;
    private final TaskExecutionGateway taskExecutionGateway;

    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void execute() {
        log.info("【定时任务1】开始扫描过期下发记录...");
        List<TaskListIssueE> expiredList = taskListIssueGateway.listExpiredInProgress();
        if (expiredList == null || expiredList.isEmpty()) {
            log.info("【定时任务1】无过期下发记录");
            return;
        }
        for (TaskListIssueE issueE : expiredList) {
            log.info("【定时任务1】下发记录[{}]周期已结束，更新为已完成", issueE.getTaskIssueId());
            issueE.setStatus(TaskStatusEnum.COMPLETED.getCode());
            taskListIssueGateway.update(issueE);

            // 同时关闭该下发记录下所有进行中的任务执行记录
            List<TaskExecutionE> executionList = taskExecutionGateway.listByTaskIssueId(issueE.getTaskIssueId());
            if (executionList != null) {
                for (TaskExecutionE executionE : executionList) {
                    if (TaskStatusEnum.IN_PROGRESS.getCode().equals(executionE.getTaskStatus())) {
                        executionE.setTaskStatus(TaskStatusEnum.COMPLETED.getCode());
                        taskExecutionGateway.update(executionE);
                    }
                }
            }
        }
        log.info("【定时任务1】过期下发记录扫描完成，共处理{}条", expiredList.size());
    }
}
