package com.zcloud.safetyDutyList.command.tasklist;

import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.safetyDutyList.domain.enums.TaskStatusEnum;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskExecutionGateway;
import com.zcloud.safetyDutyList.domain.gateway.tasklist.TaskListGateway;
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 org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Transactional(rollbackFor = Exception.class)
    public void execute(String taskIssueId) {
        // 1. 关闭清单下发
        TaskListIssueE issueE = taskListIssueGateway.getByTaskIssueId(taskIssueId);
        if (issueE == null) {
            throw new BizException("清单下发记录不存在");
        }

        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser == null) {
            throw new BizException("用户未登录");
        }
        if (issueE.getIssueUserId() == null) {
            throw new BizException("清单下发记录未指定下发人");
        }
        if (!Objects.equals(issueE.getIssueUserId(), ssoUser.getUserId())) {
            throw new BizException("用户无权限关闭该清单下发记录");
        }

        issueE.setStatus(TaskStatusEnum.CLOSED.getCode());
        issueE.setCloseTime(LocalDateTime.now());
        boolean res = taskListIssueGateway.update(issueE);
        if (!res) {
            throw new BizException("关闭清单下发记录失败");
        }

        // 3. 关闭该下发记录下所有进行中的任务执行记录
        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.CLOSED.getCode());
                    taskExecutionGateway.update(executionE);
                }
            }
        }
    }
}
