package com.zcloud.domain.command;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
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.command.convertor.ProjectTaskGroupUserCoConvertor;
import com.zcloud.domain.command.convertor.ProjectTaskInfoCoConvertor;
import com.zcloud.domain.command.convertor.ProjectTaskScoreInfoCoConvertor;
import com.zcloud.domain.domain.config.MessageConfig;
import com.zcloud.domain.domain.enums.CommonFlagEnum;
import com.zcloud.domain.domain.enums.ProjectTaskExecuteStatusEnum;
import com.zcloud.domain.domain.gateway.ProjectTaskGateway;
import com.zcloud.domain.domain.model.ProjectTaskE;
import com.zcloud.domain.dto.ProjectTaskAddCmd;
import com.zcloud.domain.dto.ProjectTaskGroupUserAddCmd;
import com.zcloud.domain.dto.ProjectTaskInfoAddCmd;
import com.zcloud.domain.dto.ProjectTaskScoreInfoAddCmd;
import com.zcloud.domain.persistence.dataobject.*;
import com.zcloud.domain.persistence.repository.*;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
import com.zcloud.gbscommon.todolistmq.event.TodoListAddBatchEvent;
import com.zcloud.gbscommon.todolistmq.event.TodoListAddEvent;
import com.zcloud.gbscommon.utils.Tools;
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.util.*;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2026-01-29 11:28:41
 */
