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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.exception.BizException;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.fire.check.command.convertor.FireCheckStandardCoConvertor;
import com.zcloud.fire.check.command.convertor.FireDeviceCoConvertor;
import com.zcloud.fire.check.domain.enums.CommonFlagEnum;
import com.zcloud.fire.check.domain.enums.CorpTypeEnum;
import com.zcloud.fire.check.domain.enums.UserTypeEnum;
import com.zcloud.fire.check.domain.gateway.FirePointGateway;
import com.zcloud.fire.check.domain.gateway.FireRegionGateway;
import com.zcloud.fire.check.domain.model.*;
import com.zcloud.fire.check.dto.CorpStatisticsPageQry;
import com.zcloud.fire.check.dto.FireDeviceListQry;
import com.zcloud.fire.check.dto.FireDevicePageQry;
import com.zcloud.fire.check.dto.FirePointPageQry;
import com.zcloud.fire.check.dto.clientobject.CorpStatisticsCO;
import com.zcloud.fire.check.dto.clientobject.FireCheckStandardCO;
import com.zcloud.fire.check.dto.clientobject.FireDeviceCO;
import com.zcloud.fire.check.dto.clientobject.FirePointCO;
import com.zcloud.fire.check.persistence.dataobject.*;
import com.zcloud.fire.check.persistence.repository.*;
import com.zcloud.gbscommon.excelEntity.FireDeviceExcelExportEntity;
import com.zcloud.gbscommon.excelEntity.FirePointExcelExportEntity;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-26 10:12:34
 */
@Component
@AllArgsConstructor
public class FireDeviceQueryExe {
    private final FireDeviceRepository fireDeviceRepository;
    private final FireDeviceCoConvertor fireDeviceCoConvertor;
    private final DepartmentRepository departmentRepository;
    private final UserRepository userRepository;
    private final FireRegionRepository fireRegionRepository;
    private final FirePointRepository firePointRepository;
    private final FireRegionGateway fireRegionGateway;
    private final FirePointGateway firePointGateway;
    private final CorpInfoRepository corpInfoRepository;
    private final FireCheckStandardRepository fireCheckStandardRepository;
    private final FireCheckStandardCoConvertor fireCheckStandardCoConvertor;

