package com.ho.business.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.Device;
import com.ho.business.entity.ElecMeterValue;
import com.ho.business.entity.Station;
import com.ho.business.entity.TranslateProvince;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.mapper.TranslateProvinceMapper;
import com.ho.business.service.*;
import com.ho.business.vo.req.bigScreen.CommonBigScreenReq;
import com.ho.business.vo.req.cockpit.CockpitReqVO;
import com.ho.business.vo.req.colCount.ColCountReq;
import com.ho.business.vo.resp.CountEleData;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.ProvinceStation;
import com.ho.business.vo.resp.colCount.ColCountResp;
import com.ho.business.vo.resp.iargeScreen.*;
import com.ho.business.vo.resp.mppt.MpptActiveVo;
import com.ho.business.vo.resp.profit.DayProfitType;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.BigDecimalUtil;
import com.ho.datacollect.api.constant.DataCollectConstant;
import com.ho.flow.vo.req.event.EventReqPageVO;
import com.ho.flow.vo.resp.event.EventDayNum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author gyan
 * @desc: TODO
 * @DateTime: 2023/12/13 17:39
 */
@Service
@Slf4j
public class IargeScreenShowServiceImpl implements IargeScreenShowService {
    @Autowired
    StationService stationService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @Autowired
    ElecMeterValueService elecMeterValueService;

    @Autowired
    EarningsCalculateService earningsCalculateService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    StationHomeService stationHomeService;

    @Autowired
    ColCountService colCountService;

    @Autowired
    FlowFeignClient flowFeignClient;

    @Autowired
    RedisService redisService;

    @Autowired
    TranslateProvinceMapper translateProvinceMapper;

    @Autowired
    OpenStationService openStationService;

    @Autowired
    EarningsCalculateMpptService earningsCalculateMpptService;


    private final static BigDecimal value = new BigDecimal("0.475");
    private final static BigDecimal parameter = new BigDecimal("18.3");
    private final static BigDecimal four = new BigDecimal("0.4");
    private final static BigDecimal fours = new BigDecimal("40");
    private final static BigDecimal coalPrice = new BigDecimal("0.6");//煤炭价格
    private final static Integer maxSize = 30;
    private final static BigDecimal hundred = new BigDecimal(100);
    private final static int FENGStationId = 418;
    private final static int LianStationId = 349;
    private final static int LianSrc = 432100001;


    public static final Integer CHARGE = 0;

    public static final Integer DISCHARGE = 1;

    private Map<String, PriceValue> getPrice() {
        Map<String, PriceValue> listMap = new HashMap<>();
        PriceValue price = new PriceValue();
        price.setPeakPrice(new BigDecimal("1.075592"));
        price.setLowPrice(new BigDecimal("0.220103"));
        listMap.put("陕西", price);
        PriceValue priceValue = new PriceValue();
        priceValue.setPeakPrice(new BigDecimal("1.15766875"));
        priceValue.setLowPrice(new BigDecimal("0.22646875"));
        listMap.put("山东", priceValue);
        PriceValue priceValue1 = new PriceValue();
        priceValue1.setPeakPrice(new BigDecimal("1.203"));
        priceValue1.setLowPrice(new BigDecimal("0.3141"));
        listMap.put("浙江", priceValue1);
        PriceValue priceValue2 = new PriceValue();
        priceValue2.setPeakPrice(new BigDecimal("1.218531"));
        priceValue2.setLowPrice(new BigDecimal("0.362067"));
        listMap.put("海南", priceValue2);
        PriceValue priceValue3 = new PriceValue();
        priceValue3.setPeakPrice(new BigDecimal("1.3309"));
        priceValue3.setLowPrice(new BigDecimal("0.2699"));
        listMap.put("江苏", priceValue3);
        PriceValue priceValue4 = new PriceValue();
        priceValue4.setPeakPrice(new BigDecimal("1.5842"));
        priceValue4.setLowPrice(new BigDecimal("0.3056"));
        listMap.put("上海", priceValue4);
        PriceValue priceValue5 = new PriceValue();
        priceValue5.setPeakPrice(new BigDecimal("1.218531"));
        priceValue5.setLowPrice(new BigDecimal("0.362067"));
        listMap.put("广东", priceValue5);
        PriceValue priceValue6 = new PriceValue();
        priceValue6.setPeakPrice(new BigDecimal("1.177691"));
        priceValue6.setLowPrice(new BigDecimal("0.36302"));
        listMap.put("吉林", priceValue6);
        PriceValue priceValue7 = new PriceValue();
        priceValue7.setPeakPrice(new BigDecimal("1.2785"));
        priceValue7.setLowPrice(new BigDecimal("0.32151"));
        listMap.put("四川", priceValue7);
        PriceValue priceValue8 = new PriceValue();
        priceValue8.setPeakPrice(new BigDecimal("1.147"));
        priceValue8.setLowPrice(new BigDecimal("0.3007"));
        listMap.put("安徽", priceValue8);
        PriceValue priceValue9 = new PriceValue();
        priceValue9.setPeakPrice(new BigDecimal("1.282023"));
        priceValue9.setLowPrice(new BigDecimal("0.350625"));
        listMap.put("河南", priceValue9);
        PriceValue priceValue10 = new PriceValue();
        priceValue10.setPeakPrice(new BigDecimal("1.112256"));
        priceValue10.setLowPrice(new BigDecimal("0.351528"));
        listMap.put("河北", priceValue10);
        PriceValue priceValue11 = new PriceValue();
        priceValue11.setPeakPrice(new BigDecimal("1.1460605"));
        priceValue11.setLowPrice(new BigDecimal("0.3236025"));
        listMap.put("江西", priceValue11);
        PriceValue priceValue12 = new PriceValue();
        priceValue12.setPeakPrice(new BigDecimal("0.724018"));
        priceValue12.setLowPrice(new BigDecimal("0.311498"));
        listMap.put("内蒙古自治区", priceValue12);
        PriceValue priceValue13 = new PriceValue();
        priceValue13.setPeakPrice(new BigDecimal("1.055203"));
        priceValue13.setLowPrice(new BigDecimal("0.324402"));
        listMap.put("黑龙江", priceValue13);
        PriceValue priceValue14 = new PriceValue();
        priceValue14.setPeakPrice(new BigDecimal("1.055203"));
        priceValue14.setLowPrice(new BigDecimal("0.324402"));
        listMap.put("湖北", priceValue14);
        return listMap;

    }

    /**
     * 返回电站所对应的省份电价
     */
    private Map<Integer, PriceValue> getStationPrice(List<Station> stations) {
        Map<Integer, PriceValue> listMap = new HashMap<>();
        //省份分组
        List<ProvinceStation> province = getProvince(stations);
        //各省份电价
        Map<String, PriceValue> price = getPrice();
        for (ProvinceStation provinceStation : province) {
            if (price.containsKey(provinceStation.getName())) {
                PriceValue priceValue = price.get(provinceStation.getName());
                List<Station> list = provinceStation.getList();
                for (Station station : list) {
                    listMap.put(station.getId(), priceValue);
                }
            }
        }
        return listMap;
    }


    @Override
    public AnnualOverviewResp getOverviewData() {
        AnnualOverviewResp annualOverviewResp = getOverviewDatas(stationService.selectAll());
        return annualOverviewResp;
    }

/*    @Override
    public AnnualOverviewResp getDayDate(List<Station> list) {
        String key = "screenGroupData:";
        AnnualOverviewResp annualOverviewResp = getOverviewDatas(list);
        annualOverviewResp.setDate(new Date());
        redisService.set(key, annualOverviewResp);
        return annualOverviewResp;
    }*/

    private AnnualPvOverviewResp getPvOverviewDatas(List<Station> list){
        AnnualPvOverviewResp annualOverviewResp = new AnnualPvOverviewResp();
        //装机容量
        BigDecimal capacity = BigDecimal.ZERO;
        //电站总数
        Integer stationNumber = list.size();
        BigDecimal todayIncone = BigDecimal.ZERO;
        BigDecimal dailyReleaseElec = BigDecimal.ZERO;
        BigDecimal yearIncone = BigDecimal.ZERO;
        BigDecimal totalIncome = BigDecimal.ZERO;
        BigDecimal yearReleaseElec = BigDecimal.ZERO;
        BigDecimal totalReleaseElec = BigDecimal.ZERO;
        //今年开始时间、结束时间
        DateTime begin = DateUtil.beginOfYear(new Date());
        String beginString = DateUtil.format(begin, CommonConstant.DATE_YMD);
        String endString = DateUtil.format(DateUtil.endOfYear(new Date()), CommonConstant.DATE_YMD);
        for (Station station : list) {
            //装机容量进行累加
            BigDecimal capacityStation = station.getCapacity();
            if (capacityStation != null) {
                capacity = capacity.add(capacityStation);
            }
            String key = RedisKeyConstant.PV.STATION_PV_TODAY_PROFIT + station.getId();
            // 今日收益
            BigDecimal tIncone = (BigDecimal)redisService.get(key);
            todayIncone = todayIncone.add(tIncone==null?BigDecimal.ZERO:tIncone);
            // 年收益
            BigDecimal yIncone = earningsCalculateMpptService.countAllPvIncome(station.getId(),beginString,endString);
            yearIncone = yearIncone.add(yIncone);
            // 累计收益
            BigDecimal allIncone = earningsCalculateMpptService.countAllPvIncome(station.getId(),null,null);
            totalIncome = totalIncome.add(allIncone);
            // 日发电
            MpptActiveVo todayPv = openStationService.getPvActivePower(station.getId());
            dailyReleaseElec = dailyReleaseElec.add(todayPv.getDailyReleaseElec());
            // 年发电
            BigDecimal yReleaseElec = elecMeterValueService.selectSumByType(station.getId(),DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,beginString,endString,null);
            yearReleaseElec = yearReleaseElec.add(yReleaseElec);
            // 累计发电
            BigDecimal allReleaseElec = elecMeterValueService.selectSumValue(station.getId(),DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,null);
            totalReleaseElec = totalReleaseElec.add(allReleaseElec);
        }
        //装机容量、电站数量
        annualOverviewResp.setCapacity(capacity);
        annualOverviewResp.setStationNumber(stationNumber);
        // 今日收益、年收益、累计收益
        annualOverviewResp.setTodayIncone(todayIncone);
        annualOverviewResp.setYearIncone(yearIncone.add(todayIncone));
        annualOverviewResp.setTotalIncome(totalIncome.add(todayIncone));
        //今日发电量、年发电量、累计发电量
        annualOverviewResp.setDailyReleaseElec(dailyReleaseElec);
        annualOverviewResp.setYearReleaseElec(yearReleaseElec.add(dailyReleaseElec));
        annualOverviewResp.setTotalReleaseElec(totalReleaseElec.add(dailyReleaseElec));
        return annualOverviewResp;
    }

