package com.zcloud.safetyDutyList.command.tasklist;

import com.alibaba.cola.exception.BizException;
import com.zcloud.safetyDutyList.domain.enums.TaskStatusEnum;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskDetailGateway;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskExecutionGateway;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskExecutionE;
import com.zcloud.safetyDutyList.dto.tasklist.TaskExecutionCloseCmd;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 任务关闭执行器
 * <p>
 * 处理关闭任务模板的业务逻辑：
 *   1. 校验任务模板是否存在
 *   2. 将任务模板状态更新为已关闭
 *   3. 同时关闭关联的所有进行中的任务执行记录
 */
@Component
@AllArgsConstructor
public class TaskExecutionCloseExe {
    private final TaskExecutionGateway taskExecutionGateway;

    @Transactional(rollbackFor = Exception.class)
    public void execute(TaskExecutionCloseCmd cmd) {
        // 1. 关闭任务执行记录
        TaskExecutionE executionE = taskExecutionGateway.getByTaskExecutionId(cmd.getTaskExecutionId());
        if (executionE == null) {
            throw new BizException("任务执行记录不存在");
        }

        executionE.setTaskStatus(TaskStatusEnum.CLOSED.getCode());
        boolean res = taskExecutionGateway.update(executionE);
        if (!res) {
            throw new BizException("关闭任务失败");
        }
    }
}