    /**
     * 分页
     *
     * @param fireDevicePageQry
     * @return
     */
    public PageResponse<FireDeviceCO> execute(FireDevicePageQry fireDevicePageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(fireDevicePageQry);
        PageResponse<FireDeviceDO> pageResponse = fireDeviceRepository.listPage(params);
        if (CollUtil.isEmpty(pageResponse.getData())) {
            return PageResponse.of(null, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<FireDeviceCO> examCenterCOS = fireDeviceCoConvertor.converDOsToCOs(pageResponse.getData());
        //拼接消防器材检查标准，获取list
        List<String> fireDeviceTypeList = examCenterCOS.stream().map(FireDeviceCO::getFireDeviceType).collect(Collectors.toList());
        //根据list查询消防器材检查标准
        List<FireCheckStandardDO> fireCheckStandardDOList = fireCheckStandardRepository.getCheckStandardList(fireDeviceTypeList);
        if (CollUtil.isNotEmpty(fireCheckStandardDOList)) {
            List<FireCheckStandardCO> fireCheckStandardCOList = fireCheckStandardCoConvertor.converDOsToCOs(fireCheckStandardDOList);
            Map<String, List<FireCheckStandardCO>> fireCheckStandardMap = fireCheckStandardCOList.stream()
                    .collect(Collectors.groupingBy(FireCheckStandardCO::getFireDeviceType));
            examCenterCOS.forEach(info -> {
                info.setFireCheckStandardList(fireCheckStandardMap.get(info.getFireDeviceType()));
            });
        }


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

    public FireDeviceCO getInfoById(Long id) {
        FireDeviceDO fireDeviceDO = fireDeviceRepository.getInfoById(id);
        if (fireDeviceDO == null) {
            return null;
        }
        FireDeviceCO fireDeviceCO = new FireDeviceCO();
        BeanUtils.copyProperties(fireDeviceDO, fireDeviceCO);
        return fireDeviceCO;
    }

    public void exportFireDevicePage(Long[] ids, HttpServletResponse httpServletResponse) {
        FireDevicePageQry fireDevicePageQry = new FireDevicePageQry();
        //Long[] 转换成list
        List<Long> idList = Arrays.asList(ids);
        fireDevicePageQry.setIds(idList);
        fireDevicePageQry.setPageSize(100000);

        Map<String, Object> params = PageQueryHelper.toHashMap(fireDevicePageQry);
        List<FireDeviceDO> fireDeviceDOList  = fireDeviceRepository.getAllList(params);
        List<FireDeviceCO> data = fireDeviceCoConvertor.converDOsToCOs(fireDeviceDOList);

        List<FireDeviceExcelExportEntity> listManagerStatisticsExcelExportEntityList = fireDeviceCoConvertor.converCOsToExcelEntitys(data);
        FireDeviceE fireDeviceE = new FireDeviceE();
        fireDeviceE.exportFireDeviceTable(httpServletResponse, listManagerStatisticsExcelExportEntityList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void importFireDevicePage(MultipartFile file) {
        // 查询所有部门
        List<DepartmentDO> departmentDOS = departmentRepository.listByCorpinfoId(AuthContext.getTenantId());
        // 查询所有人员
        List<UserDO> userDOS = userRepository.listByCorpinfoId(AuthContext.getTenantId());
        List<FireDeviceDO> fireDeviceDOList = fireDeviceRepository.getDeviceList();
        // 查询所有区域
        List<FireRegionDO> fireRegionDOS = fireRegionRepository.listByCorpinfoId(AuthContext.getTenantId());
        List<FirePointDO> firePointDOS = firePointRepository.listByCorpinfoId(AuthContext.getTenantId());
        List<DepartmentE> departmentEList = BeanUtil.copyToList(departmentDOS, DepartmentE.class);
        List<UserE> userEList = BeanUtil.copyToList(userDOS, UserE.class);
        List<FireDeviceE> fireDeviceEList = BeanUtil.copyToList(fireDeviceDOList, FireDeviceE.class);
        List<FireRegionE> fireRegionEList = BeanUtil.copyToList(fireRegionDOS, FireRegionE.class);
        List<FirePointE> firePointEList = BeanUtil.copyToList(firePointDOS, FirePointE.class);

        fireDeviceEList = FireDeviceE.parseImportTemplateData(file,
                departmentEList,
                userEList,
                fireDeviceEList,
                fireRegionEList,
                firePointEList);

        fireDeviceEList.forEach(fireDeviceE -> {

            if (StringUtils.isEmpty(fireDeviceE.getFireRegionId())) {
                //新增区域
                FireRegionE fireRegionE = fireDeviceE.getFireRegionE();
                fireRegionGateway.add(fireRegionE);
                fireDeviceE.setFireRegionId(fireRegionE.getFireRegionId());
            }
            if (StringUtils.isEmpty(fireDeviceE.getFirePointId())) {
                //新增点位
                FirePointE firePointE = fireDeviceE.getFirePointE();
                firePointE.setFireRegionId(fireDeviceE.getFireRegionId());
                firePointGateway.add(firePointE);
                fireDeviceE.setFirePointId(firePointE.getFirePointId());
            }

        });
        // 批量插入
        boolean res = false;
        try {
            res = fireDeviceRepository.addBatch(BeanUtil.copyToList(fireDeviceEList, FireDeviceDO.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("导入失败");
        }
    }

    public Collection<FireDeviceCO> getAllList(FireDeviceListQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        List<FireDeviceDO> pageResponse = fireDeviceRepository.getAllList(params);
        List<FireDeviceCO> examCenterCOS = fireDeviceCoConvertor.converDOsToCOs(pageResponse);
        return examCenterCOS;
    }

    public PageResponse<CorpStatisticsCO> corpStatisticslist(CorpStatisticsPageQry qry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(qry);
        //企业端
        params.put("inType", CorpTypeEnum.getCodesByEnterpriseType(UserTypeEnum.QY.getCode()));
        params.put("eqUseFlag", CommonFlagEnum.YES.getCode());

        PageResponse<CorpInfoDO> pageResponse = corpInfoRepository.listPage(params);
        if (CollUtil.isEmpty(pageResponse.getData())) {
            return PageResponse.of(null, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }

        List<CorpStatisticsCO> examCenterCOS = fireDeviceCoConvertor.converCorpDOsToCorpCO(pageResponse.getData());
        //获取企业id
        List<Long> corpinfoIds = examCenterCOS.stream().map(CorpStatisticsCO::getId).collect(Collectors.toList());
        //获取消防区域数量
        List<DataStatisticDO> fireRegionCountMap = fireRegionRepository.countByCorpinfoIds(corpinfoIds);
        //按照企业id进行分组
        Map<Long, DataStatisticDO> fireRegionCountMapGroup = fireRegionCountMap.stream().collect(Collectors.toMap(DataStatisticDO::getCorpinfoId, Function.identity()));
        //获取消防点位数量
        List<DataStatisticDO> firePointCountMap = firePointRepository.countByCorpinfoIds(corpinfoIds);
        Map<Long, DataStatisticDO> firePointCountMapGroup = firePointCountMap.stream().collect(Collectors.toMap(DataStatisticDO::getCorpinfoId, Function.identity()));
        List<DataStatisticDO> fireDeviceCountMap = fireDeviceRepository.countByCorpinfoIds(corpinfoIds);
        Map<Long, DataStatisticDO> fireDeviceCountMapGroup = fireDeviceCountMap.stream().collect(Collectors.toMap(DataStatisticDO::getCorpinfoId, Function.identity()));

        examCenterCOS.forEach(examCenterCO -> {
            examCenterCO.setFireRegionCount(fireRegionCountMapGroup.getOrDefault(examCenterCO.getId(), new DataStatisticDO()).getTotalCount());
            examCenterCO.setFirePointCount(firePointCountMapGroup.getOrDefault(examCenterCO.getId(), new DataStatisticDO()).getTotalCount());
            examCenterCO.setFireDeviceCount(fireDeviceCountMapGroup.getOrDefault(examCenterCO.getId(), new DataStatisticDO()).getTotalCount());
        });

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

    }


    public PageResponse<FireDeviceCO> pageByPointId(FireDevicePageQry fireDevicePageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(fireDevicePageQry);
        PageResponse<FireDeviceDO> pageResponse = fireDeviceRepository.pageByPointId(params);
        if (CollUtil.isEmpty(pageResponse.getData())) {
            return PageResponse.of(null, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
        }
        List<FireDeviceCO> examCenterCOS = fireDeviceCoConvertor.converDOsToCOs(pageResponse.getData());
        //拼接消防器材检查标准，获取list
        List<String> fireDeviceTypeList = examCenterCOS.stream().map(FireDeviceCO::getFireDeviceType).collect(Collectors.toList());
        //根据list查询消防器材检查标准
        List<FireCheckStandardDO> fireCheckStandardDOList = fireCheckStandardRepository.getCheckStandardList(fireDeviceTypeList);
        if (CollUtil.isNotEmpty(fireCheckStandardDOList)) {
            List<FireCheckStandardCO> fireCheckStandardCOList = fireCheckStandardCoConvertor.converDOsToCOs(fireCheckStandardDOList);
            Map<String, List<FireCheckStandardCO>> fireCheckStandardMap = fireCheckStandardCOList.stream()
                    .collect(Collectors.groupingBy(FireCheckStandardCO::getFireDeviceType));
            examCenterCOS.forEach(info -> {
                info.setFireCheckStandardList(fireCheckStandardMap.get(info.getFireDeviceType()));
            });
        }


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

    public void deviceOverTimeMessage() {
        //获取明天的时间,String类型的时间，年月日
        LocalDateTime tomorrow = LocalDateTime.now().minusDays(1);
        String tomorrowTime = tomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        //获取到期的消防设备
        List<FireDeviceDO> fireDeviceDOList = fireDeviceRepository.getListByTime(tomorrowTime);
        if (CollUtil.isEmpty(fireDeviceDOList)) {
            return;
        }
        fireDeviceDOList.forEach(info->{
            //TODO 设备过期提醒

        });
    }
}

