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.model.tasklist.TaskDetailE;
import com.zcloud.safetyDutyList.dto.clientobject.tasklist.TaskDetailCO;
import com.zcloud.safetyDutyList.dto.tasklist.TaskDetailEditCmd;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

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

@Component
@AllArgsConstructor
public class TaskDetailEditExe {
    private final TaskDetailGateway taskDetailGateway;

    public TaskDetailCO execute(TaskDetailEditCmd cmd) {
        TaskDetailE existDetail = taskDetailGateway.getByTaskDetailId(cmd.getTaskDetailId());
        if (existDetail == null) {
            throw new BizException("任务详情不存在");
        }

        List<TaskDetailE> existDetails = taskDetailGateway.listByTaskListId(existDetail.getTaskListId());
        BigDecimal otherTotalScore = existDetails.stream()
                .filter(d -> !d.getTaskDetailId().equals(cmd.getTaskDetailId()))
                .map(TaskDetailE::getTaskScore)
                .filter(s -> s != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

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

        existDetail.setExecuteContent(cmd.getExecuteContent());
        existDetail.setFeedbackCycleType(cmd.getFeedbackCycleType());
        existDetail.setTaskScore(cmd.getTaskScore());
        boolean res = taskDetailGateway.update(existDetail);
        if (!res) {
            throw new BizException("编辑失败");
        }

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