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.TaskListGateway;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskDetailE;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskListE;
import com.zcloud.safetyDutyList.dto.tasklist.TaskListCloseCmd;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 清单关闭执行器
 * <p>
 * 处理关闭安全责任清单的业务逻辑：
 *   1. 校验清单是否存在
 *   2. 将清单状态更新为已关闭，记录关闭时间
 *   3. 同时关闭该清单下所有任务详情
 */
@Component
@AllArgsConstructor
public class TaskListCloseExe {
    private final TaskListGateway taskListGateway;
    private final TaskDetailGateway taskDetailGateway;

    @Transactional(rollbackFor = Exception.class)
    public void execute(TaskListCloseCmd cmd) {
        TaskListE taskListE = taskListGateway.getInfoByTaskListId(cmd.getTaskListId());
        if (taskListE == null) {
            throw new BizException("任务清单不存在");
        }
        taskListE.setStatus(TaskStatusEnum.CLOSED.getCode());
        taskListE.setCloseTime(LocalDateTime.now());
        boolean res = taskListGateway.update(taskListE);
        if (!res) {
            throw new BizException("关闭失败");
        }
//        List<TaskDetailE> detailList = taskDetailGateway.listByTaskListId(cmd.getTaskListId());
//        for (TaskDetailE detail : detailList) {
//            detail.setTaskStatus(TaskStatusEnum.CLOSED.getCode());
//            taskDetailGateway.update(detail);
//        }
    }
}