@Component
@AllArgsConstructor
@Slf4j
public class ProjectTaskAddExe {
    private final ProjectTaskGateway projectTaskGateway;
    private final ProjectTaskGroupUserCoConvertor projectTaskGroupUserCoConvertor;
    private final ProjectTaskGroupUserRepository projectTaskGroupUserRepository;
    private final ProjectTaskInfoCoConvertor projectTaskInfoCoConvertor;
    private final ProjectTaskInfoRepository projectTaskInfoRepository;
    private final ProjectTaskScoreInfoRepository projectTaskScoreInfoRepository;
    private final ProjectTaskScoreInfoCoConvertor projectTaskScoreInfoCoConvertor;
    private final DomainDepartmentRepository domainDepartmentRepository;
    private final TodoListEventPusherUtil todoListEventPusherUtil;
    private final DomainGroupRepository domainGroupRepository;
    private final CorpInfoRepository corpInfoRepository;
    @DubboReference
    private MessageFacade messageFacade;
    @Resource
    private MessageConfig messageConfig;
    @Transactional(rollbackFor = Exception.class)
    public boolean execute(ProjectTaskAddCmd cmd) {
        ProjectTaskE projectTaskE = new ProjectTaskE();
        BeanUtils.copyProperties(cmd, projectTaskE);
        boolean res = false;
        try {
            res = projectTaskGateway.add(projectTaskE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        //新增详细信息
        List<ProjectTaskInfoAddCmd> projectTaskInfoAddCmdList = cmd.getProjectTaskInfoAddCmdList();
        List<ProjectTaskGroupUserAddCmd> projectTaskGroupUserAddCmdList = cmd.getProjectTaskGroupUserAddCmdList();
        List<ProjectTaskScoreInfoAddCmd> projectTaskScoreInfoAddCmdList = cmd.getProjectTaskScoreInfoAddCmdList();
        if(CollUtil.isEmpty(projectTaskGroupUserAddCmdList) && CollUtil.isEmpty(projectTaskScoreInfoAddCmdList)){
            throw new BizException("请选择对应人员信息");
        }
        if(CollUtil.isNotEmpty(projectTaskInfoAddCmdList)){

            List<ProjectTaskInfoDO> projectTaskInfoDOList =projectTaskInfoCoConvertor.converCmdsToDOs(projectTaskInfoAddCmdList);
            projectTaskInfoDOList.forEach(
                    info -> {
                        info.setProjectTaskId(projectTaskE.getProjectTaskId());
                        info.setProjectTaskInfoId(Tools.get32UUID());
                    }
            );
            projectTaskInfoRepository.saveBatch(projectTaskInfoDOList);
        }
        if(CollUtil.isNotEmpty(projectTaskGroupUserAddCmdList)){
            List<ProjectTaskGroupUserDO> projectTaskGroupUserDOList =projectTaskGroupUserCoConvertor.converCmdsToDOs(projectTaskGroupUserAddCmdList);
            projectTaskGroupUserDOList.forEach(
                    info -> {
                        info.setProjectTaskId(projectTaskE.getProjectTaskId());
                        info.setExecuteCorpinfoId(projectTaskE.getExecuteCorpinfoId());
                        info.setDomainGroupId(projectTaskE.getDomainGroupId());
                        info.setProjectTaskGroupUserId(Tools.get32UUID());
                    }
            );
            projectTaskGroupUserRepository.saveBatch(projectTaskGroupUserDOList);
        }

        //新增领域组人员信息
        if(CollUtil.isNotEmpty(projectTaskScoreInfoAddCmdList)){
            //新增评审人员信息
            List<ProjectTaskScoreInfoDO> projectTaskScoreInfoDOList = projectTaskScoreInfoCoConvertor.converCmdsToDOs(projectTaskScoreInfoAddCmdList);
            projectTaskScoreInfoDOList.forEach(
                    info -> {
                        info.setProjectTaskId(projectTaskE.getProjectTaskId());
                        info.setProjectTaskScoreInfoId(Tools.get32UUID());
                    }
            );
            projectTaskScoreInfoRepository.saveBatch(projectTaskScoreInfoDOList);
        }

        //修改状态
        if (CollUtil.isNotEmpty(projectTaskGroupUserAddCmdList) && CollUtil.isNotEmpty(projectTaskScoreInfoAddCmdList)) {
            // 两个列表都不为空，设置为WAIT_PERFECT状态
            //如果当前时间大于开始时间，状态是开始状态
            if (new Date().compareTo(projectTaskE.getExecutedStartDate()) >= 0) {
                projectTaskE.setExecuteStatus(ProjectTaskExecuteStatusEnum.EXECUTING.getCode());
            }else{
                projectTaskE.setExecuteStatus(ProjectTaskExecuteStatusEnum.WAIT_PERFECT.getCode());
            }
        } else if (CollUtil.isNotEmpty(projectTaskGroupUserAddCmdList) && CollUtil.isEmpty(projectTaskScoreInfoAddCmdList)) {
            // 只有group user列表不为空，等待评分设置
            projectTaskE.setExecuteStatus(ProjectTaskExecuteStatusEnum.SCORE_WAIT_SET.getCode());
            //通知department
            String domainDepartmentId = projectTaskE.getDomainDepartmentId();
            DomainDepartmentDO infoByUUID = domainDepartmentRepository.getInfoByUUID(domainDepartmentId);
            messageNotice(infoByUUID.getMasterUserId(),messageConfig.getScoreTaskAssign(),projectTaskE.getId(),null);
            //股份端主账号,写死
                messageNotice(2018148156138532864L,messageConfig.getScoreTaskAssign(),projectTaskE.getId(),null);


        } else if (CollUtil.isEmpty(projectTaskGroupUserAddCmdList) && CollUtil.isNotEmpty(projectTaskScoreInfoAddCmdList)) {
            // 只有score info列表不为空，等待项目组设置
            //通知group
            projectTaskE.setExecuteStatus(ProjectTaskExecuteStatusEnum.PROJECT_GROUP_WAIT_SET.getCode());
            String domainGroupId = projectTaskE.getDomainGroupId();
            DomainGroupDO info = domainGroupRepository.getInfoByGroupId(domainGroupId);
            DomainDepartmentDO infoByUUID = domainDepartmentRepository.getInfoByUUID(projectTaskE.getDomainDepartmentId());

            Map<String, Object> sendParams = new HashMap<String, Object>();
            sendParams.put("DomainDepartment", infoByUUID.getMasterDepartmentName());
            messageNotice(info.getTeamUserId(),messageConfig.getTaskAssign(),projectTaskE.getId(),sendParams);
            messageNotice(info.getCorpinfoId(),messageConfig.getTaskAssign(),projectTaskE.getId(),sendParams);
        }

        projectTaskGateway.update(projectTaskE);



        return true;

    }
//  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);
    private void messageNotice(Long userId,String sourceCode,Long foreignKey,Map<String, Object> sendParams) {
        //消息通知
        try{

            MessageSendCmd messageSendCmd = new MessageSendCmd();
            messageSendCmd.setBusinessId(UuidUtil.get32UUID());
            MessageTargetCmd messageTargetCmd = new MessageTargetCmd();
            messageTargetCmd.setUserId(userId);
            messageSendCmd.setTargetCmd(messageTargetCmd);
            messageSendCmd.setSourceCode(sourceCode);
            messageSendCmd.setNeedTokenEnum(false);
            messageSendCmd.setParams(sendParams);

            log.info("评分完成消息提醒发送消息参数:messageSendCmd: {}", JSONUtil.toJsonStr(messageSendCmd));
            SingleResponse<Boolean> d = messageFacade.send(messageSendCmd);
            log.info("评分完成消息提醒发送消息结果:d: {}", JSONUtil.toJsonStr(d));

            // 发送待办
            TodoListAddEvent event = new TodoListAddEvent();
            event.setTitle("您有一条【专项领域】待处理");
            event.setContent("待开始");
            event.setForeignKey(foreignKey); // 业务表ID -申请
            event.setForeignSubsidiaryKey(foreignKey); // 业务附表ID 没有附表时为foreignKey的值
            event.setReceiveUser(userId);// user表ID
            event.setPcFlag(1); // 是否PC端待办 1是 0否
            event.setAppFlag(0); // 是否APP端待办 1是 0否
            event.setOtherParams(new JSONObject());

            todoListEventPusherUtil.sendMessageAddEvent( event);
        }catch (Exception e) {
            log.error("评分完成消息提醒发送消息异常:", e);
        }
    }
}

