package com.zcloud.fire.check.command.query;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
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.fire.check.command.convertor.*;
import com.zcloud.fire.check.domain.config.MessageConfig;
import com.zcloud.fire.check.domain.enums.HiddenCheckTypeEnum;
import com.zcloud.fire.check.domain.model.FireCheckListE;
import com.zcloud.fire.check.dto.*;
import com.zcloud.fire.check.dto.clientobject.*;
import com.zcloud.fire.check.persistence.FireCheckPointListDO;
import com.zcloud.fire.check.persistence.dataobject.*;
import com.zcloud.fire.check.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.todolistmq.event.TodoListDeleteEvent;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.gbscommon.utils.UuidUtil;
import com.zcloud.gbscommon.zcloudhidden.face.ZcloudHiddenFacade;
import com.zcloud.gbscommon.zcloudhidden.request.HiddenStatisticsQry;
import com.zcloud.gbscommon.zcloudhidden.response.HiddenListCO;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-28 10:32:09
 */
@Component
@AllArgsConstructor
@Slf4j
public class FireCheckListQueryExe {
    private final FireCheckListRepository fireCheckListRepository;
    private final FireCheckListCoConvertor fireCheckListCoConvertor;
    private final FireCheckListItemRepository fireCheckListItemRepository;
    private final FireDeviceRepository fireDeviceRepository;
    private final FireDeviceCoConvertor fireDeviceCoConvertor;
    private final FireRegionRepository fireRegionRepository;
    private final FirePointRepository firePointRepository;
    private final FireCheckStandardRepository fireCheckStandardRepository;
    private final FireCheckListUserRepository fireCheckListUserRepository;
    private final FireCheckRecordRepository fireCheckRecordRepository;
    private final FireCheckRecordPointRepository fireCheckRecordPointRepository;
    private final FireCheckStandardCoConvertor fireCheckStandardCoConvertor;
    private final FireCheckRecordDeviceRepository fireCheckRecordDeviceRepository;
    private final FireCheckRecordDeviceCoConvertor fireCheckRecordDeviceCoConvertor;
    private final FireCheckRecordHiddenRepository fireCheckRecordHiddenRepository;
    private final FireCheckRecordHiddenCoConvertor fireCheckRecordHiddenCoConvertor;
    private final FireCheckListUserCoConvertor fireCheckListUserCoConvertor;
    private final TodoListEventPusherUtil todoListEventPusherUtil;
    private final UserRepository userRepository;
    @DubboReference
    private ZcloudHiddenFacade zcloudHiddenFacade;
    @DubboReference
    private MessageFacade messageFacade;
    private MessageConfig messageConfig;

