package com.zcloud.safetyDutyList.command.tasklist;

import com.alibaba.cola.exception.BizException;
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.dto.clientobject.tasklist.TaskDetailCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskDetailSaveCmd;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

/**
 * 任务详情保存执行器
 * <p>
 * 处理新增任务详情的业务逻辑：
 *   1. 查询该清单下已有任务详情，计算总分
 *   2. 校验新增后清单总分不超过100分
 *   3. 创建任务详情实体并保存
 *   4. 返回新增后的任务详情信息
 */
@Component
@AllArgsConstructor
public class TaskDetailSaveExe {
    private final TaskDetailGateway taskDetailGateway;
    private final TaskListGateway taskListGateway;

    public TaskDetailCO execute(TaskDetailSaveCmd cmd) {
        List<TaskDetailE> existDetails = taskDetailGateway.listByTaskListId(cmd.getTaskListId());
        BigDecimal totalScore = existDetails.stream()
                .map(TaskDetailE::getTaskScore)
                .filter(s -> s != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal diff = new BigDecimal("100").subtract(totalScore);

        if (cmd.getTaskScore() != null) {
            totalScore = totalScore.add(cmd.getTaskScore());
        }
        if (totalScore.compareTo(new BigDecimal("100")) > 0) {
            throw new BizException("当前清单总分不能超过100,当前任务可设最大分值：" + diff);
        }

        TaskDetailE detailE = new TaskDetailE();
        BeanUtils.copyProperties(cmd, detailE);
        detailE.init();
        boolean res = taskDetailGateway.add(detailE);
        if (!res) {
            throw new BizException("保存失败");
        }

        TaskDetailCO co = new TaskDetailCO();
        BeanUtils.copyProperties(detailE, co);
        return co;
    }
}
