package com.mvc.service.tyrq;

import com.mvc.constant.BaseConstant;
import com.mvc.constant.ReviewResultType;
import com.mvc.dao.TAireadMapper;
import com.mvc.entity.TAiread;
import com.mvc.entity.TAireadExample;
import com.mvc.model.StationAccModel;
import com.mvc.model.tyrq.TyrqStatisticsModel;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class TyrqStatisticsService {
    @Resource
    private TAireadMapper aireadMapper;

    @Resource
    private StationAccService stationAccService;

    public TyrqStatisticsModel getStatisticsDataByStationCode(String stationCode) {
        TyrqStatisticsModel resModel = new TyrqStatisticsModel();

        LocalDate today = LocalDate.now();
        // 使用TemporalAdjusters获取今年的第一天
        LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());
        // 将LocalDate转换为Date
        Date firstDayOfYearAsDate = Date.from(firstDayOfYear.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date now = DateUtil.getMidnightDate(new Date());

        List<TAiread> aireadModels = getAireadData(stationCode, firstDayOfYearAsDate, now);
        if (aireadModels == null || aireadModels.isEmpty()) {
            return resModel;
        }

        //本年用量
        TAiread first = aireadModels.get(0);
        TAiread last = aireadModels.get(aireadModels.size() - 1);
        BigDecimal yearUsage = last.getResultValue().subtract(first.getResultValue());
        resModel.setYearUsage(yearUsage);
        //日均用量(年)
        //处理年前没数据(还未安装的情况) 2025-06-19 guozhao
        LocalDate firstAireadLocalDate = DateUtil.dateToLocalDate(first.getSampleTime());
        LocalDate tempFirstLocalDate = firstAireadLocalDate.compareTo(firstDayOfYear)>0?firstAireadLocalDate:firstDayOfYear;
        LocalDate lastLocalDate = DateUtil.dateToLocalDate(last.getSampleTime());
        long daysBetween = ChronoUnit.DAYS.between(tempFirstLocalDate, lastLocalDate);

        int dyaAveUsage = daysBetween == 0 ? 0 : yearUsage.divide(new BigDecimal(daysBetween), new MathContext(2, RoundingMode.HALF_UP)).intValue();

        resModel.setDayAveUsage(dyaAveUsage);
        //本月用量
        LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        Date firstDayOfMonthAsDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        List<TAiread> temp = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(firstDayOfMonthAsDate) > -1).collect(Collectors.toList());
        if (temp.size() > 0) {
            first = temp.get(0);
            resModel.setMonthUsage(last.getResultValue().subtract(first.getResultValue()).intValue());
        } else {
            resModel.setMonthUsage(0);
        }
        //昨日用量
        Date yesterday = DateUtil.getOtherDateByCurrentDate(now, -1);
        //Optional<TAiread> optional = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(yesterday) == 0).findFirst();
        //实际数据中有非整点数据(因此不能做绝对的比较) 2024-04-07 guozhao
        Optional<TAiread> optional = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(yesterday) >= 0).findFirst();
        if (optional.isPresent()) {
            //只忽略分钟部分,如果整个0点都没有数据则不计算 2024-04-07 guozhao
            if (DateUtil.getMinsbetweenTime(yesterday, optional.get().getSampleTime()) < 60) {
                first = optional.get();
                resModel.setYesterdayUsage(last.getResultValue().subtract(first.getResultValue()).intValue());
            }
        }

        //最近30天用量
        if (daysBetween < 62) {
            //判断62天,是为了考虑跨年环比的情况
            Date startDate = DateUtil.getOtherDateByCurrentDate(now, -62);
            aireadModels = getAireadData(stationCode, startDate, now);
        }
        List<String> recentUsageXAxis = new ArrayList<>();
        List<BigDecimal> recentUsageYAxis = new ArrayList<>();

        Date startDate = DateUtil.getOtherDateByCurrentDate(now, -30);
        Date tempDate = startDate;//循环变量
        while (tempDate.compareTo(now) < 0) {
            Date finalTempDate0 = tempDate;

            //测试
            /*String d1 = DateUtil.formateDate(finalTempDate0, "MMdd");
            if(d1.equals("0328")){
                System.out.println(d1);
            }*/

            tempDate = DateUtil.getOtherDateByCurrentDate(tempDate, 1);
            recentUsageXAxis.add(DateUtil.formateDate(finalTempDate0, "MM/dd"));
            //Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalTempDate0)).findFirst();
            Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(finalTempDate0) >= 0).findFirst();
            if (optional0.isPresent()) {
                if (DateUtil.getMinsbetweenTime(finalTempDate0, optional0.get().getSampleTime()) > 60) {
                    //有数据但不是0点范围内 2024-04-07 guozhao
                    recentUsageYAxis.add(BigDecimal.ZERO);
                    continue;
                }
            } else {
                //没有当天数据
                recentUsageYAxis.add(BigDecimal.ZERO);
                continue;
            }
            //没有第二天数据
            Date finalTempDate1 = tempDate;
            //Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalTempDate1)).findFirst();
            Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(finalTempDate1) >= 0).findFirst();
            if (optional1.isPresent()) {
                if (DateUtil.getMinsbetweenTime(finalTempDate1, optional1.get().getSampleTime()) > 60) {
                    //有数据但不是0点范围内 2024-04-07 guozhao
                    recentUsageYAxis.add(BigDecimal.ZERO);
                    continue;
                }
            } else {
                //没有这一天的起始时间,用量设置为0
                recentUsageYAxis.add(BigDecimal.ZERO);
                continue;
            }
            recentUsageYAxis.add(optional1.get().getResultValue().subtract(optional0.get().getResultValue()));
        }
        resModel.setRecentUsageXAxis(recentUsageXAxis);
        resModel.setRecentUsageYAxis(recentUsageYAxis);

        //环比(以天为单位的,还可以以月,因为天燃气数据较少,且用户需求不明确)
        //环比增长率 = (本期数 - 上期数) / 上期数 × 100%
        List<String> chainXAxis = new ArrayList<>();//环比-X轴名称
        List<BigDecimal> chainValueYAxis = new ArrayList<>();//环比-增长量
        List<BigDecimal> chainRateYAxis = new ArrayList<>();//环比-增长率

        //firstDayOfMonthAsDate
        tempDate = firstDayOfMonthAsDate;//循环变量
        while (tempDate.compareTo(now) < 0) {
            //当日(本月)
            Date finalTempDate0 = tempDate;
            tempDate = DateUtil.getOtherDateByCurrentDate(tempDate, 1);
            chainXAxis.add(DateUtil.formateDate(finalTempDate0, "dd"));
            //Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalTempDate0)).findFirst();
            Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(finalTempDate0) >= 0).findFirst();
            if (optional0.isPresent()) {
                if (DateUtil.getMinsbetweenTime(finalTempDate0, optional0.get().getSampleTime()) > 60) {
                    //有数据但不是0点范围内 2024-04-07 guozhao
                    chainValueYAxis.add(BigDecimal.ZERO);
                    chainRateYAxis.add(BigDecimal.ZERO);
                    continue;
                }
            } else {
                //没有当天数据
                chainValueYAxis.add(BigDecimal.ZERO);
                chainRateYAxis.add(BigDecimal.ZERO);
                continue;
            }
            //没有第二天数据
            Date finalTempDate1 = tempDate;
            //Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalTempDate1)).findFirst();
            Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().compareTo(finalTempDate1) >= 0).findFirst();

            if (optional1.isPresent()) {
                if (DateUtil.getMinsbetweenTime(finalTempDate1, optional1.get().getSampleTime()) > 60) {
                    //有数据但不是0点范围内 2024-04-07 guozhao
                    chainValueYAxis.add(BigDecimal.ZERO);
                    chainRateYAxis.add(BigDecimal.ZERO);
                    continue;
                }
            } else {
                //没有数据
                chainValueYAxis.add(BigDecimal.ZERO);
                chainRateYAxis.add(BigDecimal.ZERO);
                continue;
            }
            //当日用量
            BigDecimal usage1 = optional1.get().getResultValue().subtract(optional0.get().getResultValue());

            Date lstMonth = DateUtil.getOtherDateByMonth(finalTempDate0, -1);
            Optional<TAiread> optional3 = aireadModels.stream().filter(s -> s.getSampleTime().equals(lstMonth)).findFirst();
            //没有当天数据
            if (!optional3.isPresent()) {
                chainValueYAxis.add(BigDecimal.ZERO);
                chainRateYAxis.add(BigDecimal.ZERO);
                continue;
            }
            //没有第二天数据
            Date finalTempDate2 = DateUtil.getOtherDateByCurrentDate(lstMonth, 1);
            Optional<TAiread> optional4 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalTempDate2)).findFirst();
            //没有这一天的起始时间,用量设置为0
            if (!optional4.isPresent()) {
                chainValueYAxis.add(BigDecimal.ZERO);
                chainRateYAxis.add(BigDecimal.ZERO);
                continue;
            }
            //上月当日
            BigDecimal usage0 = optional4.get().getResultValue().subtract(optional3.get().getResultValue());
            chainValueYAxis.add(usage1.subtract(usage0));//增量

            if (usage0.compareTo(BigDecimal.ZERO) == 0) {
                chainRateYAxis.add(BigDecimal.ZERO);
            } else {
                BigDecimal result = usage1.subtract(usage0).divide(usage0, new MathContext(4, RoundingMode.HALF_UP));
                result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                chainRateYAxis.add(result);
            }
        }

        resModel.setChainXAxis(chainXAxis);
        resModel.setChainValueYAxis(chainValueYAxis);
        resModel.setChainRateYAxis(chainRateYAxis);

        //同比-空数据
        resModel.setYoyXAxis(new ArrayList<>());
        resModel.setYoyLastYearYAxis(new ArrayList<>());
        resModel.setYoyThisYearYAxis(new ArrayList<>());
        resModel.setYoyRateYAxis(new ArrayList<>());
        resModel.setYoyLastYearLegend(new String());
        resModel.setYoyThisYearLegend(new String());

        //同比,暂不实现(无去年数据,看用户需求吧)

        return resModel;
    }

    public TyrqStatisticsModel getStatisticsData(String unitCode) {
        //模拟数据
        if (unitCode.contains(BaseConstant.SPECIAL_UNIT_CODE)) {
            return generateMockData();
        }
        TyrqStatisticsModel statisticsModel = new TyrqStatisticsModel();
        List<StationAccModel> accModels = stationAccService.findAllStationAccListByUnitCode(unitCode);

        statisticsModel.setDeviceCount(accModels.size());//设备总数
        //Date dtEndTime = DateUtil.getMidnightDate(new Date());
        //2024年还没有数据,使用23年数据展示
        Date dtEndTime = DateUtil.parseTimeStr("20240101000000", "yyyyMMddHHmmss");
        Date dtStartTime = DateUtil.getOtherDateByCurrentDate(dtEndTime, -31);

        /**  ------------- 开始计算 近30天 数据 -------------   */
        Map<String, Map<Date, BigDecimal>> recentUsageMap = new HashMap<>();
        for (StationAccModel accModel : accModels) {
            List<TAiread> aireadModels = getAireadData(accModel.getStationCode(), dtStartTime, dtEndTime);

            Map<Date, BigDecimal> usageMap = new HashMap<>();
            Date date = dtStartTime;
            while (date.compareTo(dtEndTime) < 0) {
                Date finalDate0 = date;
                Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalDate0)).findFirst();
                Date finalDate1 = DateUtil.getOtherDateByCurrentDate(date, 1);

                //循环条件加一天
                date = DateUtil.getOtherDateByCurrentDate(date, 1);
                //没有这一天的起始时间,用量设置为0
                if (!optional0.isPresent()) {
                    usageMap.put(finalDate0, BigDecimal.ZERO);
                    continue;
                }

                Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalDate1)).findFirst();
                if (!optional1.isPresent()) {
                    usageMap.put(finalDate0, BigDecimal.ZERO);
                    continue;
                }

                TAiread airead0 = optional0.get();
                TAiread airead1 = optional1.get();

                BigDecimal value = airead1.getResultValue().subtract(airead0.getResultValue());
                usageMap.put(finalDate0, value);
            }
            recentUsageMap.put(accModel.getStationCode(), usageMap);
        }

        Date date = dtStartTime;

        //最近用量X轴名称
        List<String> recentUsageXAxis = new ArrayList<>();
        List<BigDecimal> recentUsageYAxis = new ArrayList<>();

        BigDecimal usageSum = BigDecimal.ZERO;
        while (date.compareTo(dtEndTime) < 0) {
            recentUsageXAxis.add(DateUtil.formateDate(date, "MM/dd"));
            usageSum = BigDecimal.ZERO;
            for (String stationCode : recentUsageMap.keySet()) {
                Map<Date, BigDecimal> usageMap = recentUsageMap.get(stationCode);
                if (usageMap.containsKey(date)) {
                    usageSum = usageSum.add(usageMap.get(date));
                }
            }
            date = DateUtil.getOtherDateByCurrentDate(date, 1);
            recentUsageYAxis.add(usageSum);
        }
        statisticsModel.setYesterdayUsage(usageSum.intValue());//昨日用量

        statisticsModel.setRecentUsageXAxis(recentUsageXAxis);//最近用量-X轴名称
        statisticsModel.setRecentUsageYAxis(recentUsageYAxis);//最近用量-Y轴数据

        BigDecimal yearUsage = BigDecimal.ZERO;

        List<Date> chianDateList = new ArrayList<>();//环比使用
        /**  ------------- 开始计算 同比 数据 -------------   */
        //近12个月的同比
        //当前假设数据是完整的,每天都有0点数据()
        List<String> yoyXAxis = new ArrayList<>();//同比-X轴名称
        List<BigDecimal> yoyThisYearYAxis = new ArrayList<>();//同比-今年Y轴数据
        List<BigDecimal> yoyLastYearYAxis = new ArrayList<>();//同比-去年Y轴数据
        List<BigDecimal> yoyRateYAxis = new ArrayList<>();//同比-增长率

        date = dtEndTime;
        for (int i = 12; i > 0; i--) {
            Date temp = DateUtil.getOtherDateByMonth(date, -1 * i);
            yoyXAxis.add(DateUtil.formateDate(temp, "MM"));
            chianDateList.add(temp);
            //当前年
            Date curMonthFirstDay = DateUtil.getFirstDayOfMonth(temp);
            Date nextMonthFirstDay = DateUtil.getOtherDateByMonth(curMonthFirstDay, 1);

            //上一年
            Date preYCurMonthFirstDay = DateUtil.getOtherDateByYear(curMonthFirstDay, -1);
            Date preYNextMonthFirstDay = DateUtil.getLastDayOfMonth(preYCurMonthFirstDay);

            BigDecimal curValue = BigDecimal.ZERO;
            BigDecimal lstValue = BigDecimal.ZERO;

            for (StationAccModel accModel : accModels) {
                List<TAiread> curMonthList = getAireadData(accModel.getStationCode(), curMonthFirstDay, nextMonthFirstDay);

                //当前是如果本月数据低于10条,就不计算了
                if (curMonthList.size() > 10) {
                    curValue = curValue.add(curMonthList.get(curMonthList.size() - 1).getResultValue().subtract(curMonthList.get(0).getResultValue()));
                }

                List<TAiread> preMonthList = getAireadData(accModel.getStationCode(), preYCurMonthFirstDay, preYNextMonthFirstDay);
                if (preMonthList.size() > 10) {
                    lstValue = lstValue.add(preMonthList.get(preMonthList.size() - 1).getResultValue().subtract(preMonthList.get(0).getResultValue()));
                }
            }

            //暂时用 202312
            if (DateUtil.formateDate(temp, "yyyyMM").equals("202312")) {
                statisticsModel.setMonthUsage(curValue.intValue());
            }

            yoyThisYearYAxis.add(curValue);
            yoyLastYearYAxis.add(lstValue);

            yearUsage = yearUsage.add(curValue);

            //同比增长率:(本期数 - 同期数) / |同期数| × 100%
            if (curValue.compareTo(BigDecimal.ZERO) == 0 || lstValue.compareTo(BigDecimal.ZERO) == 0) {
                yoyRateYAxis.add(BigDecimal.ZERO);
            } else {
                /*BigDecimal result = curValue.divide(lstValue, new MathContext(10, RoundingMode.HALF_UP));
                result = result.subtract(BigDecimal.ONE).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
                yoyRateYAxis.add(result);*/

                BigDecimal result = curValue.subtract(lstValue).divide(lstValue.abs(), new MathContext(4, RoundingMode.HALF_UP));
                result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                yoyRateYAxis.add(result);

                //yoyRateYAxis.add((curValue.divide(lstValue)).subtract(new BigDecimal(1)).multiply(new BigDecimal(100)).setScale(2));
            }
        }
        statisticsModel.setYoyXAxis(yoyXAxis);
        statisticsModel.setYoyLastYearYAxis(yoyLastYearYAxis);
        statisticsModel.setYoyThisYearYAxis(yoyThisYearYAxis);
        statisticsModel.setYoyRateYAxis(yoyRateYAxis);

        statisticsModel.setYearUsage(yearUsage);

        /**  ------------- 开始计算 环比 数据 -------------   */
        //环比增长率 = (本期数 - 上期数) / 上期数 × 100%
        List<String> chainXAxis = new ArrayList<>();//环比-X轴名称
        List<BigDecimal> chainValueYAxis = new ArrayList<>();//环比-增长量
        List<BigDecimal> chainRateYAxis = new ArrayList<>();//环比-增长率

        for (int i = 1; i < chianDateList.size(); i++) {
            BigDecimal curPeriodValue = yoyThisYearYAxis.get(i);
            BigDecimal lstPeriodValue = yoyLastYearYAxis.get(i - 1);

            chainXAxis.add(DateUtil.formateDate(chianDateList.get(i), "MM"));

            chainValueYAxis.add(curPeriodValue.subtract(lstPeriodValue));

            if (curPeriodValue.compareTo(BigDecimal.ZERO) == 0 || lstPeriodValue.compareTo(BigDecimal.ZERO) == 0) {
                chainRateYAxis.add(BigDecimal.ZERO);
            } else {
                //BigDecimal result = curPeriodValue.divide(lstPeriodValue, new MathContext(10, RoundingMode.HALF_UP));
                //result = result.subtract(BigDecimal.ONE).multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
                //chainRateYAxis.add(result);

                BigDecimal result = curPeriodValue.subtract(lstPeriodValue).divide(lstPeriodValue, new MathContext(4, RoundingMode.HALF_UP));
                result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                chainRateYAxis.add(result);
            }
        }
        statisticsModel.setChainXAxis(chainXAxis);
        statisticsModel.setChainValueYAxis(chainValueYAxis);
        statisticsModel.setChainRateYAxis(chainRateYAxis);

        return statisticsModel;
    }

    /**
     * 根据条件获取读数列表
     *
     * @param stationCode
     * @param startTime
     * @param endTime
     * @return
     */
    public List<TAiread> getAireadData(String stationCode, Date startTime, Date endTime) {
        //未使用TAireadService,是因为返回参数不符合,并且会查遥测站台账、服务侧识别等无关信息
        TAireadExample example = new TAireadExample();
        TAireadExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(stationCode);
        criteria.andSampleTimeGreaterThanOrEqualTo(startTime);
        criteria.andSampleTimeLessThanOrEqualTo(endTime);
        criteria.andResultValueIsNotNull();
        //不等于0,不严谨,但安装时有未识别的数据 值=0
        //criteria.andResultValueNotEqualTo(BigDecimal.ZERO); //2025-07-31 guozhao 这样会导致前端出错
        //防止数据乱,过滤未审数据(整点后又多一条的情况,采样时间不同,后者又经过审核,会导致统计不了用量)

        //因生态环境部又添加 2025-06-19 guozhao
        criteria.andReviewFlagEqualTo(BaseConstant.VALID_FLAG);
        criteria.andReviewResultFlagLessThan(ReviewResultType.UNRECOGNIZABLE.getCode());
        example.setOrderByClause("SAMPLE_TIME");
        return aireadMapper.selectByExample(example);
    }

    /**
     * --- 模拟数据 ----
     */
    private TyrqStatisticsModel generateMockData() {
        TyrqStatisticsModel model = new TyrqStatisticsModel();
        //基本
        model.setDeviceCount(66);
        model.setYesterdayUsage(120);
        model.setMonthUsage(360);
        model.setYearUsage(new BigDecimal(980));

        Random random = new Random();
        //最近
        List<String> recentUsageXAxis = new ArrayList<>();
        List<BigDecimal> recentUsageYAxis = new ArrayList<>();
        for (int i = 2; i < 32; i++) {
            recentUsageXAxis.add(String.format("12/%d", i));
            recentUsageYAxis.add(new BigDecimal(random.nextInt(101) + 100));
        }
        model.setRecentUsageXAxis(recentUsageXAxis);
        model.setRecentUsageYAxis(recentUsageYAxis);

        //同比
        model.setYoyLastYearLegend("2022");
        model.setYoyThisYearLegend("2023");

        List<String> yoyXAxis = new ArrayList<>();
        List<BigDecimal> yoyLastYearYAxis = new ArrayList<>();
        List<BigDecimal> yoyThisYearYAxis = new ArrayList<>();
        List<BigDecimal> yoyRateYAxis = new ArrayList<>();

        for (int i = 1; i < 13; i++) {
            yoyXAxis.add(String.format("%d月", i));
            BigDecimal lstValue = new BigDecimal(random.nextInt(101) + 100);
            BigDecimal curValue = new BigDecimal(random.nextInt(150) + 110);

            yoyLastYearYAxis.add(lstValue);
            yoyThisYearYAxis.add(curValue);

            BigDecimal result = curValue.subtract(lstValue).divide(lstValue.abs(), new MathContext(4, RoundingMode.HALF_UP));
            result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
            yoyRateYAxis.add(result);
        }
        model.setYoyXAxis(yoyXAxis);
        model.setYoyLastYearYAxis(yoyLastYearYAxis);
        model.setYoyThisYearYAxis(yoyThisYearYAxis);
        model.setYoyRateYAxis(yoyRateYAxis);

        //环比
        List<String> chainXAxis = new ArrayList<>();//环比-X轴名称
        List<BigDecimal> chainValueYAxis = new ArrayList<>();//环比-增长量
        List<BigDecimal> chainRateYAxis = new ArrayList<>();//环比-增长率

        for (int i = 0; i < yoyThisYearYAxis.size() - 1; i++) {
            BigDecimal lstPeriodValue = yoyThisYearYAxis.get(0);
            BigDecimal curPeriodValue = yoyThisYearYAxis.get(i + 1);

            chainXAxis.add(String.format("%d月", i + 2));
            chainValueYAxis.add(curPeriodValue.subtract(lstPeriodValue));

            BigDecimal result = curPeriodValue.subtract(lstPeriodValue).divide(lstPeriodValue, new MathContext(4, RoundingMode.HALF_UP));
            result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
            chainRateYAxis.add(result);
        }
        model.setChainXAxis(chainXAxis);
        model.setChainValueYAxis(chainValueYAxis);
        model.setChainRateYAxis(chainRateYAxis);

        return model;
    }

    /**
     * 下面的单个站点的统计 - 开始
     **/
    public TyrqStatisticsModel getStatisticsDataByStationCode11(String stationCode) {
        TyrqStatisticsModel statisticsModel = new TyrqStatisticsModel();
        statisticsModel.setDeviceCount(1);//设备总数,单站点了

        Date dtEndTime = new Date();
        Date dtStartTime = DateUtil.getOtherDateByCurrentDate(dtEndTime, -30);

        Map<String, Map<Date, BigDecimal>> recentUsageMap = new HashMap<>();
        List<TAiread> aireadModels = getAireadData(stationCode, dtStartTime, dtEndTime);

        Date date = dtStartTime;

        /**  ------------- 开始计算 近30天 数据 开始 -------------   */
        //最近用量X轴名称
        List<String> recentUsageXAxis = new ArrayList<>();
        List<BigDecimal> recentUsageYAxis = new ArrayList<>();

        while (date.compareTo(dtEndTime) < 0) {
            Date finalDate0 = date;
            Optional<TAiread> optional0 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalDate0)).findFirst();
            Date finalDate1 = DateUtil.getOtherDateByCurrentDate(date, 1);

            recentUsageXAxis.add(DateUtil.formateDate(date, "MM/dd"));

            //循环条件加一天
            date = DateUtil.getOtherDateByCurrentDate(date, 1);
            //没有这一天的起始时间,用量设置为0
            if (!optional0.isPresent()) {
                recentUsageYAxis.add(BigDecimal.ZERO);
                continue;
            }

            Optional<TAiread> optional1 = aireadModels.stream().filter(s -> s.getSampleTime().equals(finalDate1)).findFirst();
            if (!optional1.isPresent()) {
                recentUsageYAxis.add(BigDecimal.ZERO);
                continue;
            }

            TAiread airead0 = optional0.get();
            TAiread airead1 = optional1.get();

            BigDecimal value = airead1.getResultValue().subtract(airead0.getResultValue());
            recentUsageYAxis.add(value);
        }
        statisticsModel.setYesterdayUsage(recentUsageYAxis.get(recentUsageYAxis.size() - 1).intValue());//昨日用量
        /**  ------------- 开始计算 近30天 数据 结束 -------------   */

        BigDecimal yearUsage = BigDecimal.ZERO;
        List<Date> chianDateList = new ArrayList<>();//环比使用
        /**  ------------- 开始计算 同比 数据 开始 -------------   */
        //近12个月的同比
        //当前假设数据是完整的,每天都有0点数据()
        List<String> yoyXAxis = new ArrayList<>();//同比-X轴名称
        List<BigDecimal> yoyThisYearYAxis = new ArrayList<>();//同比-今年Y轴数据
        List<BigDecimal> yoyLastYearYAxis = new ArrayList<>();//同比-去年Y轴数据
        List<BigDecimal> yoyRateYAxis = new ArrayList<>();//同比-增长率

        date = dtEndTime;
        for (int i = 12; i > 0; i--) {
            Date temp = DateUtil.getOtherDateByMonth(date, -1 * i);
            yoyXAxis.add(DateUtil.formateDate(temp, "MM"));
            chianDateList.add(temp);
            //当前年
            Date curMonthFirstDay = DateUtil.getFirstDayOfMonth(temp);
            Date nextMonthFirstDay = DateUtil.getOtherDateByMonth(curMonthFirstDay, 1);

            //上一年
            Date preYCurMonthFirstDay = DateUtil.getOtherDateByYear(curMonthFirstDay, -1);
            Date preYNextMonthFirstDay = DateUtil.getLastDayOfMonth(preYCurMonthFirstDay);

            BigDecimal curValue = BigDecimal.ZERO;
            BigDecimal lstValue = BigDecimal.ZERO;

            List<TAiread> curMonthList = getAireadData(stationCode, curMonthFirstDay, nextMonthFirstDay);

            //当前是如果本月数据低于10条,就不计算了
            if (curMonthList.size() > 10) {
                curValue = curValue.add(curMonthList.get(curMonthList.size() - 1).getResultValue().subtract(curMonthList.get(0).getResultValue()));
            }

            List<TAiread> preMonthList = getAireadData(stationCode, preYCurMonthFirstDay, preYNextMonthFirstDay);
            if (preMonthList.size() > 10) {
                lstValue = lstValue.add(preMonthList.get(preMonthList.size() - 1).getResultValue().subtract(preMonthList.get(0).getResultValue()));
            }

            //暂时用 202312
            if (DateUtil.formateDate(temp, "yyyyMM").equals("202312")) {
                statisticsModel.setMonthUsage(curValue.intValue());
            }

            yoyThisYearYAxis.add(curValue);
            yoyLastYearYAxis.add(lstValue);

            yearUsage = yearUsage.add(curValue);

            //同比增长率:(本期数 - 同期数) / |同期数| × 100%
            if (curValue.compareTo(BigDecimal.ZERO) == 0 || lstValue.compareTo(BigDecimal.ZERO) == 0) {
                yoyRateYAxis.add(BigDecimal.ZERO);
            } else {
                BigDecimal result = curValue.subtract(lstValue).divide(lstValue.abs(), new MathContext(4, RoundingMode.HALF_UP));
                result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                yoyRateYAxis.add(result);

            }
        }
        statisticsModel.setYoyXAxis(yoyXAxis);
        statisticsModel.setYoyLastYearYAxis(yoyLastYearYAxis);
        statisticsModel.setYoyThisYearYAxis(yoyThisYearYAxis);
        statisticsModel.setYoyRateYAxis(yoyRateYAxis);

        statisticsModel.setYearUsage(yearUsage);
        /**  ------------- 开始计算 同比 数据 结束 -------------   */

        /**  ------------- 开始计算 环比 数据 开始 -------------   */
        //环比增长率 = (本期数 - 上期数) / 上期数 × 100%
        List<String> chainXAxis = new ArrayList<>();//环比-X轴名称
        List<BigDecimal> chainValueYAxis = new ArrayList<>();//环比-增长量
        List<BigDecimal> chainRateYAxis = new ArrayList<>();//环比-增长率

        for (int i = 1; i < chianDateList.size(); i++) {
            BigDecimal curPeriodValue = yoyThisYearYAxis.get(i);
            BigDecimal lstPeriodValue = yoyLastYearYAxis.get(i - 1);

            chainXAxis.add(DateUtil.formateDate(chianDateList.get(i), "MM"));

            chainValueYAxis.add(curPeriodValue.subtract(lstPeriodValue));

            if (curPeriodValue.compareTo(BigDecimal.ZERO) == 0 || lstPeriodValue.compareTo(BigDecimal.ZERO) == 0) {
                chainRateYAxis.add(BigDecimal.ZERO);
            } else {
                BigDecimal result = curPeriodValue.subtract(lstPeriodValue).divide(lstPeriodValue, new MathContext(4, RoundingMode.HALF_UP));
                result = result.multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                chainRateYAxis.add(result);
            }
        }
        statisticsModel.setChainXAxis(chainXAxis);
        statisticsModel.setChainValueYAxis(chainValueYAxis);
        statisticsModel.setChainRateYAxis(chainRateYAxis);
        /**  ------------- 开始计算 环比 数据 结束 -------------   */

        return statisticsModel;
    }
    /** 下面的单个站点的统计 - 结束 **/
}
