package com.ruoyi.ems.service.impl;

import com.huashe.common.utils.DateUtils;
import com.ruoyi.ems.domain.Area;
import com.ruoyi.ems.domain.ElecMeterH;
import com.ruoyi.ems.domain.EmsFacs;
import com.ruoyi.ems.domain.EnergyMeter;
import com.ruoyi.ems.domain.MeterBoundaryRel;
import com.ruoyi.ems.enums.MeterObjType;
import com.ruoyi.ems.mapper.ElecConsumptionMapper;
import com.ruoyi.ems.model.ElecConsumptionExportVO;
import com.ruoyi.ems.model.ElecConsumptionVO;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IAreaService;
import com.ruoyi.ems.service.IElecConsumptionService;
import com.ruoyi.ems.service.IEmsFacsService;
import com.ruoyi.ems.service.IMeterBoundaryRelService;
import com.ruoyi.ems.util.AreaUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用电统计服务实现
 */
@Service
public class ElecConsumptionServiceImpl implements IElecConsumptionService {

    private static final Logger logger = LoggerFactory.getLogger(ElecConsumptionServiceImpl.class);

    @Autowired
    private ElecConsumptionMapper elecConsumptionMapper;

    @Autowired
    private IMeterBoundaryRelService boundaryRelService;

    @Autowired
    private IEmsFacsService facsService;

    @Autowired
    private IAreaService areaService;

    /**
     * 电表计量类型常量
     */
    private static final int ELEC_METER_CLS = 45;

    // ==================== 用电类型查询 ====================

