package com.zcloud.domain.command;

import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.jjb.saas.message.client.message.facede.MessageFacade;
import com.jjb.saas.message.client.message.request.MessageSendCmd;
import com.jjb.saas.message.client.message.request.MessageTargetCmd;
import com.zcloud.domain.domain.config.MessageConfig;
import com.zcloud.domain.domain.enums.CommonFlagEnum;
import com.zcloud.domain.domain.enums.ScoreStatusEnum;
import com.zcloud.domain.domain.gateway.ProjectTaskScoreInfoGateway;
import com.zcloud.domain.domain.model.CorpInfoE;
import com.zcloud.domain.domain.model.ProjectTaskScoreInfoE;
import com.zcloud.domain.dto.ProjectTaskScoreInfoUpdateCmd;
import com.zcloud.domain.dto.ProjectTaskSetScoreCmd;
import com.zcloud.domain.persistence.dataobject.DomainGroupDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskGroupUserDO;
import com.zcloud.domain.persistence.dataobject.ProjectTaskScoreInfoDO;
import com.zcloud.domain.persistence.repository.*;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
import com.zcloud.gbscommon.todolistmq.event.TodoListCompleteEvent;
import com.zcloud.gbscommon.todolistmq.event.TodoListDeleteEvent;
import com.zcloud.gbscommon.utils.UuidUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2026-01-27 11:30:46
 */
@Component
@AllArgsConstructor
@Slf4j
public class ProjectTaskScoreInfoUpdateExe {
    private final ProjectTaskScoreInfoGateway projectTaskScoreInfoGateway;
    private final ProjectTaskScoreInfoRepository projectTaskScoreInfoRepository;
    private final ProjectTaskRepository projectTaskRepository;
    private final CorpInfoRepository corpInfoRepository;
    private final ProjectTaskGroupUserRepository projectTaskGroupUserRepository;
    @DubboReference
    private final MessageFacade messageFacade;
    private final TodoListEventPusherUtil todoListEventPusherUtil;
    private final DomainGroupRepository domainGroupRepository;
    @Resource
    private MessageConfig messageConfig;

    @Transactional(rollbackFor = Exception.class)
    public void execute(ProjectTaskScoreInfoUpdateCmd projectTaskScoreInfoUpdateCmd) {
        ProjectTaskScoreInfoE projectTaskScoreInfoE = new ProjectTaskScoreInfoE();
        BeanUtils.copyProperties(projectTaskScoreInfoUpdateCmd, projectTaskScoreInfoE);
        boolean res = projectTaskScoreInfoGateway.update(projectTaskScoreInfoE);
        if (!res) {
            throw new BizException("修改失败");
        }
    }

    public void setScore(ProjectTaskSetScoreCmd projectTaskSetScoreCmd) {
        ProjectTaskScoreInfoDO info = projectTaskScoreInfoRepository.getById(projectTaskSetScoreCmd.getId());
        if(info == null){
            throw new BizException("数据不存在");
        }
        //不是企业账号，并且不是本人，不允许设置评分
        if(!CorpInfoE.isCorp() && !AuthContext.getUserId().equals(info.getUserId())) {
           throw new BizException("只允许设置自己的评分");
        }

        ProjectTaskScoreInfoE projectTaskScoreInfoE = new ProjectTaskScoreInfoE();
        BeanUtils.copyProperties(projectTaskSetScoreCmd, projectTaskScoreInfoE);
        boolean res = projectTaskScoreInfoGateway.update(projectTaskScoreInfoE);
        if (!res) {
            throw new BizException("评分失败");
        }
        //判断是否所有人都评分完成，如果完成则修改任务状态为完成
        List<ProjectTaskScoreInfoDO> listByTaskId = projectTaskScoreInfoRepository.getListByTaskId(info.getProjectTaskId());
        Boolean finish = false;
          BigDecimal averageScore = null;
        if(listByTaskId.size()==listByTaskId.stream().filter(item -> item.getScore() != null).count()){
            BigDecimal totalScore = listByTaskId.stream()
                    .map(ProjectTaskScoreInfoDO::getScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 计算平均分并保留两位小数
             averageScore = totalScore.divide(new BigDecimal(listByTaskId.size()),2,RoundingMode.HALF_UP);

            projectTaskRepository.updateScoreStatus(info.getProjectTaskId(), ScoreStatusEnum.SCORED.getCode(),averageScore);
            finish = true;
        }else{
            //修改为评分中
            projectTaskRepository.updateScoreStatus(info.getProjectTaskId(), ScoreStatusEnum.SCOREING.getCode(),null);
        }
        //删除对应待办
        try{
            //评分完成待办
            TodoListCompleteEvent event1 = new TodoListCompleteEvent();
            event1.setForeignSubsidiaryKey(info.getId());// 业务附表ID 没有附表时为foreignKey的值
            log.info("完成待办,请求：{}",info.getId());
            boolean b = todoListEventPusherUtil.sendMessageCompleteEvent(event1);
            log.info("完成待办,结果：{}",b);
        }catch (Exception e){
            log.error("删除待办失败",e);
        }



        if(finish && averageScore !=null){
            ProjectTaskDO infoByTaskId = projectTaskRepository.getInfoByTaskId(info.getProjectTaskId());
            DomainGroupDO infoByGroupId = domainGroupRepository.getInfoByGroupId(infoByTaskId.getDomainGroupId());

            //完成后，发送消息通知
            List<ProjectTaskGroupUserDO> projectTaskGroupUserDOList = projectTaskGroupUserRepository.getListByTaskId(info.getProjectTaskId());
            for (ProjectTaskGroupUserDO projectTaskGroupUserDO : projectTaskGroupUserDOList) {
                MessageSendCmd messageSendCmd = new MessageSendCmd();
                messageSendCmd.setBusinessId(UuidUtil.get32UUID());
                MessageTargetCmd messageTargetCmd = new MessageTargetCmd();
                messageTargetCmd.setUserId(projectTaskGroupUserDO.getUserId());
                messageSendCmd.setTargetCmd(messageTargetCmd);
                messageSendCmd.setSourceCode(messageConfig.getScoreResult());
                messageSendCmd.setNeedTokenEnum(false);
                Map<String, Object> sendParams = new HashMap<String, Object>();

                sendParams.put("SpecialTaskForceName", infoByGroupId.getDomainGroupName());
                sendParams.put("ResearchTask", infoByTaskId.getProjectName());
                sendParams.put("AverageScore", averageScore);
                messageSendCmd.setParams(sendParams);
                try{
                    log.info("评分完成消息提醒发送消息参数:messageSendCmd: {}", JSONUtil.toJsonStr(messageSendCmd));
                    SingleResponse<Boolean> d = messageFacade.send(messageSendCmd);
                    log.info("评分完成消息提醒发送消息结果:d: {}", JSONUtil.toJsonStr(d));

                }catch (Exception e) {
                    log.error("评分完成消息提醒发送消息异常:messageSendCmd: {}", JSONUtil.toJsonStr(messageSendCmd), e);
                }
            }
            //任务完成待办
            TodoListCompleteEvent event1 = new TodoListCompleteEvent();
            event1.setForeignSubsidiaryKey(infoByTaskId.getId());// 业务附表ID 没有附表时为foreignKey的值
            log.info("完成待办,请求：{}",infoByTaskId.getId());
            boolean b = todoListEventPusherUtil.sendMessageCompleteEvent(event1);
            log.info("完成待办,结果：{}",b);

        }
    }
}