    private AnnualOverviewResp getOverviewDatas(List<Station> list) {
        AnnualOverviewResp annualOverviewResp = new AnnualOverviewResp();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        //装机容量
        BigDecimal capacity = BigDecimal.ZERO;
        //电站总数
        Integer stationNumber = stations.size();
        for (Station station : stations) {
            //装机容量进行累加
            BigDecimal capacityStation = station.getCapacity();
            if (capacityStation != null) {
                capacity = capacity.add(capacityStation);
            }
        }
        //set装机容量/电站数量
        annualOverviewResp.setCapacity(capacity);
        annualOverviewResp.setStationNumber(stationNumber);
        //日充/日放（日冻结表计算）
        BigDecimal dayCharge = BigDecimal.ZERO;
        BigDecimal dayDischarge = BigDecimal.ZERO;
        StringBuffer stationDayLog = new StringBuffer();
//        ColCountReq colCountReq = new ColCountReq();
//        colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
//        List<Integer> ids = stations.stream().map(Station::getId).collect(Collectors.toList());
//        colCountReq.setIds(ids);
//        List<ColCountResp> colCountResps = colCountService.selectByParam(colCountReq);
//        Map<Integer, String> stationMapAndType = new HashMap<>();
//        if (colCountResps != null) {
//            stationMapAndType = colCountResps.stream().collect(Collectors.toMap(ColCountResp::getStationId, ColCountResp::getDeviceType, (k1, k2) -> k1));
//        }
        for (Station station : stations) {
//            StationReq req = new StationReq();
//            req.setStationId(station.getId());
//            req.setDeviceType(stationMapAndType.get(req.getStationId()));
            BigDecimal dailyChargeElec = BigDecimal.ZERO;
            BigDecimal dailyDischargeElec = BigDecimal.ZERO;
            //  CountEleData countEleData = stationHomeService.getCountEleData(req);
            CountEleData countEleData = getByRedisData(station.getId());
            if (null == countEleData || null == countEleData.getDailyChargeElec() || null == countEleData.getDailyDischargeElec()) {
                dailyChargeElec = BigDecimal.ZERO;
                dailyDischargeElec = BigDecimal.ZERO;
            } else {
                //日充电量{
                dailyChargeElec = countEleData.getDailyChargeElec();
                //日放电量
                dailyDischargeElec = countEleData.getDailyDischargeElec();
            }

            if (dailyChargeElec.compareTo(BigDecimal.ZERO) < 0 || dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0) {
                log.info("电站：{}日充日放小于0", station.getName());
                continue;
            }
            if (dailyChargeElec != null) {
                if (station.getId() == FENGStationId) {
                    dayCharge = dayCharge.add(dailyChargeElec.multiply(new BigDecimal("1000")));
                } else {
                    dayCharge = dayCharge.add(dailyChargeElec);
                }
            }
            if (dailyDischargeElec != null) {
                if (station.getId() == FENGStationId) {
                    dayDischarge = dayDischarge.add(dailyDischargeElec.multiply(new BigDecimal("1000")));
                } else {
                    dayDischarge = dayDischarge.add(dailyDischargeElec);
                }
            }
            stationDayLog.append(station.getId()).append("充电量").append(dailyChargeElec).append("放电量").append(dailyDischargeElec).append("/");
        }

        //set日充/日放（日冻结表计算）/*总充/总放（日冻结表计算）
        annualOverviewResp.setDayCharge(dayCharge);
        annualOverviewResp.setDayDischarge(dayDischarge);
        log.info("电站日充日放" + stationDayLog.toString());

        if (!stations.isEmpty()) {
//            AnnualOverviewResp overviewProfit = getOverviewProfit(stations);
            AnnualOverviewResp overviewProfit = getEarningsCalculate(stations);
            annualOverviewResp.setYestProfit(overviewProfit.getYestProfit()==null?null:overviewProfit.getYestProfit().multiply(new BigDecimal("10000")));
            annualOverviewResp.setYearProfit(overviewProfit.getYearProfit()==null?null:overviewProfit.getYearProfit().multiply(new BigDecimal("10000")));
            annualOverviewResp.setTotalProfit(overviewProfit.getTotalProfit()==null?null:overviewProfit.getTotalProfit().multiply(new BigDecimal("10000")));
            //时间当年
            DateTime begin = DateUtil.beginOfYear(new Date());
            String beginString = DateUtil.format(begin, CommonConstant.DATE_YMD);
            String endString = DateUtil.format(DateUtil.endOfYear(new Date()), CommonConstant.DATE_YMD);
            AnnualOverviewResp incomeShow = getIncomeShow(stations, beginString, endString);
            annualOverviewResp.setYearCharge(incomeShow.getYearCharge());
            annualOverviewResp.setYearDischarge(incomeShow.getYearDischarge());
            AnnualOverviewResp incomeShow1 = getIncomeShow(stations, null, null);
            annualOverviewResp.setTotalCharge(incomeShow1.getYearCharge());
            annualOverviewResp.setTotalDischarge(incomeShow1.getYearDischarge());
        }
        return annualOverviewResp;
    }

    private AnnualOverviewResp getOverviewProfit(List<Station> stations) {
        AnnualOverviewResp annualOverviewResp = new AnnualOverviewResp();
        CockpitReqVO vo = new CockpitReqVO();
        vo.setType(CommonConstant.DAY);
        List<AnnualChartValue> profitCurve = getProfitCurve(vo, stations);
        //昨日
        AnnualChartValue annualChartValue = profitCurve.get(profitCurve.size() - 1);
        annualOverviewResp.setYestProfit(annualChartValue.getProfit());
        vo.setType(CommonConstant.MONTH);
        BigDecimal monthProfit = BigDecimal.ZERO;
        List<AnnualChartValue> monthProfitCurve = getProfitCurve(vo, stations);
        for (AnnualChartValue chartValue : monthProfitCurve) {
            monthProfit = monthProfit.add(chartValue.getProfit());
        }
        annualOverviewResp.setYearProfit(monthProfit);
        BigDecimal yearProfit = BigDecimal.ZERO;
        vo.setType(CommonConstant.YEAR);
        List<AnnualChartValue> yearProfitCurve = getProfitCurve(vo, stations);
        for (AnnualChartValue chartValue : yearProfitCurve) {
            yearProfit = yearProfit.add(chartValue.getProfit());
        }
        annualOverviewResp.setTotalProfit(yearProfit);
        return annualOverviewResp;
    }


