package com.ruoyi.ems.service.impl;

import com.huashe.common.utils.DateUtils;
import com.ruoyi.ems.mapper.ElecPvSupplyHMapper;
import com.ruoyi.ems.model.PvSupplyExportVO;
import com.ruoyi.ems.model.PvSupplyVO;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IElecPvSupplyHService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 光伏产能统计Service业务层处理
 */
@Slf4j
@Service
public class ElecPvSupplyHServiceImpl implements IElecPvSupplyHService {

    @Autowired
    private ElecPvSupplyHMapper pvSupplyHMapper;

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

        try {
            log.info("查询光伏产能统计，时间维度: {}, 区域: {}", queryMeter.getTimeDimension(),
                queryMeter.getAreaCode());

            // 根据时间维度调用相应的查询方法
            switch (queryMeter.getTimeDimension().toLowerCase()) {
                case "hour":
                    return pvSupplyHMapper.selectPvSupplyHourlyList(queryMeter);
                case "day":
                    return pvSupplyHMapper.selectPvSupplyDailyList(queryMeter);
                case "month":
                    return pvSupplyHMapper.selectPvSupplyMonthlyList(queryMeter);
                case "year":
                    return pvSupplyHMapper.selectPvSupplyYearlyList(queryMeter);
                default:
                    log.warn("未识别的时间维度: {}，使用月统计", queryMeter.getTimeDimension());
                    return pvSupplyHMapper.selectPvSupplyMonthlyList(queryMeter);
            }
        }
        catch (Exception e) {
            log.error("查询光伏产能统计列表异常", e);
            return Collections.emptyList();
        }
    }

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

        try {
            log.info("查询光伏产能汇总，区域: {}", queryMeter.getAreaCode());

            PvSupplyVO summary = pvSupplyHMapper.selectPvSupplySummary(queryMeter);
            return summary != null ? summary : new PvSupplyVO();
        }
        catch (Exception e) {
            log.error("查询光伏产能统计汇总异常", e);
            return new PvSupplyVO();
        }
    }

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

        try {
            // 导出时不分页，清除分页参数
            QueryMeter exportQuery = cloneQueryMeter(queryMeter);
            exportQuery.setPageNum(null);
            exportQuery.setPageSize(null);

            log.info("导出光伏产能统计，时间维度: {}", exportQuery.getTimeDimension());

            List<PvSupplyVO> result = selectPvSupplyList(exportQuery);
            log.info("导出光伏产能统计完成，记录数: {}", result.size());

            return result;
        }
        catch (Exception e) {
            log.error("导出光伏产能统计异常", e);
            return Collections.emptyList();
        }
    }

    @Override
    public List<PvSupplyExportVO> convertToPvSupplyExportVOList(List<PvSupplyVO> originalList, String timeDimension) {
        if (CollectionUtils.isEmpty(originalList)) {
            return Collections.emptyList();
        }

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

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

        try {
            log.info("查询光伏产能分布，区域: {}", queryMeter.getAreaCode());
            List<PvSupplyVO> result = pvSupplyHMapper.selectPvSupplyDistribution(queryMeter);
            log.info("查询光伏产能分布完成，记录数: {}", result.size());
            return result;
        }
        catch (Exception e) {
            log.error("查询光伏产能分布异常", e);
            return Collections.emptyList();
        }
    }

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

        try {
            log.info("查询光伏产能分布明细，区域: {}", queryMeter.getAreaCode());
            List<PvSupplyVO> result = pvSupplyHMapper.selectPvSupplyDistributionDetail(queryMeter);
            log.info("查询光伏产能分布明细完成，记录数: {}", result.size());
            return result;
        }
        catch (Exception e) {
            log.error("查询光伏产能分布明细异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 转换单个产能VO为导出VO
     */
    private PvSupplyExportVO convertToPvSupplyExportVO(PvSupplyVO vo, String timeDimension) {
        PvSupplyExportVO exportVO = new PvSupplyExportVO();

        // 区域名称
        exportVO.setAreaName(vo.getAreaName());

        // 统计时间 - 根据时间维度格式化
        exportVO.setStatisticTime(formatStatisticTime(vo, timeDimension));

        // 产能数据 - 格式化为2位小数
        exportVO.setGenElecQuantity(formatNumber(vo.getGenElecQuantity(), 2));
        exportVO.setUseElecQuantity(formatNumber(vo.getUseElecQuantity(), 2));
        exportVO.setUpElecQuantity(formatNumber(vo.getUpElecQuantity(), 2));
        exportVO.setUpElecEarn(formatNumber(vo.getUpElecEarn(), 2));

        return exportVO;
    }

    /**
     * 格式化统计时间
     */
    private String formatStatisticTime(PvSupplyVO 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) {
            StringBuilder sb = new StringBuilder("0.");
            for (int i = 0; i < decimals; i++) {
                sb.append("0");
            }
            return sb.toString();
        }
        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.setTimeDimension(source.getTimeDimension());
        target.setStartRecTime(source.getStartRecTime());
        target.setEndRecTime(source.getEndRecTime());
        target.setOrderFlag(source.getOrderFlag());
        // 不复制分页参数
        target.setPageNum(null);
        target.setPageSize(null);

        return target;
    }
}