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.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.FireCheckListUpdateCmd;
import com.zcloud.fire.check.dto.FireCheckListUpdateStateCmd;
import com.zcloud.fire.check.persistence.dataobject.FireCheckListDO;
import com.zcloud.fire.check.persistence.dataobject.FireCheckListUserDO;
import com.zcloud.fire.check.persistence.repository.FireCheckListItemRepository;
import com.zcloud.fire.check.persistence.repository.FireCheckListRepository;
import com.zcloud.fire.check.persistence.repository.FireCheckListUserRepository;
import com.zcloud.gbscommon.todolistmq.TodoListEventPusherUtil;
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 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:10
 */
@Component
@AllArgsConstructor
@Slf4j
public class FireCheckListUpdateExe {
    private final FireCheckListGateway fireCheckListGateway;
    private final FireCheckListRepository fireCheckListRepository;
    private final FireCheckListItemGateway fireCheckListItemGateway;
    private final FireCheckListItemRepository fireCheckListItemRepository;
    private final FireCheckListUserRepository fireCheckListUserRepository;
    private final FireCheckListUserGateway fireCheckListUserGateway;
    private final TodoListEventPusherUtil todoListEventPusherUtil;
    @DubboReference
    private MessageFacade messageFacade;
    private MessageConfig messageConfig;
    @Transactional(rollbackFor = Exception.class)
    public void execute(FireCheckListUpdateCmd fireCheckListUpdateCmd) {
        //数据是否存在
        FireCheckListDO fireCheckListDO = fireCheckListRepository.getById(fireCheckListUpdateCmd.getId());
        if (fireCheckListDO == null) {
            throw new BizException("数据不存在");
        }
        FireCheckListE fireCheckListE = new FireCheckListE();
        BeanUtils.copyProperties(fireCheckListUpdateCmd, fireCheckListE);
        boolean res = fireCheckListGateway.update(fireCheckListE);
        if (!res) {
            throw new BizException("修改失败");
        }
        fireCheckListE.setFireCheckId(fireCheckListDO.getFireCheckId());
        //删除负责人信息再添加
        if(fireCheckListUpdateCmd.getUserIdList() != null) {
            fireCheckListUserRepository.deleteByFireCheckListId(fireCheckListDO.getFireCheckId());
            FireCheckListUserE fireCHeckListUserE = new FireCheckListUserE();
            List<FireCheckListUserE> fireCheckListUserEList = fireCHeckListUserE.initUser(fireCheckListUpdateCmd.getUserIdList(),fireCheckListUpdateCmd.getDepartmentId(),fireCheckListE);
            fireCheckListUserGateway.addBath(fireCheckListUserEList);

        }


        //删除所有消防器材
        fireCheckListItemRepository.deleteByFireCheckId(fireCheckListDO.getFireCheckId());
        //新增消防器材
        fireCheckListUpdateCmd.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("检查器材保存失败");
            }
        });
    }

    public void editState(FireCheckListUpdateStateCmd fireCheckListUpdateStateCmd) {
        FireCheckListE fireCheckListE = new FireCheckListE();
        BeanUtils.copyProperties(fireCheckListUpdateStateCmd, fireCheckListE);
        boolean res = fireCheckListGateway.update(fireCheckListE);
        if (!res) {
            throw new BizException("修改失败");
        }
        if(fireCheckListUpdateStateCmd.getState() == 2){
            //删除清单
            TodoListDeleteEvent event2 = new TodoListDeleteEvent();
            event2.setForeignSubsidiaryKey(fireCheckListUpdateStateCmd.getId());// 业务附表ID 没有附表时为foreignKey的值
            log.info("删除待办,请求：{}",fireCheckListUpdateStateCmd.getId());
            boolean b = todoListEventPusherUtil.sendMessageDeleteEvent(event2);
            log.info("删除待办,结果：{}",b);
        }

        if(fireCheckListUpdateStateCmd.getState() == 0){
            FireCheckListDO byId = fireCheckListRepository.getById(fireCheckListUpdateStateCmd.getId());
            List<FireCheckListUserDO> listByFireCheckId = fireCheckListUserRepository.getListByFireCheckId(byId.getFireCheckId());
            List<Long> userIdList = listByFireCheckId.stream().map(FireCheckListUserDO::getUserId).collect(Collectors.toList());
            //启用清单
            userIdList.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", byId.getFireCheckName());
                sendParams.put("checkPeriod", byId.getFireCheckTypeName());
                messageSendCmd.setParams(sendParams);
                log.info("启动清单,提醒发送消息参数:messageSendCmd: {}", JSONUtil.toJsonStr(messageSendCmd));
                SingleResponse<Boolean> d = messageFacade.send(messageSendCmd);
                log.info("启动清单,超期提醒发送消息结果:d: {}", JSONUtil.toJsonStr(d));
            });

        }
    }
}

