package com.zcloud.safetyDutyList.command.tasklist;

import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.framework.auth.model.SSOUser;
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.TaskDetailUpdateScoreCmd;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
@AllArgsConstructor
public class TaskDetailUpdateScoreExe {
    private final TaskDetailGateway taskDetailGateway;
    private final TaskListGateway taskListGateway;

    public void execute(TaskDetailUpdateScoreCmd cmd) {

        SSOUser ssoUser = AuthContext.getCurrentUser();
        if (ssoUser == null) {
            throw new BizException("用户未登录");
        }
        TaskDetailE detailE = taskDetailGateway.getByTaskDetailId(cmd.getTaskDetailId());
        if (detailE == null) {
            throw new BizException("任务不存在");
        }
        if (detailE.getTaskStatus() == 1) {
            throw new BizException("任务正在进行， 不能评分");
        }
        if (detailE.getTaskScore() != null && cmd.getTaskRating().compareTo(detailE.getTaskScore()) > 0) {
            throw new BizException("评分不能超过任务分值");
        }
        if (detailE.getTaskRating() != null) {
            throw new BizException("已经评分禁止再次评分");
        }
        detailE.setTaskRating(cmd.getTaskRating());
        detailE.setRatingTime(LocalDateTime.now());

        detailE.setRatingDepartmentId(ssoUser.getOrgId());
        detailE.setRatingUserId(ssoUser.getUserId());

        boolean res = taskDetailGateway.update(detailE);
        if (!res) {
            throw new BizException("评分失败");
        }

        syncTaskListScore(detailE.getTaskListId(), ssoUser);
    }

    private void syncTaskListScore(String taskListId, SSOUser ssoUser) {
        List<TaskDetailE> allDetails = taskDetailGateway.listByTaskListId(taskListId);
        if (allDetails == null || allDetails.isEmpty()) {
            return;
        }
        boolean allScored = allDetails.stream().allMatch(d -> d.getTaskRating() != null);
        if (!allScored) {
            log.info("【清单评分同步】清单[{}]下仍有未评分任务，暂不更新清单分数", taskListId);
            return;
        }
        BigDecimal totalRating = allDetails.stream()
                .map(TaskDetailE::getTaskRating)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        TaskListE taskListE = taskListGateway.getInfoByTaskListId(taskListId);
        if (taskListE == null) {
            log.warn("【清单评分同步】清单[{}]不存在，跳过同步", taskListId);
            return;
        }
        taskListE.setRatingScore(totalRating);
        taskListE.setRatingUserId(ssoUser.getUserId());
        taskListE.setRatingDepartmentId(ssoUser.getOrgId());
        boolean updateRes = taskListGateway.update(taskListE);
        if (updateRes) {
            log.info("【清单评分同步】清单[{}]分数已更新为{}，评分人：{}", taskListId, totalRating, ssoUser.getUserId());
        } else {
            log.warn("【清单评分同步】清单[{}]分数更新失败", taskListId);
        }
    }
}
