package com.zcloud.fire.check.command;

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.fire.check.domain.config.MessageConfig;
import com.zcloud.fire.check.domain.gateway.FireCheckListGateway;
import com.zcloud.fire.check.domain.gateway.FireCheckListItemGateway;
import com.zcloud.fire.check.domain.gateway.FireCheckListUserGateway;
import com.zcloud.fire.check.domain.model.FireCheckListE;
import com.zcloud.fire.check.domain.model.FireCheckListItemE;
import com.zcloud.fire.check.domain.model.FireCheckListUserE;
import com.zcloud.fire.check.dto.FireCheckListAddCmd;
import com.zcloud.fire.check.persistence.dataobject.UserDO;
import com.zcloud.fire.check.persistence.repository.FireCheckListRepository;
import com.zcloud.fire.check.persistence.repository.UserRepository;
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.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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-28 10:32:08
 */
@Component
@AllArgsConstructor
@Slf4j
public class FireCheckListAddExe {
    private final FireCheckListGateway fireCheckListGateway;
    private final FireCheckListRepository fireCheckListRepository;
    private final FireCheckListItemGateway fireCheckListItemGateway;
    private final FireCheckListUserGateway fireCheckListUserGateway;
    private final TodoListEventPusherUtil todoListEventPusherUtil;
    private final UserRepository userRepository;
    @DubboReference
    private MessageFacade messageFacade;
    private MessageConfig messageConfig;
    @Transactional(rollbackFor = Exception.class)
    public boolean execute(FireCheckListAddCmd cmd) {
        //可以是多个负责人
            FireCheckListE fireCheckListE = new FireCheckListE();
            BeanUtils.copyProperties(cmd, fireCheckListE);
            boolean res = false;
            try {
                res = fireCheckListGateway.add(fireCheckListE);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (!res) {
                throw new BizException("保存失败");
            }
            //新增负责人信息
             FireCheckListUserE fireCHeckListUserE = new FireCheckListUserE();
             List<FireCheckListUserE> fireCheckListUserEList = fireCHeckListUserE.initUser(cmd.getUserIdList(),cmd.getDepartmentId(),fireCheckListE);
             fireCheckListUserGateway.addBath(fireCheckListUserEList);
            //新增检查项
            cmd.getFireCheckListItemAddCmdList().forEach(fireCheckListItemAddCmd -> {
                FireCheckListItemE fireCheckListItemE = new FireCheckListItemE();
                BeanUtils.copyProperties(fireCheckListItemAddCmd, fireCheckListItemE);
                fireCheckListItemE.setFireCheckId(fireCheckListE.getFireCheckId());
                boolean itemRes = fireCheckListItemGateway.add(fireCheckListItemE);
                if (!itemRes) {
                    throw new BizException("检查器材保存失败");
                }
            });
            //TODO 消息提醒
            try{

                List<TodoListAddEvent> todoListAddEventList = new ArrayList<>();
                cmd.getUserIdList().forEach(userId -> {
                    MessageSendCmd messageSendCmd = new MessageSendCmd();
                    messageSendCmd.setBusinessId(UuidUtil.get32UUID());
                    MessageTargetCmd messageTargetCmd = new MessageTargetCmd();
                    messageTargetCmd.setUserId(userId);
                    messageSendCmd.setTargetCmd(messageTargetCmd);
                    messageSendCmd.setSourceCode(messageConfig.getFireCheckPending());
                    messageSendCmd.setNeedTokenEnum(false);
                    Map<String, Object> sendParams = new HashMap<String, Object>();
                    sendParams.put("FirefightinglistName", cmd.getFireCheckName());
                    sendParams.put("checkPeriod", cmd.getFireCheckTypeName());
                    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(fireCheckListE.getId()); // 业务表ID -申请
                    event.setForeignSubsidiaryKey(fireCheckListE.getId()); // 业务附表ID 没有附表时为foreignKey的值
                    event.setReceiveUser(userId);// user表ID
                    event.setPcFlag(0); // 是否PC端待办 1是 0否
                    event.setAppFlag(1); // 是否APP端待办 1是 0否
                    event.setOtherParams(new JSONObject());
                    todoListAddEventList.add(event);
                });

                TodoListAddBatchEvent event3 = new TodoListAddBatchEvent();
                event3.setTodoListAddEventList(todoListAddEventList);
                log.info("创建清单,待排查待办参数:event3: {}", JSONUtil.toJsonStr(event3));
                boolean b = todoListEventPusherUtil.sendMessageAddBatchEvent(event3);
                log.info("创建清单,待排查待办结果:{}", JSONUtil.toJsonStr(b));
            }catch (Exception e){
                log.error("发送消息异常",e);
            }
        return true;
    }
}