    public PageResponse<FireCheckListScreenCO> screenList(FireCheckListScreenQry qry) {
        if (qry == null) {
            qry = new FireCheckListScreenQry();
        }
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.screenList(params);
        List<FireCheckListScreenCO> result = new ArrayList<>();
        for (FireCheckListDO item : pageResponse.getData()) {
            FireCheckListScreenCO co = new FireCheckListScreenCO();
            BeanUtils.copyProperties(item, co);
            Long checkCycleCount = parseLong(item.getCheckCycleCount());
            co.setCheckCycleCount(checkCycleCount);
            FireCheckListE info = new FireCheckListE();
            info.getCheckRecordPeriod(item.getFireCheckType(), LocalDateTime.now());
            co.setCheckStartTime(info.getPeriodStart());
            co.setCheckEndTime(info.getPeriodEnd());
            if (checkCycleCount > 0) {
                co.setCheckStatus(2);
                co.setCheckStatusName("已检查");
            } else {
                co.setCheckStatus(1);
                co.setCheckStatusName("未检查");
            }
            result.add(co);
        }
        return PageResponse.of(result, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    private Long parseLong(String value) {
        if (StringUtils.isEmpty(value)) {
            return 0L;
        }
        return Long.valueOf(value);
    }

    /**
     * 分页
     *
     * @param fireCheckListPageQry
     * @return
     */
    public PageResponse<FireCheckListCO> execute(FireCheckListPageQry fireCheckListPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(fireCheckListPageQry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.listPage(params);
        List<FireCheckListCO> examCenterCOS = fireCheckListCoConvertor.converDOsToCOs(pageResponse.getData());
        //按照负责人搜索的话，需要补充名字
        if(StringUtils.isNotEmpty(fireCheckListPageQry.getUserName())){
            //补充完整的用户负责人
//            examCenterCOS.stream()
            List<String> fireCheckIdList = examCenterCOS.stream().map(FireCheckListCO::getFireCheckId).collect(Collectors.toList());
            List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserNameByFireCheckIdList(fireCheckIdList);
            //fireCheckListUserDOList转换为key value map
            Map<String, String> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                    .collect(Collectors.groupingBy(
                            FireCheckListUserDO::getFireCheckId,
                            Collectors.mapping(FireCheckListUserDO::getUserName, Collectors.joining(","))));
            examCenterCOS.forEach(fireCheckListCO->{
                fireCheckListCO.setUserName(fireCheckListUserDONameMap.getOrDefault(fireCheckListCO.getFireCheckId(), ""));

            });
        }
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public FireCheckListCO getInfoById(Long id) {
        FireCheckListDO fireCheckListDO = fireCheckListRepository.getInfoById(id);
        if (fireCheckListDO == null) {
            throw new RuntimeException("点位检查表不存在");
        }
        FireCheckListCO fireCheckListCO = new FireCheckListCO();
        BeanUtils.copyProperties(fireCheckListDO, fireCheckListCO);
        //fireCheckListCO设置检查信息
        List<FireCheckListItemDO> fireCheckListItemDOList = fireCheckListItemRepository.listByFireCheckId(fireCheckListDO.getFireCheckId());
        if (CollUtil.isEmpty(fireCheckListItemDOList)) {
            return fireCheckListCO;
        }
        //获取所有id
        List<String> fireCheckListItemIdList = fireCheckListItemDOList.stream().map(FireCheckListItemDO::getFireDeviceId).collect(Collectors.toList());
        //获取所有的消防器材信息
        Map<String, Object> params = new HashMap<>();
        params.put("fireDeviceIdList", fireCheckListItemIdList);
        List<FireDeviceDO> fireDeviceDOList = fireDeviceRepository.getAllList(params);
        List<FireDeviceCO> examCenterCOS = fireDeviceCoConvertor.converDOsToCOs(fireDeviceDOList);
        fireCheckListCO.setFireDeviceCOList(examCenterCOS);
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListByFireCheckId(fireCheckListDO.getFireCheckId());
        List<FireCheckListUserCO> fireCheckListUserCOS = fireCheckListUserCoConvertor.converDOsToCOs(fireCheckListUserDOList);
        fireCheckListCO.setFireCheckListUserCOList(fireCheckListUserCOS);

        return fireCheckListCO;
    }

    public PageResponse<FireCheckListCO> appCheckList(FireCheckListPageQry qry) {

        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.appCheckList(params);
        List<FireCheckListCO> examCenterCOS = fireCheckListCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<String> fireCheckIdList = examCenterCOS.stream().map(FireCheckListCO::getFireCheckId).collect(Collectors.toList());
        //补充完整的用户负责人
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserNameByFireCheckIdList(fireCheckIdList);
        //fireCheckListUserDOList转换为key value map
        Map<String, String> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                .collect(Collectors.groupingBy(
                        FireCheckListUserDO::getFireCheckId,
                        Collectors.mapping(FireCheckListUserDO::getUserName, Collectors.joining(","))));
        //获取所有的检查项目信息
        List<FireCheckListItemStatisticDO> fireCheckListItemStatisticDOList = fireCheckListItemRepository.statisticListByFireCheckIdList(fireCheckIdList);
        //fireCheckListItemStatisticDOList转换为key value map

        Map<String, Long> fireCheckListItemStatisticDOMap = fireCheckListItemStatisticDOList.stream().collect(Collectors.toMap(FireCheckListItemStatisticDO::getFireCheckId, FireCheckListItemStatisticDO::getFireCheckItemCount));
        //补充点位数和排查周期
        for (FireCheckListCO fireCheckListCO : examCenterCOS) {
            fireCheckListCO.setFireCheckItemCount(fireCheckListItemStatisticDOMap.getOrDefault(fireCheckListCO.getFireCheckId(), 0L));
            FireCheckListE info = new FireCheckListE();
            info.getCheckRecordPeriod(fireCheckListCO.getFireCheckType(), LocalDateTime.now());
            fireCheckListCO.setCheckStartTime(info.getPeriodStart());
            fireCheckListCO.setCheckEndTime(info.getPeriodEnd());
            fireCheckListCO.setUserName(fireCheckListUserDONameMap.getOrDefault(fireCheckListCO.getFireCheckId(), ""));
        }
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());


    }
    public Integer checkListCount(FireCheckListPageQry qry) {

        //待办数
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.appCheckList(params);

        //打回的数量

        Map<String, Object> backParams = PageQueryHelper.toHashMap(qry);
        backParams.put("userId",AuthContext.getUserId());
        PageResponse<FireCheckListDO> backPageResponse = fireCheckListRepository.getBackChecKList(backParams);


        if (CollUtil.isEmpty(pageResponse.getData()) && CollUtil.isEmpty(backPageResponse.getData())) {
            return 0;
        }else{
            return pageResponse.getTotalCount()+backPageResponse.getTotalCount();
        }
    }


    public PageResponse<RiskDistributionCO> riskDistribution(RiskDistributionPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<RiskDistributionDO> pageResponse = fireCheckListRepository.riskDistribution(params);
        List<RiskDistributionCO> examCenterCOS = fireCheckListCoConvertor.converStatictisDOsToCOs(pageResponse.getData());
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public RiskDistributionStasticCO riskDistributionStatistic() {
        RiskDistributionStasticCO riskDistributionStasticCO = new RiskDistributionStasticCO();
        riskDistributionStasticCO.setFireRegionCount(fireRegionRepository.getFireRegionCount());
        riskDistributionStasticCO.setFirePointCount(firePointRepository.getFirePointCount());
        riskDistributionStasticCO.setFireDeviceCount(fireDeviceRepository.getFireDeviceCount());
        return riskDistributionStasticCO;
    }

    public PageResponse<PointDistributionCO> pointDistributionStatistic(PointDistributionPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<PointDistributionDO> pageResponse = fireCheckListRepository.pointDistribution(params);
        List<PointDistributionCO> examCenterCOS = fireCheckListCoConvertor.converPointDistributionDOsToCOs(pageResponse.getData());
        //增加检查标准
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        //获取所有的检查类型
        List<String> fireCheckTypeList = examCenterCOS.stream().map(PointDistributionCO::getFireDeviceType).distinct().collect(Collectors.toList());


        List<FireCheckStandardDO> fireCheckStandardDOList = fireCheckStandardRepository.getCheckStandardList(fireCheckTypeList);

        Map<String, List<String>> fireCheckListItemStatisticDOMap = fireCheckStandardDOList.stream()
                .collect(Collectors.groupingBy(
                        FireCheckStandardDO::getFireDeviceType,
                        Collectors.mapping(FireCheckStandardDO::getFireCheckStandardItem, Collectors.toList())
                ));

        //补充检查标准
        for (PointDistributionCO pointDistributionCO : examCenterCOS) {
            List<String> fireCheckTypeItemList = fireCheckListItemStatisticDOMap.get(pointDistributionCO.getFireDeviceType());
            if (fireCheckTypeItemList != null) {
                pointDistributionCO.setFireCheckTypeItemList(fireCheckTypeItemList);
            }
        }
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public List<FireCheckPointListCO> getCheckPointList(CheckPointListQry qry) {

        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        List<FireCheckPointListDO> fireCheckPointListDOList = fireCheckListRepository.getCheckPointList(params);
        if (CollUtil.isEmpty(fireCheckPointListDOList)) {
            return Collections.emptyList();
        }
        //过滤标准数量为0的
        List<FireCheckPointListDO> missingTypes = fireCheckPointListDOList.stream().filter(item -> item.getStandardCount() == 0).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(missingTypes)) {
            //获取类型名称，逗号分隔
            List<String> fireDeviceTypeNameList = missingTypes.stream().map(FireCheckPointListDO::getFireDeviceTypeName).distinct().collect(Collectors.toList());
            throw new BizException(fireDeviceTypeNameList + "无检查标准,无法检查");
        }
        // 获取检查标准数据
        List<String> fireDeviceTypeList = fireCheckPointListDOList.stream().map(FireCheckPointListDO::getFireDeviceType).collect(Collectors.toList());

        List<FireCheckStandardDO> fireCheckStandardDOList = fireCheckStandardRepository.getCheckStandardList(fireDeviceTypeList);
        // 如果没有找到任何检查标准，抛出异常
        if (CollUtil.isEmpty(fireCheckStandardDOList)) {
            throw new BizException("所有检查设备没有检查标准");
        }
        // 构建检查标准映射
        List<FireCheckStandardCO> fireCheckStandardCOList = fireCheckStandardCoConvertor.converDOsToCOs(fireCheckStandardDOList);
        Map<String, List<FireCheckStandardCO>> fireCheckStandardMap = fireCheckStandardCOList.stream()
                .collect(Collectors.groupingBy(FireCheckStandardCO::getFireDeviceType));


        //fireCheckPointListDOList按照pointid进行分组
        Map<String, List<FireCheckPointListDO>> fireCheckPointListDOMap = fireCheckPointListDOList.stream().collect(Collectors.groupingBy(FireCheckPointListDO::getFirePointId));

        //获取隐患相关信息
        List<FireCheckRecordHiddenDO> fireCheckRecordHiddenDOList = fireCheckRecordHiddenRepository.getHiddenListByFireCheckId(qry.getFireCheckId(), HiddenCheckTypeEnum.CHECK_ITEM_HIDDEN.getCode());
        List<String> hiddenIdList = fireCheckRecordHiddenDOList.stream().map(FireCheckRecordHiddenDO::getHiddenId).collect(Collectors.toList());
        MultiResponse<HiddenListCO> hiddenListCOMultiResponse = null;
        if(CollUtil.isNotEmpty(hiddenIdList)){
            HiddenStatisticsQry hiddenStatisticsQry = new HiddenStatisticsQry();
            hiddenStatisticsQry.setHiddenIds(hiddenIdList);
            //获取下所有的检查项隐患信息，根据隐患id查询
            try {
                log.info("根据隐患id查询未整改隐患数：请求hiddenStatisticsQry:{}", hiddenStatisticsQry);
                hiddenListCOMultiResponse = zcloudHiddenFacade.queryHiddenCountByForeignKey(hiddenStatisticsQry);
                log.info("根据隐患id查询未整改隐患数：响应hiddenListCOMultiResponse:{}", JSONUtil.toJsonStr( hiddenListCOMultiResponse));
            }catch (Exception e){
                log.error("根据隐患id查询未整改隐患数失败:{}",e.getMessage());
            }
        }
        //checkRecordHiddenDOList根据事故id进行分组
        Map<String, List<FireCheckRecordHiddenDO>> fireDeviceCheckRecordHiddenDOMap = fireCheckRecordHiddenDOList.stream().collect(Collectors.groupingBy(FireCheckRecordHiddenDO::getFireDeviceId));


        // 处理设备类型名和设备编码的聚合显示
        List<FireCheckPointListCO> result = new ArrayList<>();
        for (Map.Entry<String, List<FireCheckPointListDO>> entry : fireCheckPointListDOMap.entrySet()) {
            List<FireCheckPointListDO> fireCheckPointListDOS = entry.getValue();
            if (CollUtil.isEmpty(fireCheckPointListDOS)) {
                continue;
            }
            FireCheckPointListCO node = new FireCheckPointListCO();
            node.setFireRegionId(fireCheckPointListDOS.get(0).getFireRegionId());
            node.setFireRegionCode(fireCheckPointListDOS.get(0).getFireRegionCode());
            node.setFireRegionName(fireCheckPointListDOS.get(0).getFireRegionName());
            node.setFirePointId(fireCheckPointListDOS.get(0).getFirePointId());
            node.setFirePointCode(fireCheckPointListDOS.get(0).getFirePointCode());
            node.setFirePointName(fireCheckPointListDOS.get(0).getFirePointName());
            String deviceTypeNames = fireCheckPointListDOS.stream()
                    .map(FireCheckPointListDO::getFireDeviceTypeName)
                    .filter(StringUtils::isNotEmpty)
                    .distinct()
                    .collect(Collectors.joining(","));
            node.setFireDeviceTypeName(deviceTypeNames);

            // 聚合设备编码
            String deviceCodes = fireCheckPointListDOS.stream()
                    .map(FireCheckPointListDO::getFireDeviceCode)
                    .filter(StringUtils::isNotEmpty)
                    .distinct()
                    .collect(Collectors.joining(","));
            node.setFireDeviceCode(deviceCodes);
            List<FireCheckPointDeviceListCO> fireCheckPointDeviceListCOList = new ArrayList<>();
            //处理设备信息 ,并且判断设备下是否存在隐患信息
            MultiResponse<HiddenListCO> finalHiddenListCOMultiResponse = hiddenListCOMultiResponse;
            fireCheckPointListDOS.forEach(info -> {
                FireCheckPointDeviceListCO childNode = new FireCheckPointDeviceListCO();
                childNode.setFireRegionId(info.getFireRegionId());
                childNode.setFireRegionCode(info.getFireRegionCode());
                childNode.setFireRegionName(info.getFireRegionName());
                childNode.setFirePointId(info.getFirePointId());
                childNode.setFirePointName(info.getFirePointName());
                childNode.setFirePointCode(info.getFirePointCode());
                childNode.setFireDeviceId(info.getFireDeviceId());
                childNode.setFireDeviceType(info.getFireDeviceType());
                childNode.setFireDeviceCode(info.getFireDeviceCode());
                childNode.setFireDeviceTypeName(info.getFireDeviceTypeName());
                if (fireCheckStandardMap != null && !fireCheckStandardMap.isEmpty()) {
                    childNode.setFireCheckStandardCOList(fireCheckStandardMap.get(info.getFireDeviceType()));
                }
                if (finalHiddenListCOMultiResponse !=null && CollUtil.isNotEmpty(finalHiddenListCOMultiResponse.getData())) {
                    List<String> hiddenIds = finalHiddenListCOMultiResponse.getData().stream().map(HiddenListCO::getHiddenId).collect(Collectors.toList());
                    List<FireCheckRecordHiddenDO> hiddenList = fireDeviceCheckRecordHiddenDOMap.get(childNode.getFireDeviceId());
                    if (CollUtil.isNotEmpty(hiddenList)) {
                        List<String> hiddenIdsInDevice = hiddenList.stream().map(FireCheckRecordHiddenDO::getHiddenId).collect(Collectors.toList());
                        //如果hiddenIdsInRiskPoint在hiddenIds中，则存在隐患
                        if (CollUtil.containsAny(hiddenIdsInDevice, hiddenIds)) {
                            childNode.setHasHidden(true);
                        } else {
                            childNode.setHasHidden(false);
                        }
                    }
                }


                fireCheckPointDeviceListCOList.add(childNode);
            });
            node.setFireCheckPointDeviceListCOList(fireCheckPointDeviceListCOList);
            result.add(node);
        }

        //查找是否有已完成的检查，有的话，查出来
        // 查找是否有未完成的检查记录
        FireCheckRecordDO fireCheckRecordDO = fireCheckRecordRepository.getNoFinishedInfoId(qry.getFireCheckId());
        if (fireCheckRecordDO != null) {
            List<FireCheckRecordPointDO> fireCheckRecordPointDOList = fireCheckRecordPointRepository.getInfoByFireCheckRecordId(fireCheckRecordDO.getFireRecordId());
            List<FireCheckRecordDeviceDO> checkRecordDeviceList = fireCheckRecordDeviceRepository.getCheckRecordDeviceList(fireCheckRecordDO.getFireRecordId());
            Map<String, List<FireCheckRecordDeviceDO>> checkRecordDeviceMap = checkRecordDeviceList.stream().collect(Collectors.groupingBy(FireCheckRecordDeviceDO::getFireRecordPointId));
            if (CollUtil.isNotEmpty(fireCheckRecordPointDOList)) {
                Map<String, FireCheckRecordPointDO> fireCheckRecordPointDOMap = fireCheckRecordPointDOList.stream()
                        .collect(Collectors.toMap(FireCheckRecordPointDO::getFirePointId, Function.identity()));

                //获取隐患信息
                //fireCheckRecordHiddenDOList 按照设备id key value对象

                Map<String, FireCheckRecordHiddenDO> fireCheckRecordHiddenDOMap = fireCheckRecordHiddenDOList.stream()
                        .collect(Collectors.toMap(FireCheckRecordHiddenDO::getFireRecordDeviceId, Function.identity()));


                result.forEach(fireCheckPointListCO -> {
                    FireCheckRecordPointDO recordPointDO = fireCheckRecordPointDOMap.get(fireCheckPointListCO.getFirePointId());
                    fireCheckPointListCO.setFireRecordId(fireCheckRecordDO.getFireRecordId());
                    if (recordPointDO != null) {
                        fireCheckPointListCO.setFireRecordPointId(recordPointDO.getFireRecordPointId());
                        fireCheckPointListCO.setCheckedFlag(recordPointDO.getCheckedFlag());
                        fireCheckPointListCO.setId(recordPointDO.getId());
                        List<FireCheckRecordDeviceDO> fireCheckRecordDeviceDOS = checkRecordDeviceMap.get(recordPointDO.getFireRecordPointId());
                        //转换
                        List<FireCheckRecordDeviceCO> fireCheckPointDeviceListCOList =fireCheckRecordDeviceCoConvertor.converDOsToDeviceCOs(fireCheckRecordDeviceDOS);
                        //查找是否有隐患信息

                        fireCheckPointDeviceListCOList.forEach(info->{
                            FireCheckRecordHiddenDO fireCheckRecordHiddenDO = fireCheckRecordHiddenDOMap.get(info.getFireRecordDeviceId());
                            if(fireCheckRecordHiddenDO != null){
                                info.setFireCheckRecordHiddenCO(fireCheckRecordHiddenCoConvertor.convertToCO(fireCheckRecordHiddenDO));
                            }
                        });
                        fireCheckPointListCO.setFireCheckRecordDeviceStatusList(fireCheckPointDeviceListCOList);
                    }
                });
            }
        }
        return result;
    }

    private void checkFireDeviceStandard(List<FireCheckPointListDO> fireCheckPointListDOList) {
        // 获取检查标准数据
        Map<String, String> fireDeviceTypeNameMap = fireCheckPointListDOList.stream()
                .collect(Collectors.toMap(
                        FireCheckPointListDO::getFireDeviceType,
                        FireCheckPointListDO::getFireDeviceTypeName,
                        (existing, replacement) -> existing)); // 处理重复key的情况
        if (CollUtil.isEmpty(fireDeviceTypeNameMap)) {
            throw new BizException("检查设备没有检查标准");
        }

        List<String> fireDeviceTypeList = new ArrayList<>(fireDeviceTypeNameMap.keySet());
        List<FireCheckStandardDO> fireCheckStandardDOList = fireCheckStandardRepository.getCheckStandardList(fireDeviceTypeList);

        // 如果没有找到任何检查标准，抛出异常
        if (CollUtil.isEmpty(fireCheckStandardDOList)) {
            throw new BizException("所有检查设备没有检查标准");
        }
        // 构建检查标准映射
        List<FireCheckStandardCO> fireCheckStandardCOList = fireCheckStandardCoConvertor.converDOsToCOs(fireCheckStandardDOList);
        Map<String, List<FireCheckStandardCO>> fireCheckStandardMap = fireCheckStandardCOList.stream()
                .collect(Collectors.groupingBy(FireCheckStandardCO::getFireDeviceType));

        // 检查是否存在没有检查标准的设备类型
        Set<String> availableTypes = fireCheckStandardMap.keySet();
        List<String> missingTypes = fireDeviceTypeList.stream()
                .filter(type -> !availableTypes.contains(type))
                .map(fireDeviceTypeNameMap::get)
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(missingTypes)) {
            throw new BizException("检查设备没有检查标准：" + missingTypes);
        }
    }


    public PageResponse<FireBackCheckListCO> getBackChecKList(FireBackCheckListPageQry qry) {
        if (qry.getUserId() == null) {
            qry.setUserId(AuthContext.getUserId());
        }
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);

        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.getBackChecKList(params);
        List<FireBackCheckListCO> fireBackCheckListCOList = fireCheckListCoConvertor.converDOsToBackCOs(pageResponse.getData());

        if (CollUtil.isEmpty(fireBackCheckListCOList)) {
            return PageResponse.of(fireBackCheckListCOList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());

        }
        //补充检查数和完整检查人

        List<String> fireCheckIdList = fireBackCheckListCOList.stream().map(FireBackCheckListCO::getFireCheckId).collect(Collectors.toList());
        //补充完整的用户负责人
        List<FireCheckListStatisticDO> fireCheckListStatisticDOList = fireCheckListUserRepository.getListUserStatisticByFireCheckIdList(fireCheckIdList);
        //fireCheckListUserDOList转换为key value map
        Map<String, FireCheckListStatisticDO> fireCheckListUserDONameMap = fireCheckListStatisticDOList.stream()
                .collect(Collectors.toMap(FireCheckListStatisticDO::getFireCheckId, Function.identity()));
        //获取清单的检查数量
        //补充检查数和完整检查人
        fireBackCheckListCOList.forEach(fireBackCheckListCO -> {
            //补充检查数量
            if (CollUtil.isNotEmpty(fireCheckListUserDONameMap) && fireCheckListUserDONameMap.get(fireBackCheckListCO.getFireCheckId()) != null) {
                FireCheckListStatisticDO fireCheckListStatisticDO = fireCheckListUserDONameMap.get(fireBackCheckListCO.getFireCheckId());
                fireBackCheckListCO.setUserNameList(fireCheckListStatisticDO.getUserName());
                fireBackCheckListCO.setCheckCount(fireCheckListStatisticDO.getCheckCount());
            }
        });
        return PageResponse.of(fireBackCheckListCOList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());

    }



    public PageResponse<FireCheckListCO> checkListRecordList(FireCheckListRecordPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.checkListRecordList(params);
        List<FireCheckListCO> examCenterCOS = fireCheckListCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)) {
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<String> fireCheckIdList = examCenterCOS.stream().map(FireCheckListCO::getFireCheckId).collect(Collectors.toList());
        //补充完整的用户负责人
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserNameByFireCheckIdList(fireCheckIdList);
        //fireCheckListUserDOList转换为key value map
        Map<String, String> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                .collect(Collectors.groupingBy(
                        FireCheckListUserDO::getFireCheckId,
                        Collectors.mapping(FireCheckListUserDO::getUserName, Collectors.joining(","))));
        //获取检查次数
        List<FireCheckRecordStatisticDO> fireCheckRecordStatisticDOList = fireCheckRecordRepository.statisticListByFireCheckIdList(fireCheckIdList);
        //fireCheckListItemStatisticDOList转换为key value map

        Map<String, Long> fireCheckListItemStatisticDOMap = fireCheckRecordStatisticDOList.stream().collect(Collectors.toMap(FireCheckRecordStatisticDO::getFireCheckId, FireCheckRecordStatisticDO::getFireCheckCount));
        //补充点位数和排查周期
        for (FireCheckListCO fireCheckListCO : examCenterCOS) {
            fireCheckListCO.setCheckCount(fireCheckListItemStatisticDOMap.getOrDefault(fireCheckListCO.getFireCheckId(), 0L));
            FireCheckListE info = new FireCheckListE();
            info.getCheckRecordPeriod(fireCheckListCO.getFireCheckType(), LocalDateTime.now());
            fireCheckListCO.setCheckStartTime(info.getPeriodStart());
            fireCheckListCO.setCheckEndTime(info.getPeriodEnd());
            fireCheckListCO.setUserName(fireCheckListUserDONameMap.getOrDefault(fireCheckListCO.getFireCheckId(), ""));
        }
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public PageResponse<FireCheckListCO> getCheckListRecord(CheckListRecordPageQry qry) {

        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        PageResponse<FireCheckListDO> pageResponse = fireCheckListRepository.getCheckListRecord(params);
        List<FireCheckListCO> examCenterCOS = fireCheckListCoConvertor.converDOsToCOs(pageResponse.getData());
        if(CollUtil.isEmpty(examCenterCOS)){
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<String> fireCheckIdList = examCenterCOS.stream().map(FireCheckListCO::getFireCheckId).collect(Collectors.toList());
        //补充完整的用户负责人
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserNameByFireCheckIdList(fireCheckIdList);
        //fireCheckListUserDOList转换为key value map
        Map<String, String> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                .collect(Collectors.groupingBy(
                        FireCheckListUserDO::getFireCheckId,
                        Collectors.mapping(FireCheckListUserDO::getUserName, Collectors.joining(","))));

        //补充检查次数
        List<FireCheckRecordStatisticDO> fireCheckRecordStatisticDOList = fireCheckRecordRepository.statisticListByFireCheckIdList(fireCheckIdList);
        Map<String, Long> fireCheckListItemStatisticDOMap = fireCheckRecordStatisticDOList.stream().collect(Collectors.toMap(FireCheckRecordStatisticDO::getFireCheckId, FireCheckRecordStatisticDO::getFireCheckCount));
        examCenterCOS.forEach(info -> {
            info.setUserName(fireCheckListUserDONameMap.getOrDefault(info.getFireCheckId(), ""));
            info.setCheckCount(fireCheckListItemStatisticDOMap.getOrDefault(info.getFireCheckId(), 0L));
        });

        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public void checkStandard(CheckPointListQry qry) {

        //获取所有的设备检查标准
        List<FireCheckStandardStatisticDO> fireCheckStandardDOList = fireCheckStandardRepository.getDeviceStandardList(qry.getFireCheckId());
        if(CollUtil.isEmpty(fireCheckStandardDOList)){
            throw new BizException("请维护点检设备的检查标准");
        }
        //获取fireCheckStandardDOList中count未空或者为0的数据，做异常提示
        List<FireCheckStandardStatisticDO> fireCheckStandardDOList1 = fireCheckStandardDOList.stream()
                .filter(info -> info.getStatisticCount() == null || info.getStatisticCount() == 0).collect(Collectors.toList());
        //fireCheckStandardDOList1获取名字集合做提示

        if(CollUtil.isNotEmpty(fireCheckStandardDOList1)){
            List<String> fireCheckStandardDOList1NameList = fireCheckStandardDOList1.stream().map(FireCheckStandardStatisticDO::getFireDeviceTypeName).collect(Collectors.toList());
            throw new BizException(fireCheckStandardDOList1NameList + "无检查标准,无法检查");
        }
    }


    public void overTimeRecord(Map<String, Object> params) {


        List<FireCheckListDO> noFinishedCheckList =fireCheckListRepository.overTimeRecord(params);
        if(CollUtil.isEmpty(noFinishedCheckList)){
            return;
        }
        List<String> fireCheckIdList = noFinishedCheckList.stream().map(FireCheckListDO::getFireCheckId).collect(Collectors.toList());
        //查找所有负责人
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserIdByFireCheckIdList(fireCheckIdList);
        Map<String, List<Long>> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                     .collect(Collectors.groupingBy(
                                     FireCheckListUserDO::getFireCheckId,
                                  Collectors.mapping(FireCheckListUserDO::getUserId, Collectors.toList())));
        noFinishedCheckList.forEach(info->{
            //TODO 进行超期 提醒
            /**
             * 清单负责人-待检查
             * "您有一条【点检表名称（排查周期）】已超期，请尽快处理。"
             */
            try{
                for (Long userId : fireCheckListUserDONameMap.get(info.getFireCheckId())) {
                    MessageSendCmd messageSendCmd = new MessageSendCmd();
                    messageSendCmd.setBusinessId(UuidUtil.get32UUID());
                    MessageTargetCmd messageTargetCmd = new MessageTargetCmd();
                    messageTargetCmd.setUserId(userId);
                    messageSendCmd.setTargetCmd(messageTargetCmd);
                    messageSendCmd.setSourceCode(messageConfig.getFireCheckOverdue());
                    messageSendCmd.setNeedTokenEnum(false);
                    Map<String, Object> sendParams = new HashMap<String, Object>();
                    sendParams.put("FirefightinglistName", info.getFireCheckName());
                    sendParams.put("checkPeriod", info.getFireCheckTypeName());
                    messageSendCmd.setParams(sendParams);
                    log.info("超期提醒发送消息参数:messageSendCmd: {}", JSONUtil.toJsonStr(messageSendCmd));
                    SingleResponse<Boolean> d = messageFacade.send(messageSendCmd);
                    log.info("超期提醒发送消息结果:d: {}", JSONUtil.toJsonStr(d));
                }
                //删除代办
                TodoListDeleteEvent event2 = new TodoListDeleteEvent();
                event2.setForeignSubsidiaryKey(info.getId());// 业务附表ID 没有附表时为foreignKey的值
                log.info("删除待办,请求：{}",info.getId());
                boolean b = todoListEventPusherUtil.sendMessageDeleteEvent(event2);
                log.info("删除待办,结果：{}",b);

            }catch (Exception e){
                log.error("发送消息异常",e);
            }

        });
    }

    public void waitFireCheckList(String checkType) {
        List<FireCheckListDO> waitCheckList =fireCheckListRepository.waitFireCheckList(checkType);
        List<String> fireCheckIdList = waitCheckList.stream().map(FireCheckListDO::getFireCheckId).collect(Collectors.toList());
        //查找所有负责人
        List<FireCheckListUserDO> fireCheckListUserDOList = fireCheckListUserRepository.getListUserIdByFireCheckIdList(fireCheckIdList);

        Map<String, List<Long>> fireCheckListUserDONameMap = fireCheckListUserDOList.stream()
                .collect(Collectors.groupingBy(
                        FireCheckListUserDO::getFireCheckId,
                        Collectors.mapping(FireCheckListUserDO::getUserId, Collectors.toList())));
        for (FireCheckListDO info : waitCheckList) {
            //TODO 待排查 提醒
            /**
             * 清单负责人-待检查
             * "您有一条【点检表名称（排查周期）】已超期，请尽快处理。"
             */
            if (CollUtil.isEmpty(fireCheckListUserDONameMap.get(info.getFireCheckId()))) {
                continue;
            }
            try {
                List<TodoListAddEvent> todoListAddEventList = new ArrayList<>();
                for (Long userId : fireCheckListUserDONameMap.get(info.getFireCheckId())) {
                    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", info.getFireCheckName());
                    sendParams.put("checkPeriod", info.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(info.getId()); // 业务表ID -申请
                    event.setForeignSubsidiaryKey(info.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("待排查待办,请求：{}",JSONUtil.toJsonStr(event3));
                boolean b = todoListEventPusherUtil.sendMessageAddBatchEvent(event3);
                log.info("待排查待办,结果：{}",b);
            } catch (Exception e) {
                log.error("发送消息异常", e);
            }
        }

    }
}

