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.gateway.tasklist.TaskListIssueGateway;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskDetailE;
import com.zcloud.safetyDutyList.domain.model.tasklist.TaskListE;
import com.zcloud.safetyDutyList.dto.clientobject.tasklist.TaskListCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskDetailAddCmd;
import com.zcloud.safetyDutyList.dto.tasklist.TaskListUpdateCmd;
import com.zcloud.safetyDutyList.persistence.repository.tasklist.TaskListRepository;
import lombok.AllArgsConstructor;
import org.apache.xpath.operations.Bool;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 清单修改执行器
 * <p>
 * 处理修改安全责任清单的业务逻辑：
 *   1. 校验清单是否存在
 *   2. 更新清单信息
 *   3. 先删除该清单下所有旧的任务详情，再根据命令重新创建任务详情
 * <p>
 * 注意：修改清单时采用"先删后增"策略处理任务详情
 */
@Component
@AllArgsConstructor
public class TaskListUpdateExe {
    private final TaskListGateway taskListGateway;
    private final TaskListIssueGateway taskListIssueGateway;

    @Transactional(rollbackFor = Exception.class)
    public Boolean execute(TaskListUpdateCmd cmd) {
        TaskListE existE = taskListGateway.getInfoByTaskListId(cmd.getTaskListId());
        if (existE == null) {
            throw new BizException("任务清单不存在");
        }

        // 已经下发的任务，禁止修改
        if (taskListIssueGateway.isIssued(existE.getTaskListId())) {
            throw new BizException("任务清单已下发，禁止修改");
        }

        BeanUtils.copyProperties(cmd, existE);
        boolean res = taskListGateway.update(existE);
        if (!res) {
            throw new BizException("修改失败");
        }
        return true;
    }
}
