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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zcloud.fire.check.command.convertor.FirePointCoConvertor;
import com.zcloud.fire.check.domain.enums.CorpTypeEnum;
import com.zcloud.fire.check.domain.config.PointConfig;
import com.zcloud.fire.check.domain.model.FirePointE;
import com.zcloud.fire.check.dto.FirePointDeviceQry;
import com.zcloud.fire.check.dto.FirePointPageQry;
import com.zcloud.fire.check.dto.clientobject.FirePointCO;
import com.zcloud.fire.check.dto.clientobject.FirePointDeviceCO;
import com.zcloud.fire.check.persistence.dataobject.FirePointDeviceCountDO;
import com.zcloud.fire.check.persistence.dataobject.FirePointDO;
import com.zcloud.fire.check.persistence.repository.FireCheckRecordPointRepository;
import com.zcloud.fire.check.persistence.repository.FireDeviceRepository;
import com.zcloud.fire.check.persistence.repository.FirePointRepository;
import com.zcloud.gbscommon.excelEntity.FirePointExcelExportEntity;
import com.zcloud.gbscommon.zcloudimgfiles.facade.ZcloudImgFilesFacade;
import com.zcloud.gbscommon.zcloudimgfiles.request.ZcloudImgFilesQryCmd;
import com.zcloud.gbscommon.zcloudimgfiles.response.ZcloudImgFilesCO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-26 10:12:55
 */
@Component
@AllArgsConstructor
@Slf4j
public class FirePointQueryExe {
    private final FirePointRepository firePointRepository;
    private final FirePointCoConvertor firePointCoConvertor;
    private final FireDeviceRepository fireDeviceRepository;
    private final FireCheckRecordPointRepository fireCheckRecordPointRepository;


    @Autowired
    private PointConfig pointConfig;
    @DubboReference(check = false)
    private ZcloudImgFilesFacade zcloudImgFilesFacade;
    /**
     * 分页
     *
     * @param firePointPageQry
     * @return
     */
    public PageResponse<FirePointCO> execute(FirePointPageQry firePointPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(firePointPageQry);
        PageResponse<FirePointDO> pageResponse = firePointRepository.listPage(params);
        List<FirePointCO> examCenterCOS = firePointCoConvertor.converDOsToCOs(pageResponse.getData());
        if (CollUtil.isEmpty(examCenterCOS)){
            return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        //
        List<String> firePointIds = examCenterCOS.stream().map(FirePointCO::getFirePointId).collect(Collectors.toList());
        Map<String,Long> deviceCountMap =fireDeviceRepository.countByFirePointIdIn(firePointIds);
        examCenterCOS.forEach(examCenterCO -> examCenterCO.setDeivceCount(deviceCountMap.getOrDefault(examCenterCO.getFirePointId(),0L)));
        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }

    public FirePointCO getInfoById(Long id) {
        FirePointDO firePointDO = firePointRepository.getInfoById(id);
        if(firePointDO == null){
            return null;
        }
        FirePointCO firePointCO = new FirePointCO();
        BeanUtils.copyProperties(firePointDO, firePointCO);
        //获取点位检查的最新三个检查点位id
        List<String> fireRecordPointIdList = fireCheckRecordPointRepository.getLastThreeRecord(firePointCO.getFirePointId());
        if(CollUtil.isNotEmpty(fireRecordPointIdList)){
            ZcloudImgFilesQryCmd zcloudImgFilesQryCmd = new ZcloudImgFilesQryCmd();
            String[] foreignKeys = fireRecordPointIdList.toArray(new String[0]);
            zcloudImgFilesQryCmd.setInForeignKey(foreignKeys);
            log.info("调用统一用户获取点位最新图片请求:{}", JSONUtil.toJsonStr(zcloudImgFilesQryCmd));
            try{
                MultiResponse<ZcloudImgFilesCO> zcloudImgFilesCOs = zcloudImgFilesFacade.listAll(zcloudImgFilesQryCmd);
                log.info("调用统一用户获取点位最新图片返回:{}", JSONUtil.toJsonStr(zcloudImgFilesCOs));
                List<ZcloudImgFilesCO> data = zcloudImgFilesCOs.getData();
                if(CollUtil.isNotEmpty(data)){
                    List<String> urlList = data.stream()
                            .filter(Objects::nonNull) // 过滤掉 null 元素
                            .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                            .limit(3)
                            .map(ZcloudImgFilesCO::getFilePath)
                            .collect(Collectors.toList());
                    firePointCO.setUrlList(urlList);
                }
            }catch (Exception e){
                log.error("调用统一用户获取点位最新图片异常:", e);
            }
        }
        return firePointCO;
    }

    public void exportFirePointPage(Long[] ids,HttpServletResponse httpServletResponse) {
        FirePointPageQry firePointPageQry = new FirePointPageQry();
        firePointPageQry.setIds(ids);
        firePointPageQry.setPageSize(100000);

        PageResponse<FirePointCO> firePointCOPageResponse = execute(firePointPageQry);
        List<FirePointCO> data = firePointCOPageResponse.getData();
        List<FirePointExcelExportEntity> listManagerStatisticsExcelExportEntityList = firePointCoConvertor.converCOsToExcelEntitys(data);

        FirePointE firePointE = new FirePointE();
        firePointE.exportFirePointTable(httpServletResponse, listManagerStatisticsExcelExportEntityList,pointConfig.getPrefix() );


    }

    public MultiResponse<FirePointCO> listByFireRegionId(String fireRegionId) {
        List<FirePointDO> pageResponse = firePointRepository.listByFireRegionId(fireRegionId);
        List<FirePointCO> examCenterCOS = firePointCoConvertor.converDOsToCOs(pageResponse);
        return MultiResponse.of(examCenterCOS);
    }

    public PageResponse<FirePointDeviceCO> listDevice(FirePointDeviceQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        if (ObjectUtil.isNotEmpty(params.get("enterpriseType"))) {
            List<Integer> enterpriseType = CorpTypeEnum.getCodesByEnterpriseType((Integer) params.get("enterpriseType"));
            if (CollUtil.isNotEmpty(enterpriseType)) {
                params.put("type", enterpriseType);
            }
        }
        List<Integer> inType = (List<Integer>) params.get("inType");
        if (CollUtil.isNotEmpty(inType)) {
            params.put("type", inType);
        }
        PageResponse<FirePointDeviceCountDO> pageResponse = firePointRepository.listDevice(params);
        List<FirePointDeviceCO> list = pageResponse.getData().stream().map(item -> {
            FirePointDeviceCO co = new FirePointDeviceCO();
            BeanUtils.copyProperties(item, co);
            return co;
        }).collect(Collectors.toList());
        return PageResponse.of(list, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }
}