    private AnnualOverviewResp getIncomeShow(List<Station> stations, String beginString, String endString) {
//        Map<Integer, PriceValue> stationPrice = getStationPrice(stations);
        AnnualOverviewResp annualOverviewResp = new AnnualOverviewResp();
        //昨日收益 所有已投运电站总放*1.3309-总充*0.2699
        //年收益
        /*储能年度收益概览
         * 1.年度充电成本 日充*0.2699+今年
         * 2.年度放电收益 日放*1.3309+今年
         * */
        //各站收益
        List<Subdata> list = new ArrayList<>();
        //年总充/年总放（日冻结表计算）或者总充/总放
        BigDecimal yearCharge = BigDecimal.ZERO;
        BigDecimal yearDischarge = BigDecimal.ZERO;
        List<ElecMeterValue> byTimeList = getByTimeList(stations, beginString, endString);
//        AnnualChartValue curveResult = getCurveResult(stationPrice, byTimeList);
//        annualOverviewResp.setYearProfit(curveResult.getProfit());
        List<ElecMeterValue> chargeList = new ArrayList<>();
        byTimeList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(i.getType())).forEach(s -> chargeList.add(s));
        List<ElecMeterValue> disList = new ArrayList<>();
        byTimeList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(i.getType())).forEach(s -> disList.add(s));
        for (ElecMeterValue elecMeterValue : chargeList) {
            if (FENGStationId == elecMeterValue.getStationId()) {
                yearCharge = yearCharge.add(elecMeterValue.getDigital().multiply(new BigDecimal("1000")));
            } else {
                yearCharge = yearCharge.add(elecMeterValue.getDigital());
            }

        }
        for (ElecMeterValue elecMeterValue : disList) {
            if (FENGStationId == elecMeterValue.getStationId()) {
                yearDischarge = yearDischarge.add(elecMeterValue.getDigital().multiply(new BigDecimal("1000")));
            } else {
                yearDischarge = yearDischarge.add(elecMeterValue.getDigital());
            }

        }
        //set年总充/年总放（日冻结表计算）或者总充/总放
        annualOverviewResp.setYearCharge(yearCharge);
        annualOverviewResp.setYearDischarge(yearDischarge);
        return annualOverviewResp;
    }


    //电站收益率排名->各电站总放/总充 倒排 和  //总收益（不按照时间进行计算）
    //        BigDecimal totalProfit;
    private IncomeListResp getIncomeList(List<Station> stations) {
        //拿到电站所对应省份的数据
        Map<Integer, PriceValue> stationPrice = getStationPrice(stations);
        IncomeListResp incomeListResp = new IncomeListResp();
        List<Subdata> list = new ArrayList<>();
        List<Subdata> efficiencyList = new ArrayList<>();
        //总充
        BigDecimal charge = BigDecimal.ZERO;
        //总放
        BigDecimal discharge = BigDecimal.ZERO;
        //总收益
        BigDecimal totalProfit = BigDecimal.ZERO;
        List<Integer> stationIds = null;
        if (stations.size() < CommonConstant.FIVE) {
            stationIds = stations.stream().map(Station::getId).collect(Collectors.toList());
        }
        List<ElecMeterValue> elecMeterValueList = elecMeterValueService.selectByStationIdsAndTime(stationIds, null, null, null);
        Map<String, BigDecimal> stationTypeMap = new HashMap<>();
        if (elecMeterValueList != null && !elecMeterValueList.isEmpty()) {
            stationTypeMap = elecMeterValueList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(i.getType()) ||
                    DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(i.getType())).collect(Collectors.toMap(i -> i.getStationId() + "," + i.getType(), ElecMeterValue::getDigital, (k1, k2) -> k1));
        }
        for (Station station : stations) {
            Subdata subdata = new Subdata();
            Subdata efficiencyData = new Subdata();
            BigDecimal totalCharge = stationTypeMap.get(station.getId() + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            BigDecimal totalDischarge = stationTypeMap.get(station.getId() + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            if (station.getId() == 349) {
                Integer srcId = 432100001;
                totalCharge = elecMeterValueService.selectSumByType(station.getId(),
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE, null, null, srcId);
                totalDischarge = elecMeterValueService.selectSumByType(station.getId(),
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE, null, null, srcId);
            }

            //各电站总放/总充
            if (totalCharge != null) {
                if (station.getId() == FENGStationId) {
                    charge = charge.add(totalCharge.multiply(new BigDecimal("1000")));
                } else {
                    charge = charge.add(totalCharge);
                }
            }
            if (totalDischarge != null) {
                if (station.getId() == FENGStationId) {
                    discharge = discharge.add(totalDischarge.multiply(new BigDecimal("1000")));
                } else {
                    discharge = discharge.add(totalDischarge);
                }
            }

            if (totalCharge != null && totalCharge.compareTo(new BigDecimal(0.00)) != 0) {
                BigDecimal divide = totalDischarge.divide(totalCharge, 6, BigDecimal.ROUND_HALF_UP);
                subdata.setIncomeValue(divide);
                BigDecimal divide1 = divide.multiply(hundred).setScale(2, BigDecimal.ROUND_HALF_UP);
                efficiencyData.setEfficiencyValue(divide1);
            } else {
                charge = charge.add(new BigDecimal(0.00));
                discharge = discharge.add(new BigDecimal(0.00));
                subdata.setIncomeValue(new BigDecimal(0.00));
                efficiencyData.setEfficiencyValue(new BigDecimal(0));
            }
            if (stationPrice.containsKey(station.getId())) {
                PriceValue priceValue = stationPrice.get(station.getId());
                if (totalCharge != null && totalDischarge != null) {
                    BigDecimal profit = totalDischarge.multiply(priceValue.getPeakPrice()).subtract(totalCharge.multiply(priceValue.getLowPrice()));
                    //总收益
                    totalProfit = totalProfit.add(profit);
                }
            }
            subdata.setStationId(station.getId());
            subdata.setStationName(station.getName());
            subdata.setCharge(totalCharge);
            subdata.setDischarge(totalDischarge);
            efficiencyData.setStationName(station.getName());
            efficiencyData.setStationCapacity(station.getCapacity());
            efficiencyData.setStationId(station.getId());
            list.add(subdata);
            //系统转换效率（放/充）
            efficiencyList.add(efficiencyData);

        }
        //倒叙
        list.stream().sorted(Comparator.comparing((Subdata::getIncomeValue)).reversed()).collect(Collectors.toList());
        efficiencyList.stream().sorted(Comparator.comparing((Subdata::getStationCapacity)).reversed()).collect(Collectors.toList());
        incomeListResp.setList(list);
        incomeListResp.setEfficiencyList(efficiencyList);
        incomeListResp.setTotalProfit(totalProfit);
        incomeListResp.setTotalChargeElec(charge);
        incomeListResp.setTotalDischargeElec(discharge);
        return incomeListResp;
    }


    @Override
    public EnergySavingRespVo getEnergySaving() {
        List<Station> list = stationService.selectAll();
        return getEnergySavingRespVo(list);
    }
    private EnergySavingRespVo getPvEnergySavingRespVo(List<Station> list){
        EnergySavingRespVo energySavingRespVo = new EnergySavingRespVo();
        AnnualPvOverviewResp vo = getPvOverviewDatas(list);
        BigDecimal totalReleaseElec = vo.getTotalReleaseElec();
        BigDecimal reductionCO2 = totalReleaseElec.multiply(value);
        energySavingRespVo.setReductionCO2(reductionCO2);

        //等效植树量  等效植树量=等效减排CO2/183/40
        BigDecimal treePlanting = reductionCO2.divide(parameter, 6, BigDecimal.ROUND_HALF_UP).divide(fours, 6, BigDecimal.ROUND_HALF_UP);
        energySavingRespVo.setTreePlanting(treePlanting);
        //等效节约煤 等效节约煤=所有电站总充*节约标准煤转换系数(04)
        BigDecimal equivalentCoal = totalReleaseElec.multiply(four);
        energySavingRespVo.setEquivalentCoal(equivalentCoal);
        //等效经济收入 等效经济收入=等效节约煤*煤价 (600元/吨)  等效节约煤此处单位为kg,故而单价调整为0.6元/kg
        energySavingRespVo.setIncome(equivalentCoal.multiply(coalPrice));
        return energySavingRespVo;
    }
    private EnergySavingRespVo getEnergySavingRespVo(List<Station> list) {
        EnergySavingRespVo energySavingRespVo = new EnergySavingRespVo();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        Map<Integer, PriceValue> stationPrice = getStationPrice(stations);
        IncomeListResp incomeList = getIncomeList(stations);
        List<Subdata> incomeListList = incomeList.getList();
        //总充/总放（日冻结表计算）
        BigDecimal totalCharge = BigDecimal.ZERO;
        BigDecimal totalDischarge = BigDecimal.ZERO;
        BigDecimal income = BigDecimal.ZERO;
        if (!incomeListList.isEmpty()) {
            for (Subdata subdata : incomeListList) {
                if (subdata.getCharge() != null) {
                    totalCharge = totalCharge.add(subdata.getCharge());
                    if (stationPrice.containsKey(subdata.getStationId())) {
                        PriceValue priceValue = stationPrice.get(subdata.getStationId());
                        BigDecimal multiply = subdata.getCharge().multiply(priceValue.getLowPrice());
                        income = income.add(multiply);
                    }
                    if (subdata.getDischarge() != null) {
                        totalDischarge = totalDischarge.add(subdata.getDischarge());
                    }
                }
            }
        }
        //等效减排二氧化碳  等效减排CO2=所有电站总充0.475
        BigDecimal reductionCO2 = totalCharge.multiply(value);
        energySavingRespVo.setReductionCO2(reductionCO2);

        //等效植树量  等效植树量=等效减排CO2/183/40
        BigDecimal treePlanting = reductionCO2.divide(parameter, 6, BigDecimal.ROUND_HALF_UP).divide(fours, 6, BigDecimal.ROUND_HALF_UP);
        energySavingRespVo.setTreePlanting(treePlanting);
        //等效节约煤 等效节约煤=所有电站总充*节约标准煤转换系数(04)
        BigDecimal equivalentCoal = totalCharge.multiply(four);
        energySavingRespVo.setEquivalentCoal(equivalentCoal);
        //等效经济收入 等效经济收入=等效节约煤*煤价 (600元/吨)  等效节约煤此处单位为kg,故而单价调整为0.6元/kg
        energySavingRespVo.setIncome(equivalentCoal.multiply(coalPrice));
        return energySavingRespVo;
    }

    @Override
    public List<Subdata> getProfit(String beginString, String endString) {
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        List<Subdata> subdataList = getSubdata(beginString, endString, stations);
        return subdataList;
    }

    private List<Subdata> getPvElec(String beginString, String endString, List<Station> stations){
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        List<DayProfitType> stationElec = elecMeterValueService.getElec(beginString, endString, groupId,DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,null);
        Map<Integer, List<DayProfitType>> profitMap = stationElec.stream().collect(Collectors.groupingBy(DayProfitType::getStationId));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        profitMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            //收益
            BigDecimal result = v.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
            if (stationMap.containsKey(k)) {
                Station station = stationMap.get(k);
                subdata.setStationId(k);
                subdata.setStationName(station.getName());
                subdata.setRelease(result);
                subdataList.add(subdata);
            }
        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;
    }
    private List<Subdata> getPvSubdata(String beginString, String endString, List<Station> stations){
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        List<DayProfitType> stationProfit = earningsCalculateMpptService.getProfit(beginString, endString, groupId);
        Map<Integer, List<DayProfitType>> profitMap = stationProfit.stream().collect(Collectors.groupingBy(DayProfitType::getStationId));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        profitMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            //收益
            BigDecimal result = v.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
            if (stationMap.containsKey(k)) {
                Station station = stationMap.get(k);
                subdata.setStationId(k);
                subdata.setStationName(station.getName());
                subdata.setIncomeValue(result);
                subdataList.add(subdata);
            }
        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;
    }
    @NotNull
    private List<Subdata> getSubdata(String beginString, String endString, List<Station> stations) {
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        //按电站分组查询收益
        List<DayProfitType> stationProfit = earningsCalculateService.getProfit(beginString, endString, groupId);
        Map<Integer, List<DayProfitType>> profitMap = stationProfit.stream().collect(Collectors.groupingBy(DayProfitType::getStationId));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        profitMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            //根据类型分组
            Map<Integer, List<DayProfitType>> typeMap = v.stream().collect(Collectors.groupingBy(DayProfitType::getType));
            //充
            List<DayProfitType> chargeGroupProfitTypes = typeMap.get(CHARGE);
            //放
            List<DayProfitType> dischargeGroupProfitTypes = typeMap.get(DISCHARGE);
            //充收益
            BigDecimal chargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(chargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : chargeGroupProfitTypes) {
                    chargeProfit = chargeGroupProfitType.getDigital() != null ? chargeProfit.add(chargeGroupProfitType.getDigital()) : chargeProfit;
                }
            }
            //放收益
            BigDecimal dischargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(dischargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : dischargeGroupProfitTypes) {
                    dischargeProfit = chargeGroupProfitType.getDigital() != null ? dischargeProfit.add(chargeGroupProfitType.getDigital()) : dischargeProfit;
                }
            }
            BigDecimal result = dischargeProfit.subtract(chargeProfit).divide(new BigDecimal("10000"));
            if (stationMap.containsKey(k)) {
                Station station = stationMap.get(k);
                subdata.setStationId(k);
                subdata.setStationName(station.getName());
                if (result.doubleValue() < 0.0) {
                    subdata.setIncomeValue(BigDecimal.ZERO);
                } else {
                    subdata.setIncomeValue(result);
                }
                subdataList.add(subdata);
            }


        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;
    }

    private List<Subdata> getPvElecByDay(String beginString, String endString, List<Station> stations){
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        List<Integer> ids = new ArrayList<>();
        for (Station station : stations) {
            groupId = station.getGroupId();
            ids.add(station.getId());
        }
        CommonBigScreenReq req = new CommonBigScreenReq();
        req.setBeginTime(beginString);
        req.setEndTime(endString);
        req.setStationIds(ids);
        req.setGroupId(groupId);
        List<DayProfitType> stationElec = elecMeterValueService.getElec(beginString, endString, groupId,DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,ids);
        Map<String, List<DayProfitType>> elecMap = stationElec.stream().collect(Collectors.groupingBy(s -> s.getStationId() + "," + s.getDay()));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        elecMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            // 收益
            BigDecimal result = v.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
            String[] split = k.split(",");
            Integer stationId = Integer.parseInt(split[0]);
            if (stationMap.containsKey(stationId)) {
                Station station = stationMap.get(stationId);
                subdata.setStationId(stationId);
                subdata.setStationName(split[1] + station.getName());
                subdata.setRelease(result);
                subdataList.add(subdata);
            }
        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;

    }

    private List<Subdata> getPvSubdataByDay(String beginString, String endString, List<Station> stations){
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        List<Integer> ids = new ArrayList<>();
        for (Station station : stations) {
            groupId = station.getGroupId();
            ids.add(station.getId());
        }
        CommonBigScreenReq req = new CommonBigScreenReq();
        req.setBeginTime(beginString);
        req.setEndTime(endString);
        req.setStationIds(ids);
        req.setGroupId(groupId);
        List<DayProfitType> stationProfit = earningsCalculateMpptService.getEarningsByParam(req);
        Map<String, List<DayProfitType>> profitMap = stationProfit.stream().collect(Collectors.groupingBy(s -> s.getStationId() + "," + s.getDay()));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        profitMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            // 收益
            BigDecimal result = v.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
            String[] split = k.split(",");
            Integer stationId = Integer.parseInt(split[0]);
            if (stationMap.containsKey(stationId)) {
                Station station = stationMap.get(stationId);
                subdata.setStationId(stationId);
                subdata.setStationName(split[1] + station.getName());
                subdata.setIncomeValue(result);
                subdataList.add(subdata);
            }
        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;
    }

    private List<Subdata> getSubdataByDay(String beginString, String endString, List<Station> stations) {
        Map<Integer, Station> stationMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        Integer groupId = null;
        List<Integer> ids = new ArrayList<>();
        for (Station station : stations) {
            groupId = station.getGroupId();
            ids.add(station.getId());
        }
        //按电站分组查询收益
        CommonBigScreenReq req = new CommonBigScreenReq();
        req.setBeginTime(beginString);
        req.setEndTime(endString);
        req.setStationIds(ids);
        req.setGroupId(groupId);
        List<DayProfitType> stationProfit = earningsCalculateService.getEarningsByParam(req);
        Map<String, List<DayProfitType>> profitMap = stationProfit.stream().collect(Collectors.groupingBy(s -> s.getStationId() + "," + s.getDay()));
        //创建返回对象
        List<Subdata> subdataList = new ArrayList<>();
        profitMap.forEach((k, v) -> {
            Subdata subdata = new Subdata();
            //根据类型分组
            Map<Integer, List<DayProfitType>> typeMap = v.stream().collect(Collectors.groupingBy(DayProfitType::getType));
            //充
            List<DayProfitType> chargeGroupProfitTypes = typeMap.get(CHARGE);
            //放
            List<DayProfitType> dischargeGroupProfitTypes = typeMap.get(DISCHARGE);
            //充收益
            BigDecimal chargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(chargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : chargeGroupProfitTypes) {
                    chargeProfit = chargeGroupProfitType.getDigital() != null ? chargeProfit.add(chargeGroupProfitType.getDigital()) : chargeProfit;
                }
            }
            //放收益
            BigDecimal dischargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(dischargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : dischargeGroupProfitTypes) {
                    dischargeProfit = chargeGroupProfitType.getDigital() != null ? dischargeProfit.add(chargeGroupProfitType.getDigital()) : dischargeProfit;
                }
            }
            BigDecimal result = dischargeProfit.subtract(chargeProfit).divide(new BigDecimal("10000"));
            String[] split = k.split(",");
            Integer stationId = Integer.parseInt(split[0]);
            if (stationMap.containsKey(stationId)) {
                Station station = stationMap.get(stationId);
                subdata.setStationId(stationId);
                subdata.setStationName(split[1] + station.getName());
                if (result.doubleValue() < 0.0) {
                    subdata.setIncomeValue(BigDecimal.ZERO);
                } else {
                    subdata.setIncomeValue(result);
                }
                subdataList.add(subdata);
            }
        });
        subdataList.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        return subdataList;
    }

    @Override
    public List<Subdata> getEfficiencyDate() {
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(stations::add);
//        List<Subdata> subDataLists = getSubdata(stations);
        List<Subdata> subDataLists = getEfficiencyDate(stations);
        return subDataLists;
    }

    private List<Subdata> getEfficiencyDate(List<Station> stations) {
        List<Subdata> subDataList = new ArrayList<>();
        for (Station s:stations) {
            Subdata subdata = new Subdata();
            CountEleData countEleData = getByRedisData(s.getId());
            subdata.setStationId(s.getId());
            subdata.setStationName(s.getName());
            subdata.setStationCapacity(s.getCapacity());
            //总充或总放等于0，总放大于总充，日充与日放都为0时，重放电效率记录为0
            if(countEleData==null||BigDecimal.ZERO.equals(countEleData.getTotalDischargeElec())||BigDecimal.ZERO.equals(countEleData.getTotalChargeElec())
                    ||countEleData.getTotalDischargeElec().compareTo(countEleData.getTotalChargeElec())>=0
                    ||(BigDecimal.ZERO.compareTo(countEleData.getDailyChargeElec())==0&&BigDecimal.ZERO.compareTo(countEleData.getDailyDischargeElec())==0)){
                subdata.setEfficiencyValue(BigDecimal.ZERO);
            }else{
                subdata.setEfficiencyValue(countEleData.getTotalDischargeElec().divide(countEleData.getTotalChargeElec(),4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            subDataList.add(subdata);
        }
        List<Subdata> subDataLists = new ArrayList<>();
        subDataList.stream().filter(i -> !BigDecimal.ZERO.equals(i.getEfficiencyValue())).forEach(s -> subDataLists.add(s));
        subDataLists.sort(Comparator.comparing((Subdata::getEfficiencyValue)).reversed());
        if (subDataLists.size() > 30) {
            List<Subdata> limit = subDataLists.subList(0, 30);
            return limit;
        }
        return subDataLists;
    }
    /**
     * 获取系统转化效率
     *
     * @param stations
     * @return
     */
    private List<Subdata> getSubdata(List<Station> stations) {
        Map<Integer, List<Station>> stationIdMap = stations.stream().collect(Collectors.groupingBy(Station::getId));
        List<AnnualChartValue> dischargeValue = getDischargeValue(stations);
        List<Subdata> subDataList = new ArrayList<>();
        for (AnnualChartValue annualChartValue : dischargeValue) {
            if (stationIdMap.containsKey(annualChartValue.getStationId())) {
                List<Station> stationList = stationIdMap.get(annualChartValue.getStationId());
                Subdata subdata = new Subdata();
                BigDecimal totalCharge = annualChartValue.getDayCharge();
                BigDecimal totalDischarge = annualChartValue.getDayDischarge();
                if (totalCharge != null && totalCharge.compareTo(new BigDecimal(0.00)) != 0) {
                    BigDecimal divide = totalDischarge.divide(totalCharge, 6, BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide1 = divide.multiply(hundred).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (divide1.compareTo(hundred) == 1 || divide1.compareTo(hundred) == 0) {
                        continue;
                    }
                    subdata.setEfficiencyValue(divide1);
                } else {
                    subdata.setEfficiencyValue(new BigDecimal(0));
                }
                subdata.setStationName(annualChartValue.getStationName());
                subdata.setStationCapacity(stationList.get(0).getCapacity());
                subdata.setStationId(annualChartValue.getStationId());
                subDataList.add(subdata);
            }
        }

        List<Subdata> subDataLists = new ArrayList<>();
        subDataList.stream().filter(i -> !new BigDecimal(0).equals(i.getEfficiencyValue())).forEach(s -> subDataLists.add(s));
        subDataLists.sort(Comparator.comparing((Subdata::getEfficiencyValue)).reversed());
        if (subDataLists.size() > 30) {
            List<Subdata> limit = subDataLists.subList(0, 30);
            return limit;
        }
        return subDataLists;
    }

    /**
     * 获取系统转化效率
     *
     * @param stations
     * @param req
     * @return
     */
    private List<Subdata> getSubdataByDay(List<Station> stations, CommonBigScreenReq req) {
        List<AnnualChartValue> dischargeValue = getDischargeValue(stations, req);
        List<Subdata> subDataList = new ArrayList<>();
        for (AnnualChartValue annualChartValue : dischargeValue) {
            Subdata subdata = new Subdata();
            BigDecimal totalCharge = annualChartValue.getDayCharge();
            BigDecimal totalDischarge = annualChartValue.getDayDischarge();
            if (totalCharge != null && totalCharge.compareTo(new BigDecimal(0.00)) != 0) {
                BigDecimal divide = totalDischarge.divide(totalCharge, 6, BigDecimal.ROUND_HALF_UP);
                BigDecimal divide1 = divide.multiply(hundred).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (divide1.compareTo(hundred) == 1 || divide1.compareTo(hundred) == 0) {
                    continue;
                }
                subdata.setEfficiencyValue(divide1);
            } else {
                subdata.setEfficiencyValue(new BigDecimal(0));
            }
            subdata.setStationName(annualChartValue.getStationName());
            subdata.setStationCapacity(annualChartValue.getStationCapacity());
            subdata.setStationId(annualChartValue.getStationId());
            subDataList.add(subdata);
        }
        List<Subdata> subDataLists = new ArrayList<>();
        subDataList.stream().filter(i -> !new BigDecimal(0).equals(i.getEfficiencyValue())).forEach(s -> subDataLists.add(s));
        subDataLists.sort(Comparator.comparing((Subdata::getEfficiencyValue)).reversed());
        if (subDataLists.size() > 30) {
            List<Subdata> limit = subDataLists.subList(0, 30);
            return limit;
        }
        return subDataLists;
    }

    @Override
    public List<Subdata> getIncomeList() {
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        List<AnnualChartValue> dischargeValue = getDischargeValue(stations);
        List<Subdata> subDataList = new ArrayList<>();
        Map<Integer, List<Station>> stationIdMap = stations.stream().collect(Collectors.groupingBy(Station::getId));
        Map<Integer, PriceValue> stationPrice = getStationPrice(stations);
        for (AnnualChartValue annualChartValue : dischargeValue) {
            if (stationIdMap.containsKey(annualChartValue.getStationId())) {
                Subdata subdata = new Subdata();
                BigDecimal totalCharge = annualChartValue.getDayCharge();
                BigDecimal totalDischarge = annualChartValue.getDayDischarge();
                if (totalCharge != null && totalCharge.compareTo(new BigDecimal(0.00)) != 0) {
                    if (stationPrice.containsKey(annualChartValue.getStationId())) {
                        PriceValue priceValue = stationPrice.get(annualChartValue.getStationId());
                        BigDecimal divide = totalDischarge.multiply(priceValue.getPeakPrice()).subtract(totalCharge.multiply(priceValue.getLowPrice()));
                        subdata.setIncomeValue(divide.divide(new BigDecimal("10000")));
                    }
                } else {
                    subdata.setIncomeValue(new BigDecimal(0));
                }
                subdata.setStationName(annualChartValue.getStationName());
                subdata.setStationId(annualChartValue.getStationId());
                subDataList.add(subdata);
            }
        }
        List<Subdata> subDataLists = new ArrayList<>();
        List<Subdata> subDates = new ArrayList<>();
        subDataList.stream().filter(i -> !new BigDecimal(0).equals(i.getIncomeValue())).forEach(s -> subDataLists.add(s));
        subDataLists.stream().filter(i -> null != i.getIncomeValue()).forEach(s -> subDates.add(s));
        subDates.sort(Comparator.comparing((Subdata::getIncomeValue)).reversed());
        if (subDates.size() > maxSize) {
            List<Subdata> limit = subDates.subList(0, maxSize);
            return limit;
        }
        return subDates;
    }


    /**
     * 各个电站的日充日充
     *
     * @param stations
     * @return
     */
    private List<AnnualChartValue> getDischargeValue(List<Station> stations) {
        List<AnnualChartValue> list = new ArrayList<>();
        List<ElecMeterValue> elecMeterValueList = elecMeterValueService.selectByStationIdsAndTime(null, null, null, null);
        Map<String, BigDecimal> stationTypeMap = new HashMap<>();
        if (elecMeterValueList != null && !elecMeterValueList.isEmpty()) {
            stationTypeMap = elecMeterValueList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(i.getType()) ||
                    DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(i.getType())).collect(Collectors.toMap(i -> i.getStationId() + "," + i.getType(), ElecMeterValue::getDigital, (k1, k2) -> k1));
        }
        for (Station station : stations) {
            AnnualChartValue subdata = new AnnualChartValue();
            BigDecimal totalCharge = stationTypeMap.get(station.getId() + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            BigDecimal totalDischarge = stationTypeMap.get(station.getId() + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            if (station.getId() == LianStationId) {
                Integer srcId = LianSrc;
                totalCharge = elecMeterValueService.selectSumValue(station.getId(),
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE, srcId);
                totalDischarge = elecMeterValueService.selectSumValue(station.getId(),
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE, srcId);
            }
            //各电站总放/总充
            if (totalCharge == null) {
                subdata.setDayCharge(BigDecimal.ZERO);
            } else {
                if (station.getId() == FENGStationId) {
                    subdata.setDayCharge(totalCharge.multiply(new BigDecimal("1000")));
                } else {
                    subdata.setDayCharge(totalCharge);
                }
            }
            if (totalDischarge == null) {
                subdata.setDayDischarge(BigDecimal.ZERO);
            } else {
                if (station.getId() == FENGStationId) {
                    subdata.setDayDischarge(totalDischarge.multiply(new BigDecimal("1000")));
                } else {
                    subdata.setDayDischarge(totalDischarge);
                }
            }
            subdata.setStationId(station.getId());
            subdata.setStationName(station.getName());
            list.add(subdata);
        }
        return list;
    }

    /**
     * 按日计算各个电站的日充日充比值
     *
     * @param stations
     * @return
     */
    private List<AnnualChartValue> getDischargeValue(List<Station> stations, CommonBigScreenReq req) {
        Map<Integer, Station> idNameMap = stations.stream().collect(Collectors.toMap(Station::getId, Function.identity()));
        List<AnnualChartValue> list = new ArrayList<>();
        List<ElecMeterValue> elecMeterValueList = elecMeterValueService.selectGroupByDay(req);
        Map<String, List<ElecMeterValue>> profitMap = elecMeterValueList.stream().collect(Collectors.groupingBy(s -> s.getStationId() + "," + s.getDay()));
        //慈溪电站特殊电站
        Map<String, List<ElecMeterValue>> specialMap = new HashMap<>();
        if (idNameMap.get(LianStationId) != null) {
            getSpecailStationReq(req);
            List<ElecMeterValue> specialEle = elecMeterValueService.selectGroupByDay(req);
            specialMap = specialEle.stream().collect(Collectors.groupingBy(s -> s.getStationId() + "," + s.getDay()));
        }
        Map<String, List<ElecMeterValue>> finalSpecialMap = specialMap;
        //创建返回对象
        profitMap.forEach((k, v) -> {
            AnnualChartValue subdata = new AnnualChartValue();
            Map<Integer, List<ElecMeterValue>> typeMap = v.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
            //充
            List<ElecMeterValue> chargeGroupProfitTypes = typeMap.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            //放
            List<ElecMeterValue> dischargeGroupProfitTypes = typeMap.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            String[] split = k.split(",");
            Integer stationId = Integer.parseInt(split[0]);
            if (stationId == LianStationId) {
                List<ElecMeterValue> eleList = finalSpecialMap.get(k);
                if (!eleList.isEmpty()) {
                    chargeGroupProfitTypes = eleList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(i.getType())).collect(Collectors.toList());
                    dischargeGroupProfitTypes = eleList.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(i.getType())).collect(Collectors.toList());
                } else {
                    chargeGroupProfitTypes = new ArrayList<>();
                    dischargeGroupProfitTypes = new ArrayList<>();
                }
            }
            BigDecimal totalCharge = BigDecimal.ZERO;
            if (chargeGroupProfitTypes != null) {
                for (ElecMeterValue e : chargeGroupProfitTypes) {
                    totalCharge = e.getDigital() != null ? totalCharge.add(e.getDigital()) : totalCharge;
                }
            }
            BigDecimal totalDischarge = BigDecimal.ZERO;
            if (dischargeGroupProfitTypes != null) {
                for (ElecMeterValue e : dischargeGroupProfitTypes) {
                    totalDischarge = e.getDigital() != null ? totalDischarge.add(e.getDigital()) : totalDischarge;
                }
            }
            //各电站总放/总充
            if (totalCharge == null) {
                subdata.setDayCharge(BigDecimal.ZERO);
            } else {
                if (stationId == FENGStationId) {
                    subdata.setDayCharge(totalCharge.multiply(new BigDecimal("1000")));
                } else {
                    subdata.setDayCharge(totalCharge);
                }
            }
            if (totalDischarge == null) {
                subdata.setDayDischarge(BigDecimal.ZERO);
            } else {
                if (stationId == FENGStationId) {
                    subdata.setDayDischarge(totalDischarge.multiply(new BigDecimal("1000")));
                } else {
                    subdata.setDayDischarge(totalDischarge);
                }
            }
            subdata.setStationId(stationId);
            Station station = idNameMap.get(stationId);
            subdata.setStationName(split[1] + station.getName());
            subdata.setStationCapacity(station.getCapacity());
            list.add(subdata);
        });
        return list;
    }

    /**
     * 获取特殊电站参数
     *
     * @param req
     */
    private void getSpecailStationReq(CommonBigScreenReq req) {
        String deviceType = colCountService.getDeviceType(LianStationId);
        if (deviceType == null) {
            deviceType = DeviceTypeConstant.PCS;
        }
        List<DeviceRespVO> deviceList = deviceService.getListByDeviceType(LianStationId, deviceType);
        if (deviceList.isEmpty()) {
            deviceList = deviceService.getListByFuzzyDeviceType(LianStationId, deviceType);
        }
        List<Integer> srcIds = deviceList.stream().map(DeviceRespVO::getSrcId).collect(Collectors.toList());
        List<Integer> ids = new ArrayList<>();
        ids.add(LianStationId);
        req.setStationIds(ids);
        req.setSrcIds(srcIds);
    }

    @Override
    public List<Subdata> getRegionList() {
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        List<Subdata> regionList = new ArrayList<>();
        List<ProvinceStation> provinceList = getProvince(stations);
        Map<String, PriceValue> price = getPrice();
        for (ProvinceStation provinceStation : provinceList) {
            if (price.containsKey(provinceStation.getName())) {
                PriceValue priceValue = price.get(provinceStation.getName());
            }
            Subdata subdata = new Subdata();
            subdata.setAddName(provinceStation.getName());
            subdata.setAddNameEn(provinceStation.getNameEn());
            List<Station> stationList = provinceStation.getList();
            if (!stationList.isEmpty()) {
                subdata.setRegionValue(stationList.size());
                regionList.add(subdata);
            }
        }
        return regionList;
    }

    private List<ProvinceStation> getProvince(List<Station> stations) {
        Map<String, List<Station>> natioMap = stations.stream().filter(s->s.getProvince()!=null).collect(Collectors.groupingBy(Station::getNation));
        List<ProvinceStation> list = new ArrayList<>();
        natioMap.forEach((k, v) -> {
            ProvinceStation provinceStation = new ProvinceStation();
            provinceStation.setName(k);
            provinceStation.setList(v);
            list.add(provinceStation);
        });
        return list;
    }

    @Override
    public List<Subdata> getCapacity() {
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        List<Subdata> subDataList = getSubdataList(stations);
        return subDataList;
    }

    /**
     * 装机容量倒排接口抽取
     *
     * @param stations
     * @return
     */
    private List<Subdata> getSubdataList(List<Station> stations) {
        List<Subdata> subDataList = new ArrayList<>();
        List<ProvinceStation> provinceList = getProvince(stations);
        for (ProvinceStation provinceStation : provinceList) {
            Subdata subdata = new Subdata();
            subdata.setAddName(provinceStation.getName());
            subdata.setAddNameEn(provinceStation.getNameEn());
            List<Station> stationList = provinceStation.getList();
            BigDecimal capacity = BigDecimal.ZERO;
            for (Station station : stationList) {
                if (station.getCapacity() != null) {
                    capacity = capacity.add(station.getCapacity());
                }
            }
            subdata.setStationCapacity(capacity);
            subDataList.add(subdata);
        }
        subDataList.sort(Comparator.comparing((Subdata::getStationCapacity)).reversed());
        return subDataList;
    }

    @Override
    public List<Station> getStationInfo() {
        List<Station> stations = stationService.selectAll();
        List<Station> list = new ArrayList<>();
        stations.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> list.add(s));
        return list;
    }

    @Override
    public List<AnnualChartValue> getChargeDailyChart() {
        //直接查询
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        return getAnnualChartValues(stations);
    }

    private List<AnnualChartValue> getAnnualReleaseValues(List<Station> stations){
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        //时间（近30天）
        Date date = DateUtil.yesterday();
        Date startDate = DateUtils.addDays(date, -maxSize);
        Date endDate = DateUtil.endOfDay(date);
        List<DateTime> dateTimes = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
        String beginTime = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String endTime = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DayProfitType> stationElec = elecMeterValueService.getElec(beginTime, endTime, groupId,DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,null);
        Map<String, List<DayProfitType>> elecMap = stationElec.stream().collect(Collectors.groupingBy(s -> s.getDay()));
        List<AnnualChartValue> resultList = new ArrayList<>();
        for (DateTime dateTime:dateTimes){
            AnnualChartValue annualChartValue = new AnnualChartValue();
            BigDecimal release = BigDecimal.ZERO;
            String time = DateUtil.format(dateTime, CommonConstant.DATE_YMD);
            List<DayProfitType> elecList = elecMap.get(time);
            if(elecList != null && elecList.size()>0){
                release = elecList.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
            }
            annualChartValue.setTime(time);
            annualChartValue.setRelease(release);
            resultList.add(annualChartValue);
        }
        return resultList;
    }

    private List<AnnualChartValue> getAnnualChartValues(List<Station> stations) {
        //时间（近30天）
        Date date = DateUtil.yesterday();
        Date startDate = DateUtils.addDays(date, -maxSize);
        Date endDate = DateUtil.endOfDay(date);
        List<DateTime> dateTimes = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
        /***************************此处为改造代码******************************/
        //过滤真实设备中上送的电量单位类型为MWh以及以上类型
        Map<Integer, BigDecimal> specialUnit = new HashMap<>();
        Device device = new Device();
        device.setVirtual(CommonConstant.ZERO);
        device.setIsFilterUnitType(CommonConstant.ZERO);
        List<Device> realDevice = deviceService.getRealDevice(device);
        if (!realDevice.isEmpty()) {
            ColCountReq colCountReq = new ColCountReq();
            colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
            List<Integer> ids = stations.stream().map(Station::getId).collect(Collectors.toList());
            colCountReq.setIds(ids);
            List<ColCountResp> colCountResps = colCountService.selectByParam(colCountReq);
            Map<Integer, String> IdTypeMap = colCountResps.stream().collect(Collectors.toMap(ColCountResp::getStationId, ColCountResp::getDeviceType, (k1, k2) -> k1));
            for (Device d : realDevice) {
                String type = IdTypeMap.get(d.getStationId());
                if (type != null) {
                    if (d.getDeviceType().contains(type)) {
                        //如果是2则是MWh，否则是GWh
                        specialUnit.put(d.getStationId(), d.getUnitType().equals(CommonConstant.TWO) ? new BigDecimal(1000) : new BigDecimal(1000000));
                    }
                }
            }
        }
        List<Integer> stationIds = stations.stream().filter(i -> i.getId() != LianStationId).map(Station::getId).collect(Collectors.toList());
        CommonBigScreenReq req = new CommonBigScreenReq();
        req.setBeginTime(DateUtil.format(startDate, CommonConstant.DATE_YMD));
        req.setEndTime(DateUtil.format(endDate, CommonConstant.DATE_YMD));
        req.setStationIds(stationIds);
        List<ElecMeterValue> elecMeterValueList = new ArrayList<>();
        if (!stationIds.isEmpty()) {
            elecMeterValueList = elecMeterValueService.selectGroupByDay(req);
        }
        List<Integer> specialIds = stations.stream().filter(i -> i.getId() == LianStationId).map(Station::getId).collect(Collectors.toList());
        if (!specialIds.isEmpty()) {
            getSpecailStationReq(req);
            List<ElecMeterValue> specialEle = elecMeterValueService.selectGroupByDay(req);
            elecMeterValueList.addAll(specialEle);
        }
        Map<String, List<ElecMeterValue>> eleMap = elecMeterValueList.stream().collect(Collectors.groupingBy(s -> s.getDay() + "," + s.getType()));
        List<AnnualChartValue> resultList = new ArrayList<>();
        for (DateTime d : dateTimes) {
            AnnualChartValue annualChartValue = new AnnualChartValue();
            BigDecimal totalCharge = BigDecimal.ZERO;
            BigDecimal totalDischarge = BigDecimal.ZERO;
            String time = DateUtil.format(d, CommonConstant.DATE_YMD);
            List<ElecMeterValue> chargeList = eleMap.get(time + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            List<ElecMeterValue> dischargeList = eleMap.get(time + "," + DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            if (chargeList != null) {
                for (ElecMeterValue elecMeterValue : chargeList) {
                    totalCharge = totalCharge.add(specialUnit.get(elecMeterValue.getStationId()) == null ? elecMeterValue.getDigital() : elecMeterValue.getDigital().multiply(specialUnit.get(elecMeterValue.getStationId())));
                }
            }
            if (dischargeList != null) {
                for (ElecMeterValue elecMeterValue : dischargeList) {
                    totalDischarge = totalDischarge.add(specialUnit.get(elecMeterValue.getStationId()) == null ? elecMeterValue.getDigital() : elecMeterValue.getDigital().multiply(specialUnit.get(elecMeterValue.getStationId())));
                }
            }
            annualChartValue.setTime(time);
            annualChartValue.setDayCharge(totalCharge);
            annualChartValue.setDayDischarge(totalDischarge);
            resultList.add(annualChartValue);
        }
        return resultList;
    }


    @Override
    public List<AnnualChartValue> getIncomeCurve(CockpitReqVO vo) {
        List<AnnualChartValue> curveResult = new ArrayList<>();
        //直接查询
        List<Station> list = stationService.selectAll();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus()) && LianStationId != i.getId()).forEach(s -> stations.add(s));
        List<Integer> stationIds = stations.stream().map(s -> {
            return s.getId();
        }).collect(Collectors.toList());
        //联城单独计算
        List<Integer> lianStationIds = new ArrayList<>();
        for (Station station : list) {
            if (station.getId() == LianStationId) {
                stations.add(station);
                lianStationIds.add(station.getId());
            }
        }
        Map<Integer, PriceValue> stationPrice = getStationPrice(stations);
        //根据type去获取数据
        if (CommonConstant.DAY.equals(vo.getType())) {
            //开始结束时间为30天
            Date date = DateUtil.yesterday();
            Date startDate = DateUtils.addDays(date, -maxSize);
            Date endDate = DateUtil.endOfDay(date);
            List<DateTime> dateTimes = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
            for (DateTime dateTime : dateTimes) {
                String yesBeginTime = DateUtil.format(DateUtil.beginOfDay(dateTime), CommonConstant.DATE);
                String yesEndTime = DateUtil.format(DateUtil.endOfDay(dateTime), CommonConstant.DATE);
                AnnualOverviewResp yesIncomeShow = getIncomeShow(stations, yesBeginTime, yesEndTime);
                AnnualChartValue annualChartValue = new AnnualChartValue();
                annualChartValue.setProfit(yesIncomeShow.getYearProfit().divide(new BigDecimal("10000")));
                String dateString = dateTime + "";
                String time = dateString.substring(0, 10);
                annualChartValue.setTime(time);
                curveResult.add(annualChartValue);

            }

        } else if (CommonConstant.MONTH.equals(vo.getType())) {
            Date date = new Date();
            Date startDate = DateUtil.beginOfYear(date);
            Date endDate = DateUtil.endOfDay(date);
            List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.MONTH);
            for (DateTime time : dateTime) {
                DateTime begin = DateUtil.beginOfMonth(time);
                String beginString = DateUtil.format(begin, CommonConstant.DATE);
                String endString = DateUtil.format(DateUtil.endOfMonth(time), CommonConstant.DATE);
                List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectByStationIdsAndTime(stationIds, beginString.substring(0, 10), endString.substring(0, 10), null);
                List<ElecMeterValue> lianElecMeterValues = elecMeterValueService.selectByStationIdsAndTime(lianStationIds, beginString.substring(0, 10), endString.substring(0, 10), LianSrc);
                elecMeterValues.addAll(lianElecMeterValues);
                AnnualChartValue curveResult1 = getCurveResult(stationPrice, elecMeterValues);
                AnnualChartValue annualChartValue = new AnnualChartValue();
                annualChartValue.setProfit(curveResult1.getProfit().divide(new BigDecimal("10000")));
                String timeString = DateUtil.format(time, CommonConstant.DATE);
                annualChartValue.setTime(timeString.substring(0, 7));
                curveResult.add(annualChartValue);
            }
        } else if (CommonConstant.YEAR.equals(vo.getType())) {
            //时间一年 按照月份
            List<ElecMeterValue> chargeYearList = elecMeterValueService.selectListByStationIds(stationIds, DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE,
                    null, null);
            //时间是一年 按照年
            //充电量
            Map<String, List<ElecMeterValue>> yearChargeList = new HashMap<>();
            if (chargeYearList != null) {
                yearChargeList = chargeYearList.stream().collect(Collectors.groupingBy(s -> {
                    String month = s.getDay().substring(0, 4);
                    return month;
                }));
            }
            //使用迭代器，获取key
            //存放key的List
            List<String> keyString = new ArrayList<>();
            Iterator<Map.Entry<String, List<ElecMeterValue>>> iter = yearChargeList.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, List<ElecMeterValue>> entry = iter.next();
                String key = entry.getKey();
                keyString.add(key);
            }
            Collections.reverse(keyString);
            for (String key : keyString) {
                int year = Integer.parseInt(key);
                Calendar calendar = Calendar.getInstance();
                calendar.clear();
                calendar.set(Calendar.YEAR, year);
                Date begin = calendar.getTime();
                String beginString = DateUtil.format(begin, CommonConstant.DATE);
                String endString = DateUtil.format(DateUtil.endOfYear(begin), CommonConstant.DATE);
                List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectByStationIdsAndTime(stationIds, beginString.substring(0, 10), endString.substring(0, 10), null);
                List<ElecMeterValue> lianElecMeterValues = elecMeterValueService.selectByStationIdsAndTime(lianStationIds, beginString.substring(0, 10), endString.substring(0, 10), LianSrc);
                elecMeterValues.addAll(lianElecMeterValues);
                AnnualChartValue curveResult1 = getCurveResult(stationPrice, elecMeterValues);
                AnnualChartValue annualChartValue = new AnnualChartValue();
                annualChartValue.setProfit(curveResult1.getProfit().divide(new BigDecimal("10000")));
                annualChartValue.setTime(key);
                curveResult.add(annualChartValue);
            }

        }
        return curveResult;
    }

    @Override
    public List<AnnualChartValue> getProfitCurve(CockpitReqVO vo) {
        //查询电站
        List<Station> list = stationService.selectAll();
        List<Station> oneList = list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).collect(Collectors.toList());
        return getProfitCurve(vo, oneList);
    }

    @Override
    public AnnualOverviewResp getOverviewData(List<Integer> stationIds) {
        if (stationIds == null) {
            return new AnnualOverviewResp();
        }
        List<Station> list = stationService.selectStationsByIds(stationIds,null);
        AnnualOverviewResp annualOverviewResp = getOverviewDatas(list);
        return annualOverviewResp;
    }

    @Override
    public AnnualPvOverviewResp getPvOverviewData(List<Integer> stationIds) {
        if (stationIds == null) {
            return new AnnualPvOverviewResp();
        }
        List<Station> list = getCountPvStations(stationIds);
        AnnualPvOverviewResp annualOverviewResp = getPvOverviewDatas(list);
        return annualOverviewResp;
    }

    @Override
    public EnergySavingRespVo getPvEnergySaving(List<Integer> stationIds) {
        if (stationIds == null) {
            return new EnergySavingRespVo();
        }
        List<Station> list = getCountPvStations(stationIds);
        return getPvEnergySavingRespVo(list);
    }

    @Override
    public List<AnnualChartValue> getPVCommonProfitCurve(CockpitReqVO vo, List<Integer> stationIds) {
        if (stationIds == null) {
            return new ArrayList<>();
        }
        List<Station> list = getCountPvStations(stationIds);
        return getPvProfitCurve(vo, list);
    }

    @Override
    public List<Subdata> getCommonRegionList(List<Integer> stationIds) {
        if (stationIds == null) {
            return new ArrayList<>();
        }
        List<Station> list = getCountStations(stationIds,null);
        List<Subdata> regionList = new ArrayList<>();
        Map<String, List<Station>> nationMap = list.stream().filter(i -> i.getProvince() != null).collect(Collectors.groupingBy(Station::getNation));
        if (nationMap.size() > CommonConstant.ONE) {
            regionList = getListSubdata(nationMap);
        } else {
            Map<String, List<Station>> provinceMap = list.stream().filter(i -> i.getCity() != null).collect(Collectors.groupingBy(Station::getProvince));
            if (provinceMap.size() > CommonConstant.ONE) {
                regionList = getListSubdata(provinceMap);
            } else {
                Map<String, List<Station>> cityMap = list.stream().filter(i -> i.getDistrict() != null).collect(Collectors.groupingBy(Station::getCity));
                regionList = getListSubdata(cityMap);
            }
        }
        return regionList;
    }


    @Override
    public List<Subdata> getCommonPvRegionList(List<Integer> stationIds) {
        if (stationIds == null) {
            return new ArrayList<>();
        }
        List<Station> list = getCountPvStations(stationIds);
        List<Subdata> regionList = new ArrayList<>();
        Map<String, List<Station>> nationMap = list.stream().filter(i -> i.getProvince() != null).collect(Collectors.groupingBy(Station::getNation));
        if (nationMap.size() > CommonConstant.ONE) {
            regionList = getListSubdata(nationMap);
        } else {
            Map<String, List<Station>> provinceMap = list.stream().filter(i -> i.getCity() != null).collect(Collectors.groupingBy(Station::getProvince));
            if (provinceMap.size() > CommonConstant.ONE) {
                regionList = getListSubdata(provinceMap);
            } else {
                Map<String, List<Station>> cityMap = list.stream().filter(i -> i.getDistrict() != null).collect(Collectors.groupingBy(Station::getCity));
                regionList = getListSubdata(cityMap);
            }
        }
        return regionList;
    }

    private List<Subdata> getListSubdata(Map<String, List<Station>> map) {
        List<Subdata> regionList = new ArrayList<>();
        Subdata subdata = null;
        for (Map.Entry<String, List<Station>> m : map.entrySet()) {
            subdata = new Subdata();
            subdata.setAddName(m.getKey());
            subdata.setRegionValue(m.getValue().size());
            regionList.add(subdata);
        }
        return regionList;
    }
    public List<AnnualChartValue> getPvProfitCurve(CockpitReqVO vo, List<Station> stations){
        List<AnnualChartValue> curveResult = new ArrayList<>();
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        if (CommonConstant.DAY.equals(vo.getType())) {
            setDayPvCurveResult(curveResult, groupId, stations);
        } else if (CommonConstant.YEAR.equals(vo.getType())) {
            setYearPVCurveResult(curveResult, groupId, stations);
        } else {
            setMonthPvCurveResult(curveResult, groupId, stations);
        }

        return curveResult;
    }
    public List<AnnualChartValue> getProfitCurve(CockpitReqVO vo, List<Station> stations) {
        List<AnnualChartValue> curveResult = new ArrayList<>();
        Integer groupId = null;
        for (Station station : stations) {
            groupId = station.getGroupId();
        }
        if (CommonConstant.DAY.equals(vo.getType())) {
            setDayCurveResult(curveResult, groupId, stations);
        } else if (CommonConstant.YEAR.equals(vo.getType())) {
            setYearCurveResult(curveResult, groupId, stations);
        } else {
            setMonthCurveResult(curveResult, groupId, stations);
        }

        return curveResult;
    }

    @Override
    public EnergySavingRespVo getEnergySaving(List<Integer> stationIds) {
        if (stationIds == null) {
            return new EnergySavingRespVo();
        }
        List<Station> list = getCountStations(stationIds,null);
        return getEnergySavingRespVo(list);
    }

    @Override
    public List<AnnualChartValue> getCommonProfitCurve(CockpitReqVO vo, List<Integer> stationIds) {
        if (stationIds == null) {
            return new ArrayList<>();
        }
        List<Station> list = getCountStations(stationIds,null);
        return getProfitCurve(vo, list);
    }

    @Override
    public List<AnnualChartValue> getCommonChargeDailyChart(List<Integer> stationIds) {
        if (stationIds == null) {
            return new ArrayList<>();
        }
        return getAnnualChartValues(getCountStations(stationIds,null));
    }

    @Override
    public List<AnnualChartValue> getCommonPvRelease(List<Integer> stationIds){
        if (stationIds == null) {
            return new ArrayList<>();
        }
        return getAnnualReleaseValues(getCountPvStations(stationIds));
    }

    @Override
    public List<Subdata> getPvCommonElec(String beginString, String endString,List<Integer> stationIds){
        List<Subdata> subdata = new ArrayList<>();
        if (stationIds == null) {
            return subdata;
        }
        List<Station> countStations = getCountPvStations(stationIds);
        if (countStations != null && !countStations.isEmpty()) {
            if (countStations.size() >= CommonConstant.FIVE) {
                subdata = getPvElec(beginString,endString,countStations);
            } else {
                //电站数目小于5个
                Date date = DateUtil.yesterday();
                Date startDate = DateUtils.addDays(date, -CommonConstant.FIVE);
                Date endDate = DateUtil.endOfDay(date);
                beginString = DateUtil.format(startDate, CommonConstant.DATE_YMD);
                endString = DateUtil.format(endDate, CommonConstant.DATE_YMD);
                subdata = getPvElecByDay(beginString, endString, countStations);
            }
        }
        return subdata;
    }

    @Override
    public List<Subdata> getPvCommonProfit(String beginString, String endString,List<Integer> stationIds){
        List<Subdata> subdata = new ArrayList<>();
        if (stationIds == null) {
            return subdata;
        }
        List<Station> countStations = getCountPvStations(stationIds);
        if (countStations != null && !countStations.isEmpty()) {
            if (countStations.size() >= CommonConstant.FIVE) {
                subdata = getPvSubdata(beginString,endString,countStations);
            } else {
                //电站数目小于5个
                Date date = DateUtil.yesterday();
                Date startDate = DateUtils.addDays(date, -CommonConstant.FIVE);
                Date endDate = DateUtil.endOfDay(date);
                beginString = DateUtil.format(startDate, CommonConstant.DATE_YMD);
                endString = DateUtil.format(endDate, CommonConstant.DATE_YMD);
                subdata = getPvSubdataByDay(beginString, endString, countStations);
            }
        }
        return subdata;
    }
    @Override
    public List<Subdata> getCommonProfit(String beginString, String endString, List<Integer> stationIds,String lang) {
        List<Subdata> subdata = new ArrayList<>();
        if (stationIds == null) {
            return subdata;
        }
        List<Station> countStations = getCountStations(stationIds,lang);
        if (countStations != null && !countStations.isEmpty()) {
            if (countStations.size() >= CommonConstant.FIVE) {
                subdata = getSubdata(beginString, endString, countStations);
            } else {
                //电站数目小于5个
                Date date = DateUtil.yesterday();
                Date startDate = DateUtils.addDays(date, -CommonConstant.FIVE);
                Date endDate = DateUtil.endOfDay(date);
                beginString = DateUtil.format(startDate, CommonConstant.DATE_YMD);
                endString = DateUtil.format(endDate, CommonConstant.DATE_YMD);
                subdata = getSubdataByDay(beginString, endString, countStations);
            }
        }
        return subdata;
    }

    @Override
    public List<Subdata> getCommonEfficiencyDate(List<Integer> stationIds,String lang) {
        List<Subdata> subdata = new ArrayList<>();
        if (stationIds == null) {
            return subdata;
        }
        List<Station> countStations = getCountStations(stationIds,lang);
        if (countStations != null && !countStations.isEmpty()) {
            subdata = getEfficiencyDate(countStations);
//            if (countStations.size() >= CommonConstant.FIVE) {
//                subdata = getSubdata(countStations);
//            } else {
//                //电站数目小于5个
//                Date date = DateUtil.yesterday();
//                Date startDate = DateUtils.addDays(date, -CommonConstant.FIVE);
//                Date endDate = DateUtil.endOfDay(date);
//                String beginString = DateUtil.format(startDate, CommonConstant.DATE_YMD);
//                String endString = DateUtil.format(endDate, CommonConstant.DATE_YMD);
//                CommonBigScreenReq req = new CommonBigScreenReq();
//                req.setBeginTime(beginString);
//                req.setEndTime(endString);
//                req.setStationIds(stationIds);
//                subdata = getSubdataByDay(countStations, req);
//            }
        }
        return subdata;
    }

    private void setMonthPvCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        Date date = DateUtil.yesterday();
        Date startDate = DateUtil.beginOfYear(date);
        Date endDate = DateUtil.endOfDay(date);
        String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.MONTH);
        setPvProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_YM, stations);
    }

    private void setMonthCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        Date date = DateUtil.yesterday();
        Date startDate = DateUtil.beginOfYear(date);
        Date endDate = DateUtil.endOfDay(date);
        String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.MONTH);
        setProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_YM, stations);
    }

    private void setYearPVCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        //查询数据的最小日期
        Date beginDate = earningsCalculateMpptService.getFirstTime();
        if(beginDate != null){
            Date date = DateUtil.yesterday();
            Date startDate = DateUtil.beginOfYear(beginDate);
            Date endDate = DateUtil.endOfDay(date);
            String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
            String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
            List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.YEAR);
            setPvProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_Y, stations);
        }
    }
    private void setYearCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        //查询数据的最小日期
        Date beginDate = earningsCalculateService.getFirstTime();
        if(beginDate != null){
            Date date = DateUtil.yesterday();
            Date startDate = DateUtil.beginOfYear(beginDate);
            Date endDate = DateUtil.endOfDay(date);
            String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
            String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
            List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.YEAR);
            setProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_Y, stations);
        }
    }
    private void setDayPvCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        //开始结束时间为30天
        Date date = DateUtil.yesterday();
        Date startDate = DateUtils.addDays(date, -maxSize);
        Date endDate = DateUtil.endOfDay(date);
        String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
        setPvProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_YMD, stations);
    }

    private void setDayCurveResult(List<AnnualChartValue> curveResult, Integer groupId, List<Station> stations) {
        //开始结束时间为30天
        Date date = DateUtil.yesterday();
        Date startDate = DateUtils.addDays(date, -maxSize);
        Date endDate = DateUtil.endOfDay(date);
        String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DateTime> dateTime = DateUtil.rangeToList(startDate, endDate, DateField.DAY_OF_MONTH);
        setProfitByDayFormat(curveResult, groupId, dateTime, begin, end, CommonConstant.DATE_YMD, stations);
    }

    private void setPvProfitByDayFormat(List<AnnualChartValue> curveResult, Integer groupId, List<DateTime> dateTimes, String begin, String end, String type, List<Station> stations) {
        Map<Integer, List<Station>> stationMap = stations.stream().collect(Collectors.groupingBy(Station::getId));
        //查询收益
        List<DayProfitType> dayProfit = earningsCalculateMpptService.getProfit(begin, end, groupId);
        //在使用之前将不要的电站过滤
        List<DayProfitType> profitList = new ArrayList<>();
        for (DayProfitType dayProfitType : dayProfit) {
            if (stationMap.containsKey(dayProfitType.getStationId())) {
                profitList.add(dayProfitType);
            }
        }
        Map<String, List<DayProfitType>> dayMap = profitList.stream().collect(Collectors.groupingBy(DayProfitType::getDay));
        for (DateTime dateTime : dateTimes) {
            AnnualChartValue annualChartValue = new AnnualChartValue();
            String day = DateUtil.format(dateTime, type);
            List<DayProfitType> dayProfitTypes = new ArrayList<>();
            Set<String> dayList = dayMap.keySet();
            for (String key : dayList) {
                if (key.contains(day)) {
                    dayProfitTypes.addAll(dayMap.get(key));
                }
            }
            //收益
            BigDecimal profit = dayProfitTypes.stream().map(DayProfitType::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add);
//            BigDecimal result = profit.divide(new BigDecimal("10000"));
            annualChartValue.setProfit(profit);
            annualChartValue.setTime(day);
            curveResult.add(annualChartValue);
        }
    }

    private void setProfitByDayFormat(List<AnnualChartValue> curveResult, Integer groupId, List<DateTime> dateTimes, String begin, String end, String type, List<Station> stations) {
        //直接查询需要的电站
//        List<Station> list = stationService.selectAll();
//        List<Station> stations = new ArrayList<>();
//        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).forEach(s -> stations.add(s));
        Map<Integer, List<Station>> stationMap = stations.stream().collect(Collectors.groupingBy(Station::getId));

        //查询收益
        //List<DayProfitType> dayProfit = earningsCalculateService.getDayProfit(begin, end, groupId);
        List<DayProfitType> dayProfit = earningsCalculateService.getProfit(begin, end, groupId);
        //在使用之前将不要的电站过滤
        List<DayProfitType> profitList = new ArrayList<>();
        for (DayProfitType dayProfitType : dayProfit) {
            if (stationMap.containsKey(dayProfitType.getStationId())) {
                profitList.add(dayProfitType);
            }
        }

        Map<String, List<DayProfitType>> dayMap = profitList.stream().collect(Collectors.groupingBy(DayProfitType::getDay));
        for (DateTime dateTime : dateTimes) {
            AnnualChartValue annualChartValue = new AnnualChartValue();
            String day = DateUtil.format(dateTime, type);
            List<DayProfitType> dayProfitTypes = new ArrayList<>();
            Set<String> dayList = dayMap.keySet();
            for (String key : dayList) {
                if (key.contains(day)) {
                    dayProfitTypes.addAll(dayMap.get(key));
                }
            }
            //根据类型分组
            Map<Integer, List<DayProfitType>> typeMap = dayProfitTypes.stream().collect(Collectors.groupingBy(DayProfitType::getType));
            //充
            List<DayProfitType> chargeGroupProfitTypes = typeMap.get(CHARGE);
            //放
            List<DayProfitType> dischargeGroupProfitTypes = typeMap.get(DISCHARGE);
            //充收益
            BigDecimal chargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(chargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : chargeGroupProfitTypes) {
                    chargeProfit = chargeGroupProfitType.getDigital() != null ? chargeProfit.add(chargeGroupProfitType.getDigital()) : chargeProfit;
                }
            }
            //放收益
            BigDecimal dischargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(dischargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : dischargeGroupProfitTypes) {
                    dischargeProfit = chargeGroupProfitType.getDigital() != null ? dischargeProfit.add(chargeGroupProfitType.getDigital()) : dischargeProfit;
                }
            }
            BigDecimal result = dischargeProfit.subtract(chargeProfit).divide(new BigDecimal("10000"));
            if (result.doubleValue() > 0.0) {
                annualChartValue.setProfit(result);
            } else {
                log.info("{}，大屏计算收益,放电收益小于充电收益",day);
                annualChartValue.setProfit(BigDecimal.ZERO);
            }
            annualChartValue.setTime(day);
            curveResult.add(annualChartValue);
        }
    }

    private AnnualOverviewResp getEarningsCalculate(List<Station> stations) {
        AnnualOverviewResp annualOverviewResp = new AnnualOverviewResp();
        Integer groupId = stations.get(0).getGroupId();
        Map<Integer, List<Station>> stationMap = stations.stream().collect(Collectors.groupingBy(Station::getId));
        //查询收益
        Date beginDate = earningsCalculateService.getFirstTime();
        if(beginDate == null){
            return annualOverviewResp;
        }
        Date date = DateUtil.yesterday();
        Date startDate = DateUtil.beginOfYear(beginDate);
        Date endDate = DateUtil.endOfDay(date);
        String begin = DateUtil.format(startDate, CommonConstant.DATE_YMD);
        String end = DateUtil.format(endDate, CommonConstant.DATE_YMD);
        List<DateTime> dateTimes = DateUtil.rangeToList(startDate, endDate, DateField.YEAR);
        List<DayProfitType> dayProfit = earningsCalculateService.getProfit(begin, end, groupId);
        //在使用之前将不要的电站过滤
        List<DayProfitType> profitList = new ArrayList<>();
        for (DayProfitType dayProfitType : dayProfit) {
            if (stationMap.containsKey(dayProfitType.getStationId())) {
                profitList.add(dayProfitType);
            }
        }
        Map<String, List<DayProfitType>> dayMap = profitList.stream().collect(Collectors.groupingBy(DayProfitType::getDay));
        List<AnnualChartValue> yearProfitCurve = new ArrayList<>();
        getAnnualOverviewResp(yearProfitCurve, dateTimes, CommonConstant.DATE_Y, dayMap);
        BigDecimal yearProfit = BigDecimal.ZERO;
        for (AnnualChartValue chartValue : yearProfitCurve) {
            yearProfit = yearProfit.add(chartValue.getProfit());
        }
        annualOverviewResp.setTotalProfit(yearProfit);
        startDate = DateUtil.beginOfYear(date);
        List<DateTime> nowDateTime = DateUtil.rangeToList(startDate, endDate, DateField.MONTH);
        List<AnnualChartValue> monthProfitCurve = new ArrayList<>();
        getAnnualOverviewResp(monthProfitCurve, nowDateTime, CommonConstant.DATE_YM, dayMap);
        BigDecimal monthProfit = BigDecimal.ZERO;
        for (AnnualChartValue chartValue : monthProfitCurve) {
            monthProfit = monthProfit.add(chartValue.getProfit());
        }
        annualOverviewResp.setYearProfit(monthProfit);
        List<DateTime> dayDateTime = DateUtil.rangeToList(endDate, endDate, DateField.DAY_OF_MONTH);
        List<AnnualChartValue> dayProfitCurve = new ArrayList<>();
        getAnnualOverviewResp(dayProfitCurve, dayDateTime, CommonConstant.DATE_YMD, dayMap);
        BigDecimal yestProfit = BigDecimal.ZERO;
        for (AnnualChartValue chartValue : dayProfitCurve) {
            yestProfit = yestProfit.add(chartValue.getProfit());
        }
        annualOverviewResp.setYestProfit(yestProfit);
        return annualOverviewResp;
    }

    private void getAnnualOverviewResp(List<AnnualChartValue> curveResult, List<DateTime> dateTimes, String type, Map<String, List<DayProfitType>> dayMap) {
        for (DateTime dateTime : dateTimes) {
            AnnualChartValue annualChartValue = new AnnualChartValue();
            String day = DateUtil.format(dateTime, type);
            List<DayProfitType> dayProfitTypes = new ArrayList<>();
            Set<String> dayList = dayMap.keySet();
            for (String key : dayList) {
                if (key.contains(day)) {
                    dayProfitTypes.addAll(dayMap.get(key));
                }
            }
            //根据类型分组
            Map<Integer, List<DayProfitType>> typeMap = dayProfitTypes.stream().collect(Collectors.groupingBy(DayProfitType::getType));
            //充
            List<DayProfitType> chargeGroupProfitTypes = typeMap.get(CHARGE);
            //放
            List<DayProfitType> dischargeGroupProfitTypes = typeMap.get(DISCHARGE);
            //充收益
            BigDecimal chargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(chargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : chargeGroupProfitTypes) {
                    chargeProfit = chargeGroupProfitType.getDigital() != null ? chargeProfit.add(chargeGroupProfitType.getDigital()) : chargeProfit;
                }
            }
            //放收益
            BigDecimal dischargeProfit = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(dischargeGroupProfitTypes)) {
                for (DayProfitType chargeGroupProfitType : dischargeGroupProfitTypes) {
                    dischargeProfit = chargeGroupProfitType.getDigital() != null ? dischargeProfit.add(chargeGroupProfitType.getDigital()) : dischargeProfit;
                }
            }
            BigDecimal result = dischargeProfit.subtract(chargeProfit).divide(new BigDecimal("10000"));
            if (result.doubleValue() > 0.0) {
                annualChartValue.setProfit(result);
            } else {
                log.info("{}，大屏计算收益,放电收益小于充电收益",day);
                annualChartValue.setProfit(BigDecimal.ZERO);
            }
            annualChartValue.setTime(day);
            curveResult.add(annualChartValue);
        }
    }

    //根据时间
    private List<ElecMeterValue> getByTimeList(List<Station> list, String beginString, String endString) {
        List<ElecMeterValue> resList = new ArrayList<>();
        List<Station> stations = new ArrayList<>();
        list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus()) && LianStationId != i.getId()).forEach(s -> stations.add(s));
        List<Integer> stationIds = stations.stream().map(s -> {
            return s.getId();
        }).collect(Collectors.toList());
        //联城单独计算
        List<Integer> lianStationIds = new ArrayList<>();
        for (Station station : list) {
            if (station.getId() == LianStationId) {
                stations.add(station);
                lianStationIds.add(station.getId());
            }
        }
        if (beginString == null && endString == null) {
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectByStationIdsAndTime(stationIds, null, null, null);
            if (lianStationIds.size() > 0) {
                List<ElecMeterValue> lianElecMeterValues = elecMeterValueService.selectByStationIdsAndTime(lianStationIds, null, null, LianSrc);
                resList.addAll(lianElecMeterValues);
            }
            resList.addAll(elecMeterValues);
        } else {
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectByStationIdsAndTime(stationIds, beginString.substring(0, 10), endString.substring(0, 10), null);
            if (lianStationIds.size() > 0) {
                List<ElecMeterValue> lianElecMeterValues = elecMeterValueService.selectByStationIdsAndTime(lianStationIds, beginString.substring(0, 10), endString.substring(0, 10), LianSrc);
                resList.addAll(lianElecMeterValues);
            }
            resList.addAll(elecMeterValues);
        }

        return resList;
    }

    private AnnualChartValue getCurveResult
            (Map<Integer, PriceValue> stationPrice, List<ElecMeterValue> annualChartList) {
        AnnualChartValue annualChartValue = new AnnualChartValue();
        Map<Integer, List<ElecMeterValue>> dischargeMap = annualChartList.stream().collect(Collectors.groupingBy(ElecMeterValue::getStationId));
        //存放key的List
        List<Integer> keyString = new ArrayList<>();
        Iterator<Map.Entry<Integer, List<ElecMeterValue>>> iter = dischargeMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Integer, List<ElecMeterValue>> entry = iter.next();
            Integer key = entry.getKey();
            keyString.add(key);
        }
        BigDecimal profit = BigDecimal.ZERO;
        for (Integer key : keyString) {
            //日充
            BigDecimal dayCharge = BigDecimal.ZERO;
            //日放
            BigDecimal dayDischarge = BigDecimal.ZERO;
            List<ElecMeterValue> list1 = dischargeMap.get(key);
            PriceValue priceValue = stationPrice.get(key);
            for (ElecMeterValue elecMeterValue : list1) {
                if (DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(elecMeterValue.getType())) {
                    if (FENGStationId == elecMeterValue.getStationId()) {
                        dayCharge = elecMeterValue.getDigital().multiply(new BigDecimal("1000"));
                    } else {
                        dayCharge = elecMeterValue.getDigital();
                    }
                }
                if (DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(elecMeterValue.getType())) {
                    if (FENGStationId == elecMeterValue.getStationId()) {
                        dayDischarge = elecMeterValue.getDigital().multiply(new BigDecimal("1000"));
                    } else {
                        dayDischarge = elecMeterValue.getDigital();
                    }
                }
            }
            BigDecimal divide = dayDischarge.multiply(priceValue.getPeakPrice()).subtract(dayCharge.multiply(priceValue.getLowPrice()));
            profit = profit.add(divide);
        }
        annualChartValue.setProfit(profit);
        return annualChartValue;
    }

    /**
     * 根据电站ids获取筛选统计电站
     *
     * @param stationIds
     * @return
     */
    @Override
    public List<Station> getCountStations(List<Integer> stationIds,String lang) {
        List<Station> list = stationService.selectStationsByIds(stationIds,lang);
        List<Station> oneList = list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus())).collect(Collectors.toList());
        return oneList;
    }

    public List<Station> getCountPvStations(List<Integer> stationIds) {
        List<Station> list = stationService.selectStationsByIds(stationIds,null);
        List<Station> oneList = list.stream().filter(i -> CommonConstant.ONE.equals(i.getStatus()) && CommonConstant.ONE.equals(i.getInverterFlag())).collect(Collectors.toList());
        return oneList;
    }


    @Override
    public List<Subdata> getCommonCapacity(List<Integer> stationIds,String lang) {
        List<Subdata> subDataList = new ArrayList<>();
        if (stationIds != null) {
            List<Station> stations = getCountStations(stationIds,lang);
            subDataList = getSubdataList(stations);
        }
        return subDataList;
    }

    @Override
    public List<EventDayNum> getCommonEventCount(SimpleUser user) {
        EventReqPageVO vo = new EventReqPageVO();
        Date date = DateUtil.yesterday();
        Date startDate = DateUtils.addDays(date, -6);
        vo.setStartTime(DateUtil.format(startDate, CommonConstant.DATE_YMD) + CommonConstant.START_SUFFIX_TIMESTAMP);
        vo.setEndTime(DateUtil.format(date, CommonConstant.DATE_YMD) + CommonConstant.END_SUFFIX_TIMESTAMP);
        vo.setUserLevel(user.getUserLevel());
        vo.setStationIds(user.getStationIds());
        List<EventDayNum> eventDayNums = flowFeignClient.countEventByDay(vo);
        List<DateTime> dateTimes = DateUtil.rangeToList(startDate, date, DateField.DAY_OF_MONTH);
        if (eventDayNums.size() < dateTimes.size()) {
            Map<String, EventDayNum> dayMap = eventDayNums.stream().collect(Collectors.toMap(EventDayNum::getDay, EventDayNum -> EventDayNum));
            List<EventDayNum> list = new ArrayList<>();
            for (DateTime d : dateTimes) {
                String day = DateUtil.format(d, CommonConstant.DATE_YMD);
                EventDayNum dayNum = dayMap.get(day);
                if (dayNum == null) {
                    dayNum = new EventDayNum();
                    dayNum.setDay(day);
                    dayNum.setCount(CommonConstant.ZERO);
                }
                list.add(dayNum);
            }
            eventDayNums = list;
        }
        return eventDayNums;
    }


    private CountEleData getByRedisData(Integer stationId) {
        String key = "screenGroupData:" + stationId;
        CountEleData countEleData = (CountEleData) redisService.get(key);
        return countEleData;
    }
}