    @Override
    public List<String> getElecHourTypes(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            Set<String> meterDevices = getMeterDevicesByArea(queryMeter.getObjCode());
            if (meterDevices.isEmpty()) {
                logger.info("未找到相关电表设备，查询条件: areaCode={}, objCode={}",
                    queryMeter.getAreaCode(), queryMeter.getObjCode());
                return Collections.emptyList();
            }

            return elecConsumptionMapper.selectElecHourSupportTypes(queryMeter, meterDevices);
        } catch (Exception e) {
            logger.error("查询区域用电统计列表异常", e);
            return Collections.emptyList();
        }
    }

    // ==================== 电表原始数据查询 ====================

    @Override
    public List<ElecMeterH> selectMDevElecConsumptionList(QueryMeter queryMeter) {
        return elecConsumptionMapper.selectMDevElecConsumptionList(queryMeter);
    }

    @Override
    public ElecConsumptionVO selectMDevElecConsumptionSummary(QueryMeter queryMeter) {
        return elecConsumptionMapper.selectMDevElecConsumptionSummary(queryMeter);
    }

    // ==================== 区域用电统计（day/month/year） ====================

    @Override
    public List<ElecConsumptionVO> selectAreaElecConsumptionList(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            Set<String> meterDevices = getMeterDevicesByArea(queryMeter.getObjCode());
            if (meterDevices.isEmpty()) {
                logger.info("未找到相关电表设备，查询条件: areaCode={}, objCode={}",
                    queryMeter.getAreaCode(), queryMeter.getObjCode());
                return Collections.emptyList();
            }

            logger.info("查询区域用电统计，时间维度: {}, 设备数量: {}",
                queryMeter.getTimeDimension(), meterDevices.size());

            List<ElecConsumptionVO> result;
            switch (queryMeter.getTimeDimension().toLowerCase()) {
                case "day":
                    result = elecConsumptionMapper.selectAreaDailyElecConsumptionByDevices(queryMeter, meterDevices);
                    break;
                case "month":
                    result = elecConsumptionMapper.selectAreaMonthlyElecConsumptionByDevices(queryMeter, meterDevices);
                    break;
                case "year":
                    result = elecConsumptionMapper.selectAreaYearlyElecConsumptionByDevices(queryMeter, meterDevices);
                    break;
                default:
                    logger.warn("未识别的时间维度: {}，使用月统计", queryMeter.getTimeDimension());
                    result = elecConsumptionMapper.selectAreaMonthlyElecConsumptionByDevices(queryMeter, meterDevices);
                    break;
            }

            fillAreaNameForElecConsumption(result);
            return result;
        } catch (Exception e) {
            logger.error("查询区域用电统计列表异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public ElecConsumptionVO selectAreaElecConsumptionSummary(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空对象");
            return new ElecConsumptionVO();
        }

        try {
            Set<String> meterDevices = getMeterDevicesByArea(queryMeter.getObjCode());
            if (meterDevices.isEmpty()) {
                logger.info("未找到相关电表设备，返回空汇总");
                return new ElecConsumptionVO();
            }

            logger.info("查询区域用电汇总，设备数量: {}", meterDevices.size());

            ElecConsumptionVO summary = elecConsumptionMapper.selectAreaElecConsumptionSummaryByDevices(
                queryMeter, meterDevices);
            return summary != null ? summary : new ElecConsumptionVO();
        } catch (Exception e) {
            logger.error("查询区域用电统计汇总异常", e);
            return new ElecConsumptionVO();
        }
    }

    // ==================== 设施用电统计（day/month/year） ====================

    @Override
    public List<ElecConsumptionVO> selectFacsElecConsumptionList(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            logger.info("查询设施用电统计，时间维度: {}, 设施分类: {}, 区域: {}, 设施: {}",
                queryMeter.getTimeDimension(), queryMeter.getFacsCategory(),
                queryMeter.getAreaCode(), queryMeter.getObjCode());

            switch (queryMeter.getTimeDimension().toLowerCase()) {
                case "day":
                    return elecConsumptionMapper.selectFacsDailyElecConsumption(queryMeter);
                case "month":
                    return elecConsumptionMapper.selectFacsMonthlyElecConsumption(queryMeter);
                case "year":
                    return elecConsumptionMapper.selectFacsYearlyElecConsumption(queryMeter);
                default:
                    logger.warn("未识别的时间维度: {}，使用月统计", queryMeter.getTimeDimension());
                    return elecConsumptionMapper.selectFacsMonthlyElecConsumption(queryMeter);
            }
        } catch (Exception e) {
            logger.error("查询设施用电统计列表异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public ElecConsumptionVO selectFacsElecConsumptionSummary(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空对象");
            return new ElecConsumptionVO();
        }

        try {
            logger.info("查询设施用电汇总，设施分类: {}, 区域: {}, 设施: {}",
                queryMeter.getFacsCategory(), queryMeter.getAreaCode(), queryMeter.getObjCode());

            ElecConsumptionVO summary = elecConsumptionMapper.selectFacsElecConsumptionSummary(queryMeter);
            return summary != null ? summary : new ElecConsumptionVO();
        } catch (Exception e) {
            logger.error("查询设施用电统计汇总异常", e);
            return new ElecConsumptionVO();
        }
    }

    // ==================== 导出功能 ====================

    @Override
    public List<ElecConsumptionVO> exportAreaElecConsumptionList(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("导出参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            QueryMeter exportQuery = cloneQueryMeter(queryMeter);
            exportQuery.setPageNum(null);
            exportQuery.setPageSize(null);

            logger.info("导出区域用电统计，时间维度: {}", exportQuery.getTimeDimension());

            List<ElecConsumptionVO> result = selectAreaElecConsumptionList(exportQuery);
            logger.info("导出区域用电统计完成，记录数: {}", result.size());

            return result;
        } catch (Exception e) {
            logger.error("导出区域用电统计异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<ElecConsumptionVO> exportFacsElecConsumptionList(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("导出参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            QueryMeter exportQuery = cloneQueryMeter(queryMeter);
            exportQuery.setPageNum(null);
            exportQuery.setPageSize(null);

            logger.info("导出设施用电统计，时间维度: {}, 设施分类: {}",
                exportQuery.getTimeDimension(), exportQuery.getFacsCategory());

            List<ElecConsumptionVO> result = selectFacsElecConsumptionList(exportQuery);
            logger.info("导出设施用电统计完成，记录数: {}", result.size());

            return result;
        } catch (Exception e) {
            logger.error("导出设施用电统计异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<ElecConsumptionExportVO> convertToElecExportVOList(List<ElecConsumptionVO> originalList,
        String timeDimension) {
        if (CollectionUtils.isEmpty(originalList)) {
            return Collections.emptyList();
        }

        return originalList.stream()
            .map(vo -> convertToElecExportVO(vo, timeDimension))
            .collect(Collectors.toList());
    }

    // ==================== 小时粒度查询方法（重构后） ====================

    /**
     * 查询设施小时用电汇总统计
     *
     * 重构说明:
     * - 返回类型从 EnergyMeter 改为 ElecConsumptionVO（统一对象）
     * - 原方法调用 facsService + elecMeterHService 循环查询
     * - 重构后直接通过SQL一次完成，性能大幅提升
     *
     * @param queryMeter 查询条件
     * @return 设施用电汇总列表
     */
    @Override
    public List<ElecConsumptionVO> getFacsMeterHourSta(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            // 设置默认计量类型为电表
            if (queryMeter.getMeterCls() == null) {
                queryMeter.setMeterCls(ELEC_METER_CLS);
            }

            logger.info("查询设施小时用电汇总，区域: {}, 设施分类: {}, 子类: {}",
                queryMeter.getAreaCode(), queryMeter.getFacsCategory(), queryMeter.getFacsSubCategory());

            // 直接通过Mapper一次查询完成，替代原来的循环调用
            List<ElecConsumptionVO> result = elecConsumptionMapper.selectFacsHourlyElecSummary(queryMeter);

            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            logger.error("查询设施小时用电汇总异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 查询设施小时用电明细
     *
     * @param queryMeter 查询条件
     * @return 小时用电明细列表
     */
    @Override
    public List<ElecMeterH> getFacsElecHourMeter(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            // 设置默认计量类型
            if (queryMeter.getMeterCls() == null) {
                queryMeter.setMeterCls(ELEC_METER_CLS);
            }

            // 设置默认排序
            if (StringUtils.isBlank(queryMeter.getOrderFlag())) {
                queryMeter.setOrderFlag("desc");
            }

            // 处理对象名称（用于结果展示）
            enrichFacsQueryMeter(queryMeter);

            logger.info("查询设施小时用电明细，区域: {}, 设施: {}, 设施分类: {}",
                queryMeter.getAreaCode(), queryMeter.getObjCode(), queryMeter.getFacsCategory());

            // 直接通过Mapper查询
            List<ElecMeterH> result = elecConsumptionMapper.selectFacsHourlyElecConsumption(queryMeter);

            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            logger.error("查询设施小时用电明细异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 查询区域小时用电明细
     *
     * @param queryMeter 查询条件
     * @return 小时用电明细列表
     */
    @Override
    public List<ElecMeterH> getAreaElecHourMeter(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            // 设置默认排序
            if (StringUtils.isBlank(queryMeter.getOrderFlag())) {
                queryMeter.setOrderFlag("desc");
            }

            // 处理对象名称
            enrichAreaQueryMeter(queryMeter);

            // 获取区域绑定的所有电表设备
            Set<String> meterDevices = getAreaMeterDevicesForHourly(queryMeter);

            if (CollectionUtils.isEmpty(meterDevices)) {
                logger.info("未找到区域绑定的电表设备，区域: {}", queryMeter.getAreaCode());
                return Collections.emptyList();
            }

            logger.info("查询区域小时用电明细，区域: {}, 对象: {}, 设备数量: {}",
                queryMeter.getAreaCode(), queryMeter.getObjCode(), meterDevices.size());

            // 通过Mapper查询
            List<ElecMeterH> result = elecConsumptionMapper.selectAreaHourlyElecConsumptionByDevices(
                queryMeter, meterDevices);

            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            logger.error("查询区域小时用电明细异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public EnergyMeter selectElecDayAvg(QueryMeter queryMeter) {
        if (queryMeter == null) {
            logger.warn("查询参数为空，返回空对象");
            return new EnergyMeter();
        }

        try {
            logger.info("查询日平均用电，区域: {}, 设备: {}, 时间范围: {} ~ {}",
                queryMeter.getAreaCode(), queryMeter.getDeviceCode(),
                queryMeter.getStartRecTime(), queryMeter.getEndRecTime());

            EnergyMeter result = elecConsumptionMapper.selectElecDayAvg(queryMeter);
            return result != null ? result : new EnergyMeter();
        } catch (Exception e) {
            logger.error("查询日平均用电异常", e);
            return new EnergyMeter();
        }
    }

    @Override
    public List<EnergyMeter> qryDeviceElecByDay(QueryMeter queryMeter) {
        if (queryMeter == null || StringUtils.isBlank(queryMeter.getStartRecTime())) {
            logger.warn("查询参数为空，返回空列表");
            return Collections.emptyList();
        }

        try {
            logger.info("按设备类型查询日用电，区域: {}, 起始日期: {}",
                queryMeter.getAreaCode(), queryMeter.getStartRecTime());

            List<EnergyMeter> result = elecConsumptionMapper.selectDeviceElecByDay(queryMeter);
            return result != null ? result : Collections.emptyList();
        } catch (Exception e) {
            logger.error("按设备类型查询日用电异常", e);
            return Collections.emptyList();
        }
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 为设施查询条件补充名称信息
     */
    private void enrichFacsQueryMeter(QueryMeter queryMeter) {
        String objCode = queryMeter.getObjCode();
        String areaCode = queryMeter.getAreaCode();

        if (StringUtils.isNotBlank(objCode) && !StringUtils.equals(objCode, areaCode)
            && !StringUtils.equals("-1", objCode)) {
            // 查询指定设施
            EmsFacs emsFacs = facsService.selectEmsFacsByCode(objCode);
            if (emsFacs != null) {
                queryMeter.setObjName(emsFacs.getFacsName());
            }
        } else if (StringUtils.equals("-1", areaCode)) {
            // 全部设施
            queryMeter.setObjCode("-1");
            queryMeter.setObjName("全部设施");
        } else if (StringUtils.isNotBlank(areaCode)) {
            // 指定区域下的设施
            Area area = areaService.selectAreaByCode(areaCode);
            if (area != null) {
                queryMeter.setObjCode(areaCode);
                queryMeter.setObjName(area.getAreaName());
            }
        }
    }

    /**
     * 为区域查询条件补充名称信息
     */
    private void enrichAreaQueryMeter(QueryMeter queryMeter) {
        String areaCode = queryMeter.getAreaCode();

        if (StringUtils.equals("-1", areaCode)) {
            queryMeter.setObjCode("-1");
            queryMeter.setObjName("全部区域");
        } else if (StringUtils.isNotBlank(queryMeter.getObjCode())) {
            Area area = areaService.selectAreaByCode(queryMeter.getObjCode());
            if (area != null) {
                queryMeter.setObjName(area.getAreaName());
            }
        }
    }

    /**
     * 获取区域绑定的电表设备（用于小时粒度查询）
     *
     * 复用并简化原 getAreaElecHourMeter 中的设备获取逻辑
     */
    private Set<String> getAreaMeterDevicesForHourly(QueryMeter queryMeter) {
        Set<String> meterDevices = new HashSet<>();
        String areaCode = queryMeter.getAreaCode();

        try {
            if (StringUtils.equals("-1", areaCode)) {
                // 全部区域：获取所有顶级区域的设备
                List<Area> areaTree = areaService.selectAreaTree("0", false);

                // 如果有设施分类过滤，先过滤区域
                if (StringUtils.isNotBlank(queryMeter.getFacsCategory())) {
                    EmsFacs facsParam = new EmsFacs();
                    facsParam.setFacsCategory(queryMeter.getFacsCategory());
                    List<EmsFacs> facsList = facsService.selectEmsFacsList(facsParam);
                    Set<String> facsAreaCodes = facsList.stream()
                        .map(EmsFacs::getRefArea)
                        .collect(Collectors.toSet());
                    areaTree = AreaUtils.filterTree(areaTree, facsAreaCodes);
                }

                // 获取过滤后区域的所有电表设备
                for (Area area : areaTree) {
                    List<MeterBoundaryRel> rels = boundaryRelService.selectRelByObj(
                        area.getAreaCode(), MeterObjType.METER_AREA.getType(), ELEC_METER_CLS);
                    if (CollectionUtils.isNotEmpty(rels)) {
                        rels.forEach(rel -> meterDevices.add(rel.getMeterDevice()));
                    }
                }
            } else {
                // 指定区域：使用objCode或areaCode
                String targetCode = StringUtils.isNotBlank(queryMeter.getObjCode())
                    ? queryMeter.getObjCode() : areaCode;

                List<MeterBoundaryRel> relList = boundaryRelService.selectRelByObj(
                    targetCode, MeterObjType.METER_AREA.getType(), ELEC_METER_CLS);
                if (CollectionUtils.isNotEmpty(relList)) {
                    relList.forEach(rel -> meterDevices.add(rel.getMeterDevice()));
                }
            }
        } catch (Exception e) {
            logger.error("获取区域电表设备异常，区域: {}", areaCode, e);
        }

        return meterDevices;
    }

    /**
     * 根据区域获取所有相关的测点设备
     */
    private Set<String> getMeterDevicesByArea(String objCode) {
        Set<String> meterDevices = new HashSet<>();

        try {
            Set<String> targetAreaCodes = new HashSet<>();

            if (StringUtils.isNotBlank(objCode) && !"-1".equals(objCode)) {
                targetAreaCodes.addAll(getAllChildAreaCodes(objCode));
                logger.debug("根据objCode查询区域设备，区域代码: {}, 找到子区域数量: {}",
                    objCode, targetAreaCodes.size());
            }

            if (targetAreaCodes.isEmpty()) {
                logger.debug("未指定区域，查询所有电表设备");

                List<String> allDevices = boundaryRelService.selectMeterDevices(null, 1, ELEC_METER_CLS);
                if (CollectionUtils.isNotEmpty(allDevices)) {
                    meterDevices.addAll(allDevices);
                    logger.debug("查询到所有区域电表设备数量: {}", allDevices.size());
                } else {
                    List<Area> allAreas = areaService.selectArea(new Area());
                    if (CollectionUtils.isNotEmpty(allAreas)) {
                        for (Area area : allAreas) {
                            List<String> areaDevices = boundaryRelService.selectMeterDevices(
                                area.getAreaCode(), 1, ELEC_METER_CLS);
                            if (CollectionUtils.isNotEmpty(areaDevices)) {
                                meterDevices.addAll(areaDevices);
                                logger.debug("区域 {} 找到电表设备数量: {}",
                                    area.getAreaCode(), areaDevices.size());
                            }
                        }
                    }
                }
            } else {
                for (String areaCode : targetAreaCodes) {
                    List<String> devices = boundaryRelService.selectMeterDevices(areaCode, 1, ELEC_METER_CLS);
                    if (CollectionUtils.isNotEmpty(devices)) {
                        meterDevices.addAll(devices);
                        logger.debug("区域 {} 找到电表设备数量: {}", areaCode, devices.size());
                    }
                }
            }

            logger.info("最终获取到的电表设备总数: {}", meterDevices.size());
            if (logger.isDebugEnabled()) {
                logger.debug("设备列表: {}", meterDevices);
            }

        } catch (Exception e) {
            logger.error("获取区域测点设备异常", e);
        }

        return meterDevices;
    }

    /**
     * 获取指定区域及其所有子区域的代码
     */
    private Set<String> getAllChildAreaCodes(String areaCode) {
        Set<String> areaCodes = new HashSet<>();

        if (StringUtils.isBlank(areaCode)) {
            return areaCodes;
        }

        try {
            Area currentArea = areaService.selectAreaByCode(areaCode);
            if (currentArea != null) {
                areaCodes.add(currentArea.getAreaCode());
                logger.debug("添加当前区域: {}", currentArea.getAreaCode());
            }

            List<Area> childAreas = areaService.selectAreaTree(areaCode, true);
            collectAreaCodes(childAreas, areaCodes);

            logger.debug("区域 {} 及其子区域总数: {}", areaCode, areaCodes.size());
        } catch (Exception e) {
            logger.error("获取子区域代码异常，区域代码: {}", areaCode, e);
        }

        return areaCodes;
    }

    /**
     * 递归收集区域树中的所有区域代码
     */
    private void collectAreaCodes(List<?> areas, Set<String> areaCodes) {
        if (CollectionUtils.isEmpty(areas)) {
            return;
        }

        for (Object obj : areas) {
            if (obj instanceof Area) {
                Area area = (Area) obj;
                areaCodes.add(area.getAreaCode());

                if (CollectionUtils.isNotEmpty(area.getChildren())) {
                    collectAreaCodes(area.getChildren(), areaCodes);
                }
            }
        }
    }

    /**
     * 转换单个用电VO为导出VO
     */
    private ElecConsumptionExportVO convertToElecExportVO(ElecConsumptionVO vo, String timeDimension) {
        ElecConsumptionExportVO exportVO = new ElecConsumptionExportVO();

        exportVO.setObjName(vo.getObjName());
        exportVO.setStatisticTime(formatStatisticTime(vo, timeDimension));
        exportVO.setTotalElecQuantity(formatNumber(vo.getTotalElecQuantity(), 2));
        exportVO.setSharpPeakQuantity(formatNumber(vo.getSharpPeakQuantity(), 2));
        exportVO.setPeakQuantity(formatNumber(vo.getPeakQuantity(), 2));
        exportVO.setNormalQuantity(formatNumber(vo.getNormalQuantity(), 2));
        exportVO.setValleyQuantity(formatNumber(vo.getValleyQuantity(), 2));
        exportVO.setTotalElecCost(formatNumber(vo.getTotalElecCost(), 2));

        return exportVO;
    }

    /**
     * 格式化统计时间
     */
    private String formatStatisticTime(ElecConsumptionVO vo, String timeDimension) {
        if (timeDimension == null) {
            timeDimension = "month";
        }

        switch (timeDimension.toLowerCase()) {
            case "day":
                return formatDateForDisplay(vo.getStatisticDate());
            case "month":
                return StringUtils.isNotBlank(vo.getStatisticMonth()) ? vo.getStatisticMonth() : "";
            case "year":
                return vo.getStatisticYear() != null ? vo.getStatisticYear() : "";
            default:
                return StringUtils.isNotBlank(vo.getStatisticMonth()) ? vo.getStatisticMonth() : "";
        }
    }

    /**
     * 数字格式化
     */
    private String formatNumber(java.math.BigDecimal num, int decimals) {
        if (num == null) {
            return String.format("%." + decimals + "f", 0.0);
        }
        return String.format("%." + decimals + "f", num.doubleValue());
    }

    /**
     * 日期格式化用于显示
     */
    private String formatDateForDisplay(Date dateObj) {
        return DateUtils.dateToString(dateObj, "yyyy-MM-dd");
    }

    /**
     * 克隆查询参数对象
     */
    private QueryMeter cloneQueryMeter(QueryMeter source) {
        if (source == null) {
            return null;
        }

        QueryMeter target = new QueryMeter();
        target.setAreaCode(source.getAreaCode());
        target.setObjCode(source.getObjCode());
        target.setObjType(source.getObjType());
        target.setFacsCategory(source.getFacsCategory());
        target.setFacsSubCategory(source.getFacsSubCategory());
        target.setTimeDimension(source.getTimeDimension());
        target.setStartRecTime(source.getStartRecTime());
        target.setEndRecTime(source.getEndRecTime());
        target.setOrderFlag(source.getOrderFlag());
        target.setMeterCls(source.getMeterCls());
        target.setPageNum(null);
        target.setPageSize(null);

        return target;
    }

    /**
     * 填充区域用电统计的区域名称路径
     */
    private void fillAreaNameForElecConsumption(List<ElecConsumptionVO> consumptionList) {
        if (CollectionUtils.isEmpty(consumptionList)) {
            return;
        }

        try {
            List<Area> areas = areaService.selectArea(new Area());
            Map<String, Area> areaMap = areas.stream()
                .collect(Collectors.toMap(Area::getAreaCode, Function.identity()));

            for (ElecConsumptionVO vo : consumptionList) {
                fillAreaNameForSingleRecord(vo, areaMap);
            }

            logger.debug("完成用电统计区域名称填充，记录数: {}", consumptionList.size());
        } catch (Exception e) {
            logger.error("填充用电统计区域名称异常", e);
        }
    }

    /**
     * 为单条记录填充区域名称
     */
    private void fillAreaNameForSingleRecord(ElecConsumptionVO vo, Map<String, Area> areaMap) {
        if (vo == null || StringUtils.isBlank(vo.getObjCode())) {
            return;
        }

        String areaNamePath = AreaUtils.getAreaNamePath(vo.getObjCode(), areaMap);

        if (StringUtils.isNotBlank(areaNamePath)) {
            vo.setObjName(areaNamePath);
            logger.debug("区域名称已替换: {} -> {}", vo.getObjCode(), areaNamePath);
        }
    }
}