package com.ho.business.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.feignclient.TdFeignClient;
import com.ho.business.mapper.CurveConfigMapper;
import com.ho.business.mapper.DeviceMapper;
import com.ho.business.service.*;
import com.ho.business.vo.DeviceTransfer;
import com.ho.business.vo.req.DeviceReqVO;
import com.ho.business.vo.req.MonitorQuery;
import com.ho.business.vo.req.PvEnegyValueReqVO;
import com.ho.business.vo.req.StationReq;
import com.ho.business.vo.req.colCount.ColCountReq;
import com.ho.business.vo.req.device.DeviceTypeQuery;
import com.ho.business.vo.req.dynamicConfig.DynamicConfigQuery;
import com.ho.business.vo.req.pcsStation.PcsStationReq;
import com.ho.business.vo.resp.*;
import com.ho.business.vo.resp.InverterResp.PowerGenerateRespVO;
import com.ho.business.vo.resp.cabin.TemperatureHumidityResp;
import com.ho.business.vo.resp.cabin.TemperatureValue;
import com.ho.business.vo.resp.colCount.ColCountResp;
import com.ho.business.vo.resp.dynamicConfig.CurveConfigResp;
import com.ho.business.vo.resp.mppt.MpptActiveVo;
import com.ho.business.vo.resp.pcsStation.OutStationData;
import com.ho.business.vo.resp.pcsStation.PcsElecData;
import com.ho.business.vo.resp.pcsStation.PcsStationData;
import com.ho.business.vo.resp.pcsStation.PcsTotalData;
import com.ho.business.vo.resp.station.ActiveReactivePower;
import com.ho.business.vo.resp.station.NewRealTimeCurveVo;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.DefineConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.PointCurveSrcCol;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.BigDecimalUtil;
import com.ho.common.tools.util.RedisCommon;
import com.ho.common.tools.vo.req.PointData;
import com.ho.common.tools.vo.req.StationHomeRespVo;
import com.ho.datacollect.api.constant.DataCollectConstant;
import com.ho.td.api.entity.query.TdBaseTimeQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author gyan
 * @desc: TODO
 * @DateTime: 2023/4/17 11:19
 */
@Service
@Slf4j
public class StationHomeServiceImpl implements StationHomeService {

    @Autowired
    StationService stationService;

    @Autowired
    TdFeignClient tdFeignClient;

    @Autowired
    ElecMeterValueService elecMeterValueService;

    @Autowired
    ModelDeviceService modelDeviceService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    RedisService redisService;

    @Autowired
    DeviceMapper deviceMapper;


    @Autowired
    RedisCommon redisUtil;

    @Autowired
    VirtualDeviceColService virtualDeviceColService;

    @Autowired
    JoinTbSuffixService joinTbSuffixService;

    @Autowired
    DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Autowired
    PointDemoService pointDemoService;

    @Autowired
    OpenStationService openStationService;

    @Autowired
    OutApiService outApiService;

    @Autowired
    FlowFeignClient flowFeignClient;

    @Autowired
    ColCountService colCountService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;

    @Autowired
    EarningsCalculateMpptService earningsCalculateMpptService;

    private List<AppRealTimeCurveRespVo> list;

    @Override
    public List<NewRealTimeCurveVo> getRealtimeCurve(StationReq stationReq) {
        Station station = stationService.selectById(stationReq.getStationId());
        if (station == null) {
            return new ArrayList<>();
        }
        Integer cabinNum = station.getCabinNum();
        if (cabinNum == null) {
            cabinNum = 1;
        }
        List<NewRealTimeCurveVo> voList = new ArrayList<>();
        String key = "realTimeCurve:"+station.getId();
        List<NewRealTimeCurveVo> hget = (List<NewRealTimeCurveVo>)redisService.hget(key,key);
        String date = (String)redisService.hget(key, DeviceTypeConstant.POINT_DATA.DATE);
        String today = DateUtil.format(new Date(), CommonConstant.DATE_YMD);
        if(hget == null || date == null || today.compareTo(date)>0){
            voList = getNewRealTimeCurveVos(stationReq, station);
        }else{
            voList = hget;
            //异步调用
            CompletableFuture.supplyAsync(()->getNewRealTimeCurveVos(stationReq, station));
        }
        //创建返回值
        return voList;
    }

    @NotNull
    private List<NewRealTimeCurveVo> getNewRealTimeCurveVos(StationReq stationReq, Station station) {
        List<NewRealTimeCurveVo> voList = new ArrayList<>();
        List<StationHomeRespVo> list = new ArrayList<>();
        List<DeviceRespVO> pcsDeviceList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.PCS);
        if (pcsDeviceList.isEmpty()) {
            pcsDeviceList = deviceService.getListByFuzzyDeviceType(stationReq.getStationId(), DeviceTypeConstant.PCS);
        }
        List<DeviceRespVO> bmsDeviceList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.BMS);
        if (bmsDeviceList.isEmpty()) {
            bmsDeviceList = deviceService.getListByFuzzyDeviceType(stationReq.getStationId(), DeviceTypeConstant.BMS);
        }
        //光伏逆变器
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationReq.getStationId());
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.INVERTER);
        List<DeviceRespVO> inverterDeviceList = deviceService.getList(deviceReqVO);
        //防逆流
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.AMMETER_FNL);
        List<DeviceRespVO> fnlDeviceList = deviceService.getList(deviceReqVO);

        String beginTime = null;
        String endTime = null;
        DateTime beginTimeParse = null;
        DateTime endParse = null;
        Integer samlRate = null;
        List<DateTime> dateTimes = new ArrayList<>();
        //开始时间 当天时间（零点）
        if (stationReq.getBeginTime() == null || stationReq.getBeginTime() == null) {
            //取开始时间结束时间
            Date date = new Date();
            beginTime = DateUtil.format(DateUtil.beginOfDay(date), CommonConstant.DATE);
            beginTimeParse = DateUtil.parse(beginTime, CommonConstant.DATE);
            endTime = DateUtil.format(date, CommonConstant.DATE);
            endParse = DateUtil.parse(endTime, CommonConstant.DATE);
        } else {
            beginTime = stationReq.getBeginTime();
            beginTimeParse = DateUtil.parse(beginTime, CommonConstant.DATE);
            endTime = stationReq.getEndTime();
            endParse = DateUtil.parse(endTime, CommonConstant.DATE);
        }
        //计算(采样率)出开始时间与结束时间的差 （大于1440 采样率是 时间/60）
        int timeDifference = pointDemoService.getTimeDifference(beginTime, endTime);
        if (timeDifference <= 1441) {
            samlRate = 1;
        } else {
            double divisor = 1441;
            double flag = Math.ceil(timeDifference / divisor);        //向上取整计算
            samlRate = (int) flag;
        }
        //通过size拿到循环的个数
        dateTimes = DateUtil.rangeToList(beginTimeParse, endParse, DateField.MINUTE, samlRate);
        //查询时间
        List<String> hourList = dateTimes.stream().map(s -> {
            return DateUtil.format(s, CommonConstant.DATE);
        }).collect(Collectors.toList());
        for (int i = 0; i < hourList.size(); i++) {
            StationHomeRespVo stationHomeRespVo = new StationHomeRespVo();
            stationHomeRespVo.setDate(hourList.get(i));
            list.add(stationHomeRespVo);

        }
        String finalBeginTime = beginTime;
        String finalEndTime = endTime;
        Integer finalSamlRate = samlRate;
        List<CompletableFuture<NewRealTimeCurveVo>> resultList = new ArrayList<>();
        try {
            pcsDeviceList.forEach(deviceRespVO->{
                CompletableFuture<NewRealTimeCurveVo> f = CompletableFuture.supplyAsync(() -> {
                    List<DeviceRespVO> deviceList = new ArrayList<>();
                    deviceList.add(deviceRespVO);
                    //outputPower :PCS总输出有功率 (KW)
                    DeviceColData outputPowerData = getDeviceColData(deviceList, "outputPower");
                    List<StationHomeRespVo> pointTableData = getStationHomeRespVos(station, finalBeginTime, finalEndTime, finalSamlRate, outputPowerData);
                    NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
                    vo.setSrcId(deviceRespVO.getSrcId());
                    vo.setDeviceName(deviceRespVO.getDeviceName());
                    vo.setName(DefineConstant.StationHome.OUTPUT_POWER);
                    if (pointTableData != null) {
                        vo.setList(pointTableData);
                    } else {
                        vo.setList(new ArrayList<>());
                    }
                    return vo;
                },threadPoolExecutor);
                resultList.add(f);
            });
            CompletableFuture.allOf(resultList.toArray(new CompletableFuture[resultList.size()])).join();
            for (CompletableFuture<NewRealTimeCurveVo> c : resultList) {
                voList.add(c.get());
            }
        }catch (Exception e){
            log.error("getRealtimeCurve pcs Error,stationId:{},message:{}" , stationReq.getStationId(), e.getMessage());
        }
        Integer stationId = stationReq.getStationId();
        if (stationId == 418) {
            for (DeviceRespVO deviceRespVO : bmsDeviceList) {
                List<NewRealTimeCurveVo> socList = new ArrayList<>();
                List<DeviceRespVO> deviceList = new ArrayList<>();
                deviceList.add(deviceRespVO);
                DeviceColData socPowerData = getDeviceColData(deviceList, "soc");
                List<String> cols = new ArrayList<>();
                cols.add("YC0078");
                cols.add("YC0116");
                cols.add("YC0154");
                cols.add("YC0192");
                cols.add("YC0230");
                cols.add("YC0268");
                cols.add("YC0306");
                for (String s : cols) {
                    List<String> colList = new ArrayList<>();
                    colList.add(s);
                    socPowerData.getDeviceIdList().get(0).setCols(colList);
                    List<StationHomeRespVo> pointTableData = getStationHomeRespVos(station, beginTime, endTime, samlRate, socPowerData);
                    NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
                    vo.setSrcId(deviceRespVO.getSrcId());
                    vo.setName("soc");
                    vo.setDeviceName(deviceRespVO.getDeviceName());
                    if (pointTableData != null) {
                        vo.setList(pointTableData);
                    } else {
                        vo.setList(new ArrayList<>());
                    }
                    socList.add(vo);
                }
                mergeCurve(voList, socList, deviceRespVO.getDeviceName(), "soc", CommonConstant.ONE);
            }
        } else {
            List<CompletableFuture<NewRealTimeCurveVo>> bmsResultList = new ArrayList<>();
            try {
                bmsDeviceList.forEach(deviceRespVO->{
                    CompletableFuture<NewRealTimeCurveVo> f = CompletableFuture.supplyAsync(() -> {
                        List<DeviceRespVO> deviceList = new ArrayList<>();
                        deviceList.add(deviceRespVO);
                        DeviceColData socPowerData = getDeviceColData(deviceList, "soc");
                        List<StationHomeRespVo> pointTableData = getStationHomeRespVos(station, finalBeginTime, finalEndTime, finalSamlRate, socPowerData);
                        NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
                        vo.setSrcId(deviceRespVO.getSrcId());
                        vo.setName("soc");
                        vo.setDeviceName(deviceRespVO.getDeviceName());
                        if (pointTableData != null) {
                            //BMS过滤超过最大最小值的数据
                            DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(socPowerData.getDeviceIdList().get(0).getCols().get(0), deviceRespVO.getDeviceType(),null);
                            BigDecimal maxValue = deviceTypeCol.getMaxValue();
                            BigDecimal minValue = deviceTypeCol.getMinValue();
                            if(maxValue!= null && minValue!= null){
                                pointTableData = pointTableData.stream().filter(e -> (e.getDigital()==null)||
                                        (e.getDigital().compareTo(minValue)>=0&& e.getDigital().compareTo(maxValue)<=0)).collect(Collectors.toList());
                            }
                            vo.setList(pointTableData);
                        } else {
                            vo.setList(new ArrayList<>());
                        }
                        return vo;
                    },threadPoolExecutor);
                    bmsResultList.add(f);
                });
                CompletableFuture.allOf(bmsResultList.toArray(new CompletableFuture[bmsResultList.size()])).join();
                for (CompletableFuture<NewRealTimeCurveVo> c : bmsResultList) {
                    voList.add(c.get());
                }
            }catch (Exception e){
                log.error("getRealtimeCurve bms Error,stationId:{},message:{}", stationReq.getStationId(), e.getMessage());
            }
        }
        //光储逆变器几个站特殊处理
        String specialStaion = "576,577,578";
        if (specialStaion.contains(String.valueOf(station.getId()))) {
            //光储逆变器
            List<DeviceRespVO> opticalDeviceList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.OPTICAL_STORAGE);
            if (opticalDeviceList.isEmpty()) {
                opticalDeviceList = deviceService.getListByFuzzyDeviceType(stationReq.getStationId(), DeviceTypeConstant.OPTICAL_STORAGE);
            }
            List<NewRealTimeCurveVo> pvList = getNewRealTimeCurveVos(station, opticalDeviceList, beginTime, endTime, samlRate, "acActivePower", DefineConstant.StationHome.PV_OUTPUT_POWER);
            voList.addAll(pvList);
            List<NewRealTimeCurveVo> powerList = getNewRealTimeCurveVos(station, opticalDeviceList, beginTime, endTime, samlRate, "outputPower", DefineConstant.StationHome.OUTPUT_POWER);
            voList.addAll(powerList);
            deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.LOAD_SIDE_METER);
            List<DeviceRespVO> elecDeviceList = deviceService.getList(deviceReqVO);
            List<NewRealTimeCurveVo> elecList = getNewRealTimeCurveVos(station, elecDeviceList, beginTime, endTime, samlRate, "activePower", DefineConstant.StationHome.OUTPUT_POWER);
            voList.addAll(elecList);
        }
        //增加光伏曲线
        List<NewRealTimeCurveVo> inverterList = getNewRealTimeCurveVos(station, inverterDeviceList, beginTime, endTime, samlRate, "acActivePower", "");
        //光伏逆变器合并成一个
        addVoList(voList, inverterList, DefineConstant.StationHome.PV_INVERTER, DefineConstant.StationHome.TOTAL_PV_POWER);
        //增加防逆流电表
        List<NewRealTimeCurveVo> fnlList = getNewRealTimeCurveVos(station, fnlDeviceList, beginTime, endTime, samlRate, "activePower", "");
        //防逆流电表合并成一个
        addVoList(voList, fnlList, DefineConstant.StationHome.ANTI_BACKFLOW_METER, DefineConstant.StationHome.TOTAL_ACTIVE_POWER);

        for (NewRealTimeCurveVo newRealTimeCurveVo : voList) {
            List<StationHomeRespVo> homeRespVoList = newRealTimeCurveVo.getList();
            for (int i = 0; i < list.size(); i++) {
                if (homeRespVoList != null && !CommonConstant.ZERO.equals(homeRespVoList.size())) {
                    homeRespVoList.get(i).setDate(list.get(i).getDate());
                }
            }
        }
        //进行返回
        Date date = new Date();
        String redisKey = "realTimeCurve:"+station.getId();
        Map<String,Object> map = new HashMap<>();
        map.put(redisKey,voList);
        map.put(DataCollectConstant.UPDATE_TIME,DateUtil.format(date,CommonConstant.DATE));
        map.put(DeviceTypeConstant.POINT_DATA.DATE,DateUtil.format(date,CommonConstant.DATE_YMD));
        redisService.hmset(redisKey,map);
        redisService.expire(redisKey,3, TimeUnit.MINUTES);
        return voList;
    }

    /**
     * 合并曲线
     *
     * @param voList
     * @param list
     * @param deviceName
     * @param name
     */
    private void mergeCurve(List<NewRealTimeCurveVo> voList, List<NewRealTimeCurveVo> list, String deviceName, String name, Integer flag) {
        if (!list.isEmpty()) {
            NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
            List<StationHomeRespVo> inList = list.get(0).getList();
            int len = list.size();
            int sunLen = inList.size();
            List<StationHomeRespVo> valList;
            for (int i = 1; i < len; i++) {
                valList = list.get(i).getList();
                if (!valList.isEmpty()) {
                    for (int j = 0; j < sunLen; j++) {
                        inList.get(j).setDigital(inList.get(j).getDigital() == null ? valList.get(j).getDigital() : inList.get(j).getDigital().add(valList.get(j).getDigital() == null ? BigDecimal.ZERO : valList.get(j).getDigital()));
                    }
                }
            }
            if (CommonConstant.ONE.equals(flag)) {
                inList.forEach(s -> s.setDigital(s.getDigital() == null ? null : s.getDigital().divide(BigDecimal.valueOf(len), 2, BigDecimal.ROUND_HALF_UP)));
            }
            vo.setList(inList);
            vo.setDeviceName(deviceName);
            vo.setName(name);
            voList.add(vo);
        }
    }

    @Override
    public List<NewRealTimeCurveVo> getStrategyCurve(StationReq stationReq) {
        List<NewRealTimeCurveVo> voList = getRealtimeCurve(stationReq);
//        if(!voList.isEmpty()){
//            List<StationHomeRespVo> list = voList.get(0).getList();
//            list.stream().forEach(s -> s.setDigital(BigDecimal.ZERO));
//            //需量限制
//            NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
//            vo.setName("demandLimit");
//            vo.setDeviceName("需量限制");
//            vo.setList(list);
//            voList.add(vo);
//            //逆功率限制
//            vo = new NewRealTimeCurveVo();
//            vo.setName("reversePowerLimit");
//            vo.setDeviceName("逆功率限制");
//            vo.setList(list);
//            voList.add(vo);
//        }
        //进行返回
        return voList;
    }

    /**
     * 汇总曲线
     *
     * @param voList
     * @param list
     * @param deviceName
     * @param curveName
     */
    private void addVoList(List<NewRealTimeCurveVo> voList, List<NewRealTimeCurveVo> list, String deviceName, String curveName) {
        if (!list.isEmpty()) {
            NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
            List<StationHomeRespVo> inList = list.get(0).getList();
            int len = list.size();
            int sunLen = inList.size();
            List<StationHomeRespVo> valList;
            for (int i = 1; i < len; i++) {
                valList = list.get(i).getList();
                for (int j = 0; j < sunLen; j++) {
                    inList.get(j).setDigital(inList.get(j).getDigital() == null ? valList.get(j).getDigital() : inList.get(j).getDigital().add(valList.get(j).getDigital() == null ? BigDecimal.ZERO : valList.get(j).getDigital()));
                }
            }
            vo.setList(inList);
            vo.setDeviceName(deviceName);
            vo.setName(curveName);
            voList.add(vo);
        }
    }

    /**
     * @param station
     * @param dList
     * @param beginTime
     * @param endTime
     * @param samlRate
     * @param modelCol
     * @param name
     * @return
     */
    @NotNull
    private List<NewRealTimeCurveVo> getNewRealTimeCurveVos(Station station, List<DeviceRespVO> dList, String beginTime, String endTime, Integer samlRate, String modelCol, String name) {
        List<NewRealTimeCurveVo> list = new ArrayList<>();
        for (DeviceRespVO deviceRespVO : dList) {
            List<DeviceRespVO> deviceList = new ArrayList<>();
            deviceList.add(deviceRespVO);
            DeviceColData powerData = getDeviceColData(deviceList, modelCol);
            if (powerData.getDeviceIdList().isEmpty()) {
                continue;
            }
            List<StationHomeRespVo> pointTableData = getStationHomeRespVos(station, beginTime, endTime, samlRate, powerData);
            NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
            vo.setSrcId(deviceRespVO.getSrcId());
            vo.setName(name);
            vo.setDeviceName(deviceRespVO.getDeviceName());
            if (pointTableData != null) {
                vo.setList(pointTableData);
            } else {
                vo.setList(new ArrayList<>());
            }
            list.add(vo);
        }
        return list;
    }

    /**
     * 封装查数据
     *
     * @param station
     * @param beginTime
     * @param endTime
     * @param samlRate
     * @param socPowerData
     * @return
     */
    @Override
    public List<StationHomeRespVo> getStationHomeRespVos(Station station, String beginTime, String endTime, Integer samlRate, DeviceColData socPowerData) {
        TdBaseTimeQuery tdBaseQuery = new TdBaseTimeQuery();
        tdBaseQuery.setBeginTime(beginTime);
        tdBaseQuery.setEndTime(endTime);
        tdBaseQuery.setTime(samlRate + "m");
        tdBaseQuery.setStationId(station.getId());
        tdBaseQuery.setGroupId(station.getGroupId());
        tdBaseQuery.setMap(socPowerData.getMap());
        tdBaseQuery.setDeviceIdList(socPowerData.getDeviceIdList());
        log.info("realtimeCurve.tdBaseQuery:" + tdBaseQuery);
        DataResult<List<StationHomeRespVo>> pointTable = tdFeignClient.getPointTable(tdBaseQuery);
        List<StationHomeRespVo> pointTableData = pointTable.getData();
        return pointTableData;
    }


    //根据colName进行
    // 查询（查询数据库的表名/设备字段名称）
    @Override
    public DeviceColData getDeviceColData(List<DeviceRespVO> list, String modelCol) {
        DeviceColData deviceColData = new DeviceColData();
        //在根据模型字段查询到设备字段的colName，
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        //存储srcId以及config名字
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();
        List<PointCurveSrcCol> deviceIdList = new ArrayList<>();
        for (Device device : list) {
            //实时PCS取点表指标PCS总输出有功率 (KW)
            List<ModelDeviceColComp> compListByType = modelDeviceService.getCompListByType("device", device.getDeviceType(), modelCol);
            VirtualDeviceCol vo = new VirtualDeviceCol();
            vo.setSrcId(device.getSrcId());
            vo.setStationId(device.getStationId());
            vo.setType(modelCol);
            List<VirtualDeviceColResp> virList = virtualDeviceColService.getList(vo);
            Device deviceValue = new DeviceRespVO();
            if (!compListByType.isEmpty() || !virList.isEmpty()) {
                List<String> cols = new ArrayList<>();
                if (CommonConstant.ONE.equals(device.getVirtual())) {
                    if (!virList.isEmpty()) {
                        cols.add(virList.get(0).getCol());
                    }
                    deviceValue = deviceMapper.selectByStationIdAndSrcId(device.getStationId(), device.getPid());
                    DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
                    if (deviceValue != null && deviceValue.getDeviceType() != null) {
                        deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceValue.getDeviceType(), deviceValue.getGroupId());
                    }
                    if (deviceTypeConfig != null) {
                        map.put(device.getPid(), deviceTypeConfig.getModelName());
                        srcIdAndNameMap.put(device.getPid(), deviceValue.getDeviceName());
                        srcIdAndDeviceTypeMap.put(device.getPid(), device.getDeviceType());
                    }
                    PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                    pointCurveSrcCol.setSrcId(device.getPid());
                    if (cols.isEmpty()) {
                        cols.add(compListByType.get(0).getDeviceCol());
                    }
                    DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(cols.get(0), deviceValue.getDeviceType(),null);
                    deviceColData.setSensType(deviceTypeCol.getSensType());
                    pointCurveSrcCol.setCols(cols);
                    deviceIdList.add(pointCurveSrcCol);
                } else {
                    deviceValue = deviceMapper.selectByStationIdAndSrcId(device.getStationId(), device.getSrcId());
                    DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
                    if (deviceValue != null && deviceValue.getDeviceType() != null) {
                        deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceValue.getDeviceType(), deviceValue.getGroupId());
                    }
                    if (deviceTypeConfig != null) {
                        map.put(device.getSrcId(), deviceTypeConfig.getModelName());
                        srcIdAndNameMap.put(device.getSrcId(), deviceValue.getDeviceName());
                        srcIdAndDeviceTypeMap.put(device.getSrcId(), device.getDeviceType());
                    }
                    deviceColData.setSensType(compListByType.get(0).getSensType());
                    PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                    pointCurveSrcCol.setSrcId(device.getSrcId());
                    if (cols.isEmpty()) {
                        cols.add(compListByType.get(0).getDeviceCol());
                    }
                    pointCurveSrcCol.setCols(cols);
                    deviceIdList.add(pointCurveSrcCol);
                }
            }
        }
        deviceColData.setMap(map);
        deviceColData.setDeviceIdList(deviceIdList);
        deviceColData.setSrcIdAndDeviceTypeMap(srcIdAndDeviceTypeMap);
        deviceColData.setSrcIdAndNameMap(srcIdAndNameMap);
        return deviceColData;
    }

    /**
     * 根据电站id查询电站信息
     *
     * @param stationId 电站id
     * @return
     */
    @Override
    public PcsStationData getPcsStationData(Integer stationId,String lang) {
        //根据id查询电站
        Station station = stationService.selectById(stationId);
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        //赋值返回
        PcsStationData data = new PcsStationData();
        BeanUtils.copyProperties(station, data);
        //计算运行天数
        String operationDayStr = null;
        String name = station.getName();
        if (station.getStatus().equals(CommonConstant.TWO)) {
            if(CommonConstant.langTemp.EN_US.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_EN;
                name = station.getNameEn();
            }else if(CommonConstant.langTemp.FR_FR.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_FRA;
                name = station.getNameFra();
            }else if(CommonConstant.langTemp.ES_ES.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_SPA;
                name = station.getNameSpa();
            }else if(CommonConstant.langTemp.AR_EG.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_ARA;
                name = station.getNameAra();
            }else if(CommonConstant.langTemp.DE_DE.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_DE;
                name = station.getNameDe();
            }else if(CommonConstant.langTemp.PL_PL.equals(lang)){
                operationDayStr = DefineConstant.StationHome.BUILDING_PL;
                name = station.getNamePl();
            }else{
                operationDayStr = DefineConstant.StationHome.BUILDING;
            }
        } else if (station.getStatus().equals(CommonConstant.THREE)) {
            if(CommonConstant.langTemp.EN_US.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_EN;
                name = station.getNameEn();
            }else if(CommonConstant.langTemp.FR_FR.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_FRA;
                name = station.getNameFra();
            }else if(CommonConstant.langTemp.ES_ES.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_SPA;
                name = station.getNameSpa();
            }else if(CommonConstant.langTemp.AR_EG.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_ARA;
                name = station.getNameAra();
            }else if(CommonConstant.langTemp.DE_DE.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_DE;
                name = station.getNameDe();
            }else if(CommonConstant.langTemp.PL_PL.equals(lang)){
                operationDayStr = DefineConstant.StationHome.PROPOSED_PL;
                name = station.getNamePl();
            }else{
                operationDayStr = DefineConstant.StationHome.PROPOSED;
            }
        } else {
            long operationDays = DateUtil.between(station.getGridTime(), new Date(), DateUnit.DAY);
            operationDayStr = Long.toString(operationDays);
        }

        // 储能首页的投运时间与站点信息中的并网时间保持一致 禅道bug-2000
        data.setCreateTime(station.getGridTime());

        // long operationDays = DateUtil.between(station.getGridTime(), new Date(), DateUnit.DAY);
        data.setOperationDays(operationDayStr);
        data.setName(name);
        return data;
    }

    /**
     * 根据电站id查询数据总览
     *
     * @param req
     * @return
     */
    @Override
    public PcsTotalData getPcsTotalData(StationReq req) {
        Integer stationId = req.getStationId();
        //根据id查询电站
        Station station = stationService.selectById(stationId);
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }

        //计算运行天数
        //计算运行天数
        String operationDayStr = null;
        if (station.getStatus().equals(CommonConstant.TWO)) {
            // 多语言切换
            if(CommonConstant.langTemp.EN_US.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_EN;
            }else if(CommonConstant.langTemp.FR_FR.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_FRA;
            }else if(CommonConstant.langTemp.ES_ES.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_SPA;
            }else if(CommonConstant.langTemp.AR_EG.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_ARA;
            }else if(CommonConstant.langTemp.DE_DE.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_DE;
            }else if(CommonConstant.langTemp.PL_PL.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.BUILDING_PL;
            }else{
                operationDayStr = DefineConstant.StationHome.BUILDING;
            }
        } else if (station.getStatus().equals(CommonConstant.THREE)) {
            if(CommonConstant.langTemp.EN_US.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_EN;
            }else if(CommonConstant.langTemp.FR_FR.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_FRA;
            }else if(CommonConstant.langTemp.ES_ES.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_SPA;
            }else if(CommonConstant.langTemp.AR_EG.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_ARA;
            }else if(CommonConstant.langTemp.DE_DE.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_DE;
            }else if(CommonConstant.langTemp.PL_PL.equals(req.getLang())){
                operationDayStr = DefineConstant.StationHome.PROPOSED_PL;
            }else{
                operationDayStr = DefineConstant.StationHome.PROPOSED;
            }
        } else {
            long operationDays = DateUtil.between(station.getGridTime(), new Date(), DateUnit.DAY);
            operationDayStr = Long.toString(operationDays);
        }

        //计算系统转化效率
        BigDecimal systemEfficiency = BigDecimal.ZERO;
        //获取 日充日放 总充总放
        CountEleData countEleData = getCountEleData(req);
        //总充电量
        BigDecimal totalChargeElec = countEleData.getTotalChargeElec();
        //总放电量
        BigDecimal totalDischargeElec = countEleData.getTotalDischargeElec();
        //日充电量
        BigDecimal dailyChargeElec = countEleData.getDailyChargeElec();
        //日放电量
        BigDecimal dailyDischargeElec = countEleData.getDailyDischargeElec();

        ColCountReq colCountReq = new ColCountReq();
        colCountReq.setStationId(station.getId());
        colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
        //总充
        List<ColCountResp> chargeList = colCountService.selectByParam(colCountReq);
        //总放
        colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
        List<ColCountResp> disChargeList = colCountService.selectByParam(colCountReq);
        totalChargeElec = colCountService.countOffset(totalChargeElec, chargeList);
        totalDischargeElec = colCountService.countOffset(totalDischargeElec, disChargeList);
        /*************根据站端统计总的SOC，判断是否要实时计算系统转换效率******************/
        boolean flag = false;
        ColCountReq vo = new ColCountReq();
        vo.setStationId(req.getStationId());
        vo.setCol(DeviceTypeConstant.TOTAL_SOC);
        List<ColCountResp> colCountResps = colCountService.selectByParam(vo);
        String totalKey = null;
        if (null != colCountResps && colCountResps.size() > 0) {
            ColCountResp colCountResp = colCountResps.get(0);
            BigDecimal identifyNum = colCountResp.getIdentifyNum();
            if (CommonConstant.FIVE.equals(colCountResp.getCountMethod())) {
                List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, colCountResp.getDeviceType());
                BigDecimal setVal = BigDecimal.ZERO;
                for (DeviceRespVO deviceRespVO : deviceRespVOS) {
                    //拼接电表缓存key
                    totalKey = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
                    if (redisService.hasKey(totalKey)) {
                        Map<Object, Object> map = redisService.hgetall(totalKey);
                        if (map != null) {
                            //总soc
                            DeviceTransfer objTotalCharge = (DeviceTransfer) map.get(DeviceTypeConstant.TOTAL_SOC);
                            if (objTotalCharge != null) {
                                setVal = objTotalCharge.getValue();
                            }
                            objTotalCharge = (DeviceTransfer) map.get(DeviceTypeConstant.SYSTEM_EFFICIENCY);
                            if (objTotalCharge != null) {
                                systemEfficiency = objTotalCharge.getValue();
                            }
                        }
                    }
                }
                //当当前值小于设定值时，需要计算
                if (identifyNum.compareTo(setVal) > 0) {
                    flag = true;
                }
            }
        }

        if (BigDecimal.ZERO.compareTo(totalChargeElec) != 0) {
            if (flag || BigDecimal.ZERO.compareTo(systemEfficiency) == 0) {
                systemEfficiency = totalDischargeElec.divide(totalChargeElec, 4, BigDecimal.ROUND_HALF_UP);
                if (null != totalKey) {
                    DeviceTransfer deviceTransfer = new DeviceTransfer();
                    deviceTransfer.setValue(systemEfficiency);
                    deviceTransfer.setUpdateTime(new Date());
                    redisService.hset(totalKey, DeviceTypeConstant.SYSTEM_EFFICIENCY, deviceTransfer);
                }
            }
        }
        //创建返回值并赋值
        PcsTotalData data = new PcsTotalData();
        data.setTotalCapacity(station.getCapacity());
        data.setRateCapacity(station.getCapacity());
        data.setOperationDays(operationDayStr);
        data.setTotalChargeElec(totalChargeElec);
        data.setTotalDischargeElec(totalDischargeElec);
        //日充, 日放
        data.setDailyChargeElec(dailyChargeElec);
        data.setDailyDischargeElec(dailyDischargeElec);
        data.setRatePower(station.getRatePower());
        data.setSystemEfficiency(systemEfficiency);
        //当前功率
        ActiveReactivePower acPower = openStationService.getAcPower(stationId);
        //2025-11-13 start 储能加入mppt模块开发
        //如果接入光伏mppt模块-则统计光伏模块监控数据
        if(DataCollectConstant.ONE.equals(station.getInverterFlag())){
            //当前功率(光伏)、总发电量、日发电量
            MpptActiveVo pv = openStationService.getPvActivePower(stationId);
            data.setCurrentPower(pv.getPvActivePower());
            data.setDailyReleaseElec(pv.getDailyReleaseElec());
            //计算累计发电量
            BigDecimal totalReleaseElec = elecMeterValueService.selectSumValue(station.getId(),DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE,null);
            totalReleaseElec = totalReleaseElec.add(pv.getDailyReleaseElec());
            data.setTotalReleaseElec(totalReleaseElec);
            //今日收益
            String key = RedisKeyConstant.PV.STATION_PV_TODAY_PROFIT + station.getId();
            BigDecimal todayIncone = (BigDecimal)redisService.get(key);
            todayIncone = todayIncone==null?BigDecimal.ZERO:todayIncone;
            data.setTodayIncone(todayIncone);
            //累计收益
            BigDecimal totalIncome = earningsCalculateMpptService.countAllPvIncome(station.getId(),null,null);
            totalIncome = totalIncome.add(todayIncone);
            data.setTotalIncome(totalIncome);
            //额定功率(光伏)
            data.setPvPower(station.getPvPower());
        }


        if (acPower != null) {
            data.setCurrentPower(acPower.getActivePowerPCS());
        }
        return data;
    }

    /**
     * 根据电站的id和type(年:year,月:month,日:day)查询充放电量统计图
     *
     * @param req 充放电量统计图入参
     * @return
     */
    @Override
    public List<PcsElecData> getPcsElecData(PcsStationReq req) throws ParseException {

        //创建返回值
        List<PcsElecData> list = new ArrayList<>();
        //获取日充日放
        CountEleData countEleData = getCountEleData(req);
        //日充电量
        BigDecimal dailyChargeElec = countEleData.getDailyChargeElec();
        //日放电量
        BigDecimal dailyDischargeElec = countEleData.getDailyDischargeElec();
        //查询冻结值
        List<Integer> typeList = new ArrayList<>();
        //充放电
        typeList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
        typeList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);

        //根据传入类型判断
        //当前时间
        Date end = new Date();
        String endTime = DateUtil.format(end, CommonConstant.DATE_YMD);
        String type = req.getType();
        boolean isToday = true;
        if (CommonConstant.HOUR.equals(type)) {
            Date date = new Date();
            if (null != req.getBeginTime()) {
                isToday = DateUtil.compare(DateUtil.parseDate(req.getBeginTime()), DateUtil.parseDate(DateUtil.format(date, CommonConstant.DATE_YMD))) >= 0;
            }
            SimpleDateFormat dfFormat = new SimpleDateFormat(CommonConstant.DATE);
            SimpleDateFormat sdfDateHTime = new SimpleDateFormat(CommonConstant.DATE_YMD_H);
            // 当前时间（2023-09-01 10:43:00）转换格式 (2023-09-01 10:00:00)
            String newHour = sdfDateHTime.format(date) + CommonConstant.MINUTES_SECONDS_BEGIN;
            DateTime dateTime = new DateTime(dfFormat.parse(newHour));
            DateTime begin = DateUtil.beginOfDay(date);
            String dateTimeString = dfFormat.format(begin);
            //查询冻结值
            List<Integer> typeHourList = new ArrayList<>();
            //充放电
            typeHourList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE);
            typeHourList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE);
            if (!isToday) {
                dateTimeString = req.getBeginTime() + " 00:00:00";
                newHour = req.getBeginTime() + " 23:00:00";
                begin = new DateTime(dateTimeString);
                dateTime = new DateTime(dfFormat.parse(newHour));
            }
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeHourList, dateTimeString, newHour);
            //根据天获取时间段
            List<DateTime> dateTimes = DateUtil.rangeToList(begin, dateTime, DateField.HOUR_OF_DAY);
            //根据类型进行分组
//            Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
            setHourByTime(dateTimes, elecMeterValues, list);

        } else if (CommonConstant.DAY.equals(type)) {
            //查询最近七天
            //七天前的时间
            DateTime begin = DateUtil.offsetDay(end, -6);
            String beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeList, beginTime, endTime);
            elecMeterValues = getMeterValues(req, elecMeterValues);
            //根据天获取时间段
            List<DateTime> dateTimes = DateUtil.rangeToList(begin, end, DateField.DAY_OF_MONTH);
            setDataByTime(dateTimes,elecMeterValues,list);
            //根据类型进行分组
//            Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
//            setDataByTime(dateTimes, map, list);
        } else if (CommonConstant.RANGE_TIME.equals(type)) {
            list = new ArrayList<>();
            //查询时间范围数据
            List<Integer> typeHourList = new ArrayList<>();
            typeHourList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE);
            typeHourList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE);
            DateTime begin = new DateTime(DateUtils.addDays(new DateTime(req.getBeginTime()), -1));
            DateTime dateTime = new DateTime(req.getEndTime());
            String beginTime = DateUtil.format(begin, CommonConstant.DATE);
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeHourList, beginTime, req.getEndTime());
            Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
            List<DateTime> days = DateUtil.rangeToList(begin, dateTime, DateField.DAY_OF_MONTH);
            setRangeTime(days, map, list);
        } else if (CommonConstant.MONTH.equals(type)) {
            //七天前的时间
            DateTime begin = DateUtil.offsetDay(end, -29);
            String beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeList, beginTime, endTime);
            elecMeterValues = getMeterValues(req, elecMeterValues);
            //根据天获取时间段
            List<DateTime> dateTimes = DateUtil.rangeToList(begin, end, DateField.DAY_OF_MONTH);
            setDataByTime(dateTimes,elecMeterValues,list);
            //根据类型进行分组
//            Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
//            setDataByTime(dateTimes, map, list);
        } else if (CommonConstant.YEAR.equals(type)) {
            DateTime begin = DateUtil.offsetDay(end, -364);
            String beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeList, beginTime, endTime);
            elecMeterValues = getMeterValues(req, elecMeterValues);
            //根据类型进行分组
            Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
            //充电量
            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            Map<String, List<ElecMeterValue>> monthChargeList = new HashMap<>();
            if (chargeList != null) {
                monthChargeList = chargeList.stream().collect(Collectors.groupingBy(s -> {
                    String month = s.getDay().substring(0, 7);
                    return month;
                }));
            }
            //放电量
            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            Map<String, List<ElecMeterValue>> monthDischargeList = new HashMap<>();
            if (dischargeList != null) {
                monthDischargeList = dischargeList.stream().collect(Collectors.groupingBy(s -> {
                    String month = s.getDay().substring(0, 7);
                    return month;
                }));
            }
            //根据天获取时间段
            List<DateTime> dateTimes = DateUtil.rangeToList(begin, end, DateField.MONTH);
            for (DateTime dateTime : dateTimes) {
                String yearMonth = DateUtil.format(dateTime, CommonConstant.DATE_YM);
                PcsElecData pcsElecData = new PcsElecData();
                pcsElecData.setDate(yearMonth);
                BigDecimal charge = BigDecimal.ZERO;
                BigDecimal disCharge = BigDecimal.ZERO;
                //按yyyy-MM分组
                //分别计算充电,放电
                if (monthChargeList.containsKey(yearMonth)) {
                    List<ElecMeterValue> elecMeterValues1 = monthChargeList.get(yearMonth);
                    for (ElecMeterValue elecMeterValue : elecMeterValues1) {
                        charge = charge.add(elecMeterValue.getDigital());
                    }
                    pcsElecData.setChargeElec(charge);
                }
                if (monthDischargeList.containsKey(yearMonth)) {
                    List<ElecMeterValue> elecMeterValues1 = monthDischargeList.get(yearMonth);

                    for (ElecMeterValue elecMeterValue : elecMeterValues1) {
                        disCharge = disCharge.add(elecMeterValue.getDigital());
                    }
                    pcsElecData.setDischargeElec(disCharge);
                }

                list.add(pcsElecData);
            }
        }
        //根据时间排序
        list.stream().sorted((s1, s2) -> {
            return s1.getDate().compareTo(s2.getDate());
        }).collect(Collectors.toList());
        if (!isToday) {
            return list;
        }
        if (CommonConstant.HOUR.equals(type)) {
            BigDecimal chargeTotal = new BigDecimal(0);
            BigDecimal dischargeTotal = new BigDecimal(0);
            for (PcsElecData pcsElecData : list) {
                BigDecimal chargeElecOrig = pcsElecData.getChargeElec() == null ? BigDecimal.ZERO : pcsElecData.getChargeElec();
                BigDecimal dischargeElecOrig = pcsElecData.getDischargeElec() == null ? BigDecimal.ZERO : pcsElecData.getDischargeElec();
                chargeTotal = chargeTotal.add(chargeElecOrig);
                dischargeTotal = dischargeTotal.add(dischargeElecOrig);
            }
            if (req.getEndTime() == null || req.getEndTime().equals(endTime)) {
                if (!list.isEmpty()) {
                    PcsElecData pcsElecData = list.get(list.size() - 1);
                    String dailyChargeElecStr = String.format("%.2f", dailyChargeElec.subtract(chargeTotal));
                    String dailyDischargeElecStr = String.format("%.2f", dailyDischargeElec.subtract(dischargeTotal));
                    dailyChargeElec = new BigDecimal(dailyChargeElecStr);
                    dailyDischargeElec = new BigDecimal(dailyDischargeElecStr);
                    pcsElecData.setChargeElec(dailyChargeElec);
                    pcsElecData.setDischargeElec(dailyDischargeElec);
                }
            }
        } else {
            if (req.getEndTime() == null || req.getEndTime().equals(endTime)) {
                //当天的数据
                if (!list.isEmpty()) {
                    PcsElecData pcsElecData = list.get(list.size() - 1);
                    BigDecimal chargeElecOrig = pcsElecData.getChargeElec() == null ? BigDecimal.ZERO : pcsElecData.getChargeElec();
                    BigDecimal dischargeElecOrig = pcsElecData.getDischargeElec() == null ? BigDecimal.ZERO : pcsElecData.getDischargeElec();
                    dailyChargeElec = chargeElecOrig.add(dailyChargeElec);
                    dailyDischargeElec = dischargeElecOrig.add(dailyDischargeElec);
                    String dailyChargeElecStr = String.format("%.2f", dailyChargeElec);
                    String dailyDischargeElecStr = String.format("%.2f", dailyDischargeElec);
                    dailyChargeElec = new BigDecimal(dailyChargeElecStr);
                    dailyDischargeElec = new BigDecimal(dailyDischargeElecStr);
                    pcsElecData.setChargeElec(dailyChargeElec);
                    pcsElecData.setDischargeElec(dailyDischargeElec);
                }
            }
        }

        return list;
    }
    @Override
    public List<PowerGenerateRespVO> getPvData(PcsStationReq req) {
        // 获取今日光伏收益
        String type = req.getType();
        Date end = new Date();
        String endTime = DateUtil.format(end, CommonConstant.DATE_YMD);
        List<PowerGenerateRespVO> list = new ArrayList<>();
        DateTime begin;
        if (CommonConstant.DAY.equals(type)){
            begin = DateUtil.offsetDay(end, -6);
        }else if(CommonConstant.MONTH.equals(type)){
            begin = DateUtil.offsetDay(end, -29);
        }else{
            return list;
        }
        String beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
        //光伏收益
        List<PowerGenerateRespVO> pvIncome = earningsCalculateMpptService.countPvIncome(req.getStationId(),beginTime, endTime);
        Map<String,List<PowerGenerateRespVO>> mapIncome = pvIncome.stream().collect(Collectors.groupingBy(i ->i.getDate()));
        //光伏放电
        List<Integer> types = new ArrayList<>();
        types.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE);
        List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), types, beginTime, endTime);
        Map<String, List<ElecMeterValue>> mapMeter = elecMeterValues.stream().collect(Collectors.groupingBy(i ->i.getDay()));
        //根据天获取时间段
        List<DateTime> dateTimes = DateUtil.rangeToList(begin, end, DateField.DAY_OF_MONTH);
        for (DateTime dateTime : dateTimes){
            String date = DateUtil.format(dateTime, CommonConstant.DATE_YMD);
            PowerGenerateRespVO  pv = new PowerGenerateRespVO();
            pv.setDate(date);
            List<PowerGenerateRespVO> pvIn = mapIncome.get(date);
            //收益
            if(pvIn != null){
                pv.setProfit(pvIn.get(0).getProfit());
            }
            //放电
            List<ElecMeterValue> elecs = mapMeter.get(date);
            if(elecs != null){
                pv.setPowerGenerate(elecs.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            if(date.equals(endTime)){
                String key = RedisKeyConstant.PV.STATION_PV_TODAY_PROFIT + req.getStationId();
                //获取今日收益
                BigDecimal todayIncone = (BigDecimal)redisService.get(key);
                pv.setProfit(todayIncone);
                //获取今日发电
                //当前功率(光伏)、总发电量、日发电量
                MpptActiveVo todayPv = openStationService.getPvActivePower(req.getStationId());
                pv.setPowerGenerate(todayPv.getDailyReleaseElec());

            }
            list.add(pv);
        }
        return list;
    }
    /**
     * 慈溪电站特殊处理
     *
     * @param req
     * @param elecMeterValues
     * @return
     */
    private List<ElecMeterValue> getMeterValues(PcsStationReq req, List<ElecMeterValue> elecMeterValues) {
        List<DeviceRespVO> deviceList = new ArrayList<>();
        Integer stationId = req.getStationId();
        if (req.getStationId() == 349 && !req.getDeviceType().equals(DeviceTypeConstant.BMS)) {
            deviceList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.BMS);
            if (deviceList.isEmpty()) {
                deviceList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.BMS);
            }
            Map<Integer, DeviceRespVO> srcIdMap = deviceList.stream().collect(Collectors.toMap(DeviceRespVO::getSrcId, DeviceRespVO -> DeviceRespVO));
//            List<ElecMeterValue> bmsEleList = elecMeterValues.stream().filter(i -> srcIdMap.get(i.getSrcId()) != null).collect(Collectors.toList());
            Map<String, List<ElecMeterValue>> otherEleList = elecMeterValues.stream().filter(i -> srcIdMap.get(i.getSrcId()) == null).collect(Collectors.groupingBy(ElecMeterValue::getDay));
            List<ElecMeterValue> elecList = new ArrayList<>();
            for (Map.Entry<String, List<ElecMeterValue>> m : otherEleList.entrySet()) {
                List<ElecMeterValue> value = m.getValue();
                if (!value.isEmpty()) {
                    Map<Integer, List<ElecMeterValue>> typeMap = value.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
                    for (Map.Entry<Integer, List<ElecMeterValue>> k : typeMap.entrySet()) {
                        value = k.getValue();
                        ElecMeterValue ev = new ElecMeterValue();
                        BeanUtils.copyProperties(value.get(value.size() - 1), ev);
                        ev.setDigital(value.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO, BigDecimal::add));
                        elecList.add(ev);
                    }
                }
            }
//            bmsEleList.addAll(elecList);
//            elecMeterValues = bmsEleList;
            elecMeterValues = elecList;
        }
        return elecMeterValues;
    }

    @Override
    public List<PcsElecData> getElecData(PcsStationReq req, String name) throws ParseException {

        //创建返回值
        List<PcsElecData> list = new ArrayList<>();
        //查询冻结值
        List<Integer> typeList = new ArrayList<>();
        //充放电
        typeList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
        typeList.add(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);

        //导出时可根据具体时间段查询
        if (req.getBeginTime() != null && req.getEndTime() != null) {
            DateTime begin = DateUtil.parse(req.getBeginTime());
            DateTime end = DateUtil.parse(req.getEndTime());
            String beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
            String endTimeValue = DateUtil.format(end, CommonConstant.DATE_YMD);
            List<ElecMeterValue> elecMeterValues = elecMeterValueService.selectList(req.getStationId(), typeList, beginTime, endTimeValue);
            elecMeterValues = getMeterValues(req, elecMeterValues);
            List<DateTime> dateTimes = DateUtil.rangeToList(begin, end, DateField.DAY_OF_MONTH);
            String now = DateUtil.format(new Date(), CommonConstant.DATE_YMD);
            if (now.equals(endTimeValue)) {
                //获取日充日放
                CountEleData countEleData = getCountEleData(req);
                //日充电量
                BigDecimal dailyChargeElec = countEleData.getDailyChargeElec();
                //日放电量
                BigDecimal dailyDischargeElec = countEleData.getDailyDischargeElec();
                ElecMeterValue chargeEle = new ElecMeterValue();
                chargeEle.setStationId(req.getStationId());
                chargeEle.setDay(now);
                chargeEle.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
                chargeEle.setDigital(dailyChargeElec);
                elecMeterValues.add(chargeEle);
                ElecMeterValue disChargeEle = new ElecMeterValue();
                disChargeEle.setStationId(req.getStationId());
                disChargeEle.setDay(now);
                disChargeEle.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
                disChargeEle.setDigital(dailyDischargeElec);
                elecMeterValues.add(disChargeEle);
            }
            //根据类型进行分组
            String type = req.getType();
            if (CommonConstant.MONTH.equals(type)) {
                elecMeterValues = getElecMeterValues(req, elecMeterValues);
                begin = DateUtil.beginOfMonth(begin);
                end = DateUtil.beginOfMonth(end);
                List<DateTime> monthTimes = DateUtil.rangeToList(begin, end, DateField.MONTH);
                getDataList(list, monthTimes, elecMeterValues, CommonConstant.SEVEN, CommonConstant.DATE_YM);
            } else if (CommonConstant.YEAR.equals(type)) {
                elecMeterValues = getElecMeterValues(req, elecMeterValues);
                begin = DateUtil.beginOfMonth(begin);
                end = DateUtil.beginOfMonth(end);
                List<DateTime> yearTimes = DateUtil.rangeToList(begin, end, DateField.YEAR);
                getDataList(list, yearTimes, elecMeterValues, CommonConstant.FOUR, CommonConstant.DATE_Y);
            } else {
                //根据天获取时间段
//                Map<Integer, List<ElecMeterValue>> map = elecMeterValues.stream().collect(Collectors.groupingBy(ElecMeterValue::getType));
//                setDataByTime(dateTimes, map, list);
                setDataByTime(dateTimes,elecMeterValues,list);
            }
        }
        Integer stationId = req.getStationId();
        for (PcsElecData pcsElecData : list) {
            pcsElecData.setStationId(stationId);
            pcsElecData.setName(name);
            pcsElecData.setChargeElec(pcsElecData.getChargeElec() == null ? BigDecimal.ZERO : pcsElecData.getChargeElec().setScale(2, BigDecimal.ROUND_HALF_UP));
            pcsElecData.setDischargeElec(pcsElecData.getDischargeElec() == null ? BigDecimal.ZERO : pcsElecData.getDischargeElec().setScale(2, BigDecimal.ROUND_HALF_UP));
            pcsElecData.setIncome(pcsElecData.getIncome() == null ? BigDecimal.ZERO : pcsElecData.getIncome().setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        return list;
    }

    private List<ElecMeterValue> getElecMeterValues(PcsStationReq req, List<ElecMeterValue> elecMeterValues) {
        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(req.getStationId(), req.getDeviceType());
        if (deviceRespVOS.isEmpty()) {
            deviceRespVOS = deviceService.getListByFuzzyDeviceType(req.getStationId(), req.getDeviceType());
        }
        if (!deviceRespVOS.isEmpty()) {
            Map<Integer, Integer> srcIdMap = deviceRespVOS.stream().collect(Collectors.toMap(DeviceRespVO::getSrcId, DeviceRespVO::getSrcId));
            elecMeterValues = elecMeterValues.stream().filter(i -> srcIdMap.get(i.getSrcId()) != null).collect(Collectors.toList());
        }
        return elecMeterValues;
    }

    /**
     * 获取日充放电数据
     *
     * @param list
     * @param monthTimes
     * @param elecMeterValues
     * @param num
     * @param timeType
     */
    private void getDataList(List<PcsElecData> list, List<DateTime> monthTimes, List<ElecMeterValue> elecMeterValues, Integer num, String timeType) {
        Map<String, List<ElecMeterValue>> monthChargeList = elecMeterValues.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE.equals(i.getType())).collect(Collectors.groupingBy(s -> {
            String month = s.getDay().substring(0, num);
            return month;
        }));
        Map<String, List<ElecMeterValue>> monthDischargeList = elecMeterValues.stream().filter(i -> DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE.equals(i.getType())).collect(Collectors.groupingBy(s -> {
            String month = s.getDay().substring(0, num);
            return month;
        }));
        for (DateTime dateTime : monthTimes) {
            String yearMonth = DateUtil.format(dateTime, timeType);
            PcsElecData pcsElecData = new PcsElecData();
            pcsElecData.setDate(yearMonth);
            BigDecimal charge = BigDecimal.ZERO;
            BigDecimal disCharge = BigDecimal.ZERO;
            //按yyyy-MM分组
            //分别计算充电,放电
            if (monthChargeList.containsKey(yearMonth)) {
                List<ElecMeterValue> elecMeterValues1 = monthChargeList.get(yearMonth);
                for (ElecMeterValue elecMeterValue : elecMeterValues1) {
                    charge = charge.add(elecMeterValue.getDigital());
                }
                pcsElecData.setChargeElec(charge);
            }
            if (monthDischargeList.containsKey(yearMonth)) {
                List<ElecMeterValue> elecMeterValues1 = monthDischargeList.get(yearMonth);
                for (ElecMeterValue elecMeterValue : elecMeterValues1) {
                    disCharge = disCharge.add(elecMeterValue.getDigital());
                }
                pcsElecData.setDischargeElec(disCharge);
            }
            list.add(pcsElecData);
        }
    }

    /**
     * 根据时间(按天进行赋值)
     *
     * @param dateTimes 时间段集合(天)
     * @param eleList   数值eleList
     * @param list      返回值集合
     */
    private void setDataByTime(List<DateTime> dateTimes, List<ElecMeterValue> eleList, List<PcsElecData> list) {
        Map<String, List<ElecMeterValue>> map = eleList.stream().collect(Collectors.groupingBy(i -> i.getType() + "_" + i.getDay()));
        for (DateTime dateTime : dateTimes) {
            String date = DateUtil.format(dateTime, CommonConstant.DATE_YMD);
            PcsElecData pcsElecData = new PcsElecData();
            pcsElecData.setDate(date);
            //充电量
            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE + "_" + date);
            if (chargeList != null) {
                pcsElecData.setChargeElec(chargeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //放电
            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE + "_" + date);
            if (dischargeList != null) {
                pcsElecData.setDischargeElec(dischargeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //收益
            List<ElecMeterValue> incomeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.INCOME + "_" + date);
            if (incomeList != null) {
                pcsElecData.setIncome(incomeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //光伏充电
            List<ElecMeterValue> pvList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE + "_" + date);
            if (pvList != null) {
                pcsElecData.setPvChargeElec(pvList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            list.add(pcsElecData);
        }
    }

    /**
     * 根据时间(按天进行赋值)
     *
     * @param dateTimes 时间段集合(天)
     * @param eleList   数值eleList
     * @param list      返回值集合
     */
    private void setHourByTime(List<DateTime> dateTimes, List<ElecMeterValue> eleList, List<PcsElecData> list) {
        Map<String, List<ElecMeterValue>> map = eleList.stream().collect(Collectors.groupingBy(i -> i.getType() + "_" + i.getDay()));
        for (DateTime dateTime : dateTimes) {
            String date = DateUtil.format(dateTime, CommonConstant.DATE_Hms);
            PcsElecData pcsElecData = new PcsElecData();
            pcsElecData.setDate(date);
            //充电量
            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE + "_" + dateTime);
            if (chargeList != null) {
                pcsElecData.setChargeElec(chargeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //放电
            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE + "_" + dateTime);
            if (dischargeList != null) {
                pcsElecData.setDischargeElec(dischargeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            //收益
            List<ElecMeterValue> incomeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.INCOME + "_" + dateTime);
            if (incomeList != null) {
                pcsElecData.setIncome(incomeList.stream().map(ElecMeterValue::getDigital).reduce(BigDecimal.ZERO,BigDecimal::add));
            }
            list.add(pcsElecData);
        }
    }

    /**
     * 根据时间(按天进行赋值)
     *
     * @param dateTimes 时间段集合(天)
     * @param map       数值map
     * @param list      返回值集合
     */
//    private void setDataByTime(List<DateTime> dateTimes, Map<Integer, List<ElecMeterValue>> map, List<PcsElecData> list) {
//        for (DateTime dateTime : dateTimes) {
//            String date = DateUtil.format(dateTime, CommonConstant.DATE_YMD);
//            PcsElecData pcsElecData = new PcsElecData();
//            pcsElecData.setDate(date);
//            //充电量
//            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
//            if (chargeList != null) {
//                for (ElecMeterValue elecMeterValue : chargeList) {
//                    if (date.equals(elecMeterValue.getDay())) {
//                        pcsElecData.setChargeElec(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            //放电
//            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
//            if (dischargeList != null) {
//                for (ElecMeterValue elecMeterValue : dischargeList) {
//                    if (date.equals(elecMeterValue.getDay())) {
//                        pcsElecData.setDischargeElec(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            //收益
//            List<ElecMeterValue> incomeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.INCOME);
//            if (incomeList != null) {
//                for (ElecMeterValue elecMeterValue : incomeList) {
//                    if (date.equals(elecMeterValue.getDay())) {
//                        pcsElecData.setIncome(elecMeterValue.getDigital());
//                    }
//                }
//            }
//
//            //收益
//            List<ElecMeterValue> pvList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE);
//            if (pvList != null) {
//                for (ElecMeterValue elecMeterValue : pvList) {
//                    if (date.equals(elecMeterValue.getDay())) {
//                        pcsElecData.setPvChargeElec(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            list.add(pcsElecData);
//        }
//    }

//    /**
//     * 根据时间(按天进行赋值)
//     *
//     * @param dateTimes 时间段集合(天)
//     * @param map       数值map
//     * @param list      返回值集合
//     */
//    private void setHourByTime(List<DateTime> dateTimes, Map<Integer, List<ElecMeterValue>> map, List<PcsElecData> list) {
//        for (DateTime dateTime : dateTimes) {
//            String date = DateUtil.format(dateTime, CommonConstant.DATE_Hms);
//            PcsElecData pcsElecData = new PcsElecData();
//            pcsElecData.setDate(date);
//            //充电量
//            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE);
//            if (chargeList != null) {
//                for (ElecMeterValue elecMeterValue : chargeList) {
//                    String substring = elecMeterValue.getDay().substring(11, elecMeterValue.getDay().length());
//                    if (date.equals(substring)) {
//                        pcsElecData.setChargeElec(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            //放电
//            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE);
//            if (dischargeList != null) {
//                for (ElecMeterValue elecMeterValue : dischargeList) {
//                    String substring = elecMeterValue.getDay().substring(11, elecMeterValue.getDay().length());
//                    if (date.equals(substring)) {
//                        pcsElecData.setDischargeElec(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            //收益
//            List<ElecMeterValue> incomeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.INCOME);
//            if (incomeList != null) {
//                for (ElecMeterValue elecMeterValue : incomeList) {
//                    String substring = elecMeterValue.getDay().substring(11, elecMeterValue.getDay().length());
//                    if (date.equals(substring)) {
//                        pcsElecData.setIncome(elecMeterValue.getDigital());
//                    }
//                }
//            }
//            list.add(pcsElecData);
//        }
//    }


    /**
     * 根据时间范围(按天进行赋值)
     *
     * @param dateTimes 时间段集合(天)
     * @param map       数值map
     * @param list      返回值集合
     */
    private void setRangeTime(List<DateTime> dateTimes, Map<Integer, List<ElecMeterValue>> map, List<PcsElecData> list) {
        int len = dateTimes.size();
        if (len > 1) {
            int length = len - 1;
            //充电量
            List<ElecMeterValue> chargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE);
            //放电
            List<ElecMeterValue> dischargeList = map.get(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE);
            Map<String, List<ElecMeterValue>> chargeMap = chargeList == null ? new HashMap<>() : chargeList.stream().collect(Collectors.groupingBy(ElecMeterValue::getDay));
            Map<String, List<ElecMeterValue>> disChargeMap = dischargeList == null ? new HashMap<>() : dischargeList.stream().collect(Collectors.groupingBy(ElecMeterValue::getDay));
            String key = "";
            for (int i = 0; i < length; i++) {
                List<DateTime> times = DateUtil.rangeToList(dateTimes.get(i), dateTimes.get(i + 1), DateField.HOUR_OF_DAY);
                String date = DateUtil.format(dateTimes.get(i + 1), CommonConstant.DATE_YMD);
                PcsElecData pcsElecData = new PcsElecData();
                pcsElecData.setDate(date);
                BigDecimal chargeElec = new BigDecimal(CommonConstant.ZERO);
                BigDecimal disChargeElec = new BigDecimal(CommonConstant.ZERO);
                times.remove(times.size() - 1);
                for (DateTime dateTime : times) {
                    key = DateUtil.format(dateTime, CommonConstant.DATE);
                    List<ElecMeterValue> valueList = chargeMap.get(key);
                    if (valueList != null) {
                        chargeElec = chargeElec.add(valueList.get(0).getDigital());
                    }
                    valueList = disChargeMap.get(key);
                    if (valueList != null) {
                        disChargeElec = disChargeElec.add(valueList.get(0).getDigital());
                    }
                }
                pcsElecData.setChargeElec(chargeElec);
                pcsElecData.setDischargeElec(disChargeElec);
                list.add(pcsElecData);
            }
        }
    }

    //根据传入的采样率进行开始结束时间查询
    @Override
    public MonitorQuery getStartEndTime(Integer sampleTime) {
        MonitorQuery monitorQuery = new MonitorQuery();
        Date now = new Date();
        Date endDate = DateUtils.addDays(now, -sampleTime);
        String endTime = DateUtil.formatDateTime(now);
        String beginTime = DateUtil.formatDateTime(endDate);
        monitorQuery.setBeginTime(beginTime);
        monitorQuery.setEndTime(endTime);
        return monitorQuery;
    }

    @Autowired
    CurveConfigMapper curveConfigMapper;

    @Override
    public List<NewRealTimeCurveVo> getDynamicRealtimeCurve(DynamicConfigQuery vo) {
        Integer stationId = vo.getStationId();
        Station station = stationService.selectById(stationId);
        if (station == null) {
            return new ArrayList<>();
        }
        //创建返回值
        List<NewRealTimeCurveVo> voList = new ArrayList<>();
        List<StationHomeRespVo> list = new ArrayList<>();
        String beginTime = vo.getBeginTime();
        String endTime = vo.getEndTime();
        DateTime beginTimeParse = null;
        DateTime endParse = null;
        Integer samlRate = null;
        List<DateTime> dateTimes = new ArrayList<>();
        //开始时间 当天时间（零点）
        if (beginTime == null || endTime == null) {
            //取开始时间结束时间
            Date date = new Date();
            beginTime = DateUtil.format(DateUtil.beginOfDay(date), CommonConstant.DATE);
            beginTimeParse = DateUtil.parse(beginTime, CommonConstant.DATE);
            endTime = DateUtil.format(date, CommonConstant.DATE);
            endParse = DateUtil.parse(endTime, CommonConstant.DATE);
        } else {
            beginTimeParse = DateUtil.parse(beginTime, CommonConstant.DATE);
            endParse = DateUtil.parse(endTime, CommonConstant.DATE);
        }
        Integer sampleTime = vo.getSampleTime();
        if (sampleTime != null) {
            MonitorQuery queryTime = getStartEndTime(sampleTime);
            beginTime = queryTime.getBeginTime();
            endTime = queryTime.getEndTime();
            beginTimeParse = DateUtil.parse(beginTime, CommonConstant.DATE);
            endParse = DateUtil.parse(endTime, CommonConstant.DATE);
            samlRate = sampleTime;
        } else {
            //计算(采样率)出开始时间与结束时间的差 （大于1440 采样率是 时间/60）
            int timeDifference = pointDemoService.getTimeDifference(beginTime, endTime);
            if (timeDifference <= 1441) {
                samlRate = 1;
            } else {
                double divisor = 1441;
                double flag = Math.ceil(timeDifference / divisor);        //向上取整计算
                samlRate = (int) flag;
            }
        }
        //通过size拿到循环的个数
        dateTimes = DateUtil.rangeToList(beginTimeParse, endParse, DateField.MINUTE, samlRate);
        //查询时间
        List<String> hourList = dateTimes.stream().map(s -> {
            return DateUtil.format(s, CommonConstant.DATE);
        }).collect(Collectors.toList());
        for (int i = 0; i < hourList.size(); i++) {
            StationHomeRespVo stationHomeRespVo = new StationHomeRespVo();
            stationHomeRespVo.setDate(hourList.get(i));
            list.add(stationHomeRespVo);
        }
        DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
        deviceTypeQuery.setGroupId(station.getGroupId());
        deviceTypeQuery.setStationId(stationId);
        deviceTypeQuery.setType("1");
        List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
        Map<String, String> typeConfigMap = deviceTypeConfigs.stream().filter(i -> i.getDeviceType() != null && i.getModelName() != null).collect(Collectors.toMap(DeviceTypeConfig::getDeviceType, DeviceTypeConfig::getModelName, (k1, k2) -> k2));
        List<CurveConfigResp> curveConfigResps = curveConfigMapper.selectByParam(vo);
        Map<Integer, List<CurveConfigResp>> curveMap = curveConfigResps.stream().collect(Collectors.groupingBy(CurveConfigResp::getCurveType));
        Map<String, List<CurveConfigResp>> curveNameMap = null;
        for (Map.Entry<Integer, List<CurveConfigResp>> m : curveMap.entrySet()) {
            List<CurveConfigResp> curveConfigList = m.getValue();
            List<NewRealTimeCurveVo> curveList = null;
            switch (m.getKey()) {
                case 1:
                    //辅助线
                    StationHomeRespVo sr = null;
                    for (CurveConfigResp c : curveConfigList) {
                        List<StationHomeRespVo> auxiliaryList = new ArrayList<>();
                        for (StationHomeRespVo s : list) {
                            sr = new StationHomeRespVo();
                            sr.setDate(s.getDate());
                            sr.setDailyUsage(s.getDailyUsage());
                            sr.setDigital(c.getAuxiliaryValue());
                            auxiliaryList.add(sr);
                        }
                        NewRealTimeCurveVo curveVo = new NewRealTimeCurveVo();
                        curveVo.setName(c.getCurveName());
                        curveVo.setDeviceName("");
                        curveVo.setList(auxiliaryList);
                        curveVo.setIsAuxiliary(CommonConstant.ONE);
                        voList.add(curveVo);
                    }
                    break;
                case 2:
                    //合并曲线
                    curveNameMap = curveConfigList.stream().collect(Collectors.groupingBy(CurveConfigResp::getCurveName));
                    for (Map.Entry<String, List<CurveConfigResp>> c : curveNameMap.entrySet()) {
                        curveList = getCurveList(station, beginTime, endTime, samlRate, typeConfigMap, c.getValue());
                        mergeCurve(voList, curveList, "", c.getKey(), CommonConstant.ZERO);
                    }
                    break;
                case 3:
                    //取平均
                    curveNameMap = curveConfigList.stream().collect(Collectors.groupingBy(CurveConfigResp::getCurveName));
                    for (Map.Entry<String, List<CurveConfigResp>> c : curveNameMap.entrySet()) {
                        curveList = getCurveList(station, beginTime, endTime, samlRate, typeConfigMap, c.getValue());
                        mergeCurve(voList, curveList, "", c.getKey(), CommonConstant.ONE);
                    }
                    break;
                default:
                    //普通线
                    curveList = getCurveList(station, beginTime, endTime, samlRate, typeConfigMap, curveConfigList);
                    voList.addAll(curveList);
                    break;
            }
        }
        for (NewRealTimeCurveVo newRealTimeCurveVo : voList) {
            List<StationHomeRespVo> homeRespVoList = newRealTimeCurveVo.getList();
            for (int i = 0; i < list.size(); i++) {
                if (homeRespVoList != null && !CommonConstant.ZERO.equals(homeRespVoList.size())) {
                    homeRespVoList.get(i).setDate(list.get(i).getDate());
                }
            }
        }
        //进行返回
        return voList;
    }

    @Override
    public OutStationData getStationData(StationReq req) {
        OutStationData outStationData = new OutStationData();
        PcsStationData pcsStationData = getPcsStationData(req.getStationId(),req.getLang());
        BeanUtils.copyProperties(pcsStationData, outStationData);
        if (req.getDeviceType() == null) {
            String deviceType = colCountService.getDeviceType(req.getStationId());
            req.setDeviceType(deviceType);
        }
        PcsTotalData data = getPcsTotalData(req);
        BigDecimal systemEfficiency = data.getSystemEfficiency();
        bigDecimalUtil.keepTwoDecimalPlaces(data);
        bigDecimalUtil.ifIsNUll(data);
        //保持精度
        data.setSystemEfficiency(systemEfficiency);
        BeanUtils.copyProperties(data, outStationData);
        return outStationData;
    }

    private List<NewRealTimeCurveVo> getCurveList(Station station, String beginTime, String endTime, Integer samlRate, Map<String, String> typeConfigMap, List<CurveConfigResp> curveConfigList) {
        List<NewRealTimeCurveVo> voList = new ArrayList<>();
        for (CurveConfigResp c : curveConfigList) {
            DeviceColData outputPowerData = new DeviceColData();
            String modelName = typeConfigMap.get(c.getDeviceType());
            if (modelName == null || modelName.isEmpty()) {
                continue;
            }
            Map<Integer, String> map = new HashMap<>();
            map.put(c.getSrcId(), modelName);
            outputPowerData.setMap(map);
            List<PointCurveSrcCol> deviceIdList = new ArrayList<>();
            PointCurveSrcCol p = new PointCurveSrcCol();
            List<String> cols = new ArrayList<>();
            cols.add(c.getCol());
            p.setCols(cols);
            p.setSrcId(c.getSrcId());
            deviceIdList.add(p);
            outputPowerData.setDeviceIdList(deviceIdList);
            List<StationHomeRespVo> pointTableData = getStationHomeRespVos(station, beginTime, endTime, samlRate, outputPowerData);
            NewRealTimeCurveVo vo = new NewRealTimeCurveVo();
            vo.setSrcId(c.getSrcId());
            vo.setName(c.getCurveName());
            if (pointTableData != null) {
                vo.setList(pointTableData);
            } else {
                vo.setList(new ArrayList<>());
            }
            voList.add(vo);
        }
        return voList;
    }


    @Override
    public List<AppRealTimeCurveRespVo> getPowerCurve(MonitorQuery monitorQuery) {
        //返回值
        List<AppRealTimeCurveRespVo> powerCurveList = new ArrayList<>();
        //查询电站
        Station station = stationService.selectById(monitorQuery.getStationId());
        if (station == null) {
            return new ArrayList<>();
        }
        //获取开始结束时间
        MonitorQuery queryTime = getStartEndTime(monitorQuery.getSampleTime());
        //获取返回时间
        //通过size拿到循环的个数
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.parse(queryTime.getBeginTime(), CommonConstant.DATE), DateUtil.parse(queryTime.getEndTime(), CommonConstant.DATE), DateField.MINUTE, monitorQuery.getSampleTime());
        int endHours = dateTimes.size();
        //查询时间
        List<String> hourList = dateTimes.stream().map(s -> {
            return DateUtil.format(s, CommonConstant.DATE);
        }).collect(Collectors.toList());

        for (int i = 0; i < hourList.size(); i++) {
            AppRealTimeCurveRespVo vo = new AppRealTimeCurveRespVo();
            vo.setData(hourList.get(i));
            powerCurveList.add(vo);
        }
        //抽样率拼接
        String samlRate = monitorQuery.getSampleTime() + "m";
        //根据设备pid查询下面的BMS
        List<DeviceRespVO> pcsDeviceList = deviceService.getListByDeviceTypeAndPid(monitorQuery.getStationId(), monitorQuery.getSrcId(), DeviceTypeConstant.PCS);

        DeviceColData outputPowerData = getDeviceColData(pcsDeviceList, "outputPower");

        //直接组查询超级表的入参
        TdBaseTimeQuery tdBaseQuery = new TdBaseTimeQuery();
        tdBaseQuery.setBeginTime(queryTime.getBeginTime());
        tdBaseQuery.setEndTime(queryTime.getEndTime());
        tdBaseQuery.setTime(samlRate);

        tdBaseQuery.setStationId(monitorQuery.getStationId());
        tdBaseQuery.setGroupId(station.getGroupId());
        if (outputPowerData != null || !outputPowerData.getDeviceIdList().isEmpty()) {
            List<PointCurveSrcCol> deviceIdList = outputPowerData.getDeviceIdList();
            if (!deviceIdList.isEmpty()) {
                tdBaseQuery.setSrcId(deviceIdList.get(0).getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }
        }
        tdBaseQuery.setMap(outputPowerData.getMap());
        tdBaseQuery.setDeviceIdList(outputPowerData.getDeviceIdList());
        //数据查询
        DataResult<List<PointData>> pointDataShow = tdFeignClient.getPointData(tdBaseQuery);


        //根据设备pid查询下面的BMS
        List<DeviceRespVO> bmsDeviceList = deviceService.getListByDeviceTypeAndPid(monitorQuery.getStationId(), monitorQuery.getSrcId(), DeviceTypeConstant.BMS);
        DeviceColData socPowerData = getDeviceColData(bmsDeviceList, "soc");

        //直接组查询超级表的入参
        tdBaseQuery.setBeginTime(queryTime.getBeginTime());
        tdBaseQuery.setEndTime(queryTime.getEndTime());
        tdBaseQuery.setTime(samlRate);
        tdBaseQuery.setStationId(monitorQuery.getStationId());
        if (socPowerData != null || !socPowerData.getDeviceIdList().isEmpty()) {
            List<PointCurveSrcCol> deviceIdList = socPowerData.getDeviceIdList();
            if (!deviceIdList.isEmpty()) {
                tdBaseQuery.setSrcId(deviceIdList.get(0).getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }
        }
        tdBaseQuery.setGroupId(station.getGroupId());
        tdBaseQuery.setMap(socPowerData.getMap());
        tdBaseQuery.setDeviceIdList(socPowerData.getDeviceIdList());
        //数据查询(soc)
        DataResult<List<PointData>> pointDataList = tdFeignClient.getPointData(tdBaseQuery);
        //数据组成返回
        if (!pointDataList.isSuccess() || pointDataList.getData() == null && !pointDataShow.isSuccess() || pointDataShow.getData() == null) {
            log.error("feignClient.queryStack ,Error!");
            return powerCurveList;
        }
        for (int i = 0; i < powerCurveList.size(); i++) {
            Double socDigital = new Double("0");
            Double pcsDigital = new Double("0");
            if (!pointDataList.getData().isEmpty()) {
                socDigital = pointDataList.getData().get(i).getDigital();
            }
            if (!pointDataShow.getData().isEmpty()) {
                pcsDigital = pointDataShow.getData().get(i).getDigital();
            }
            if (socDigital == null) {
                powerCurveList.get(i).setInCoreDataCurve(null);
            } else {
                powerCurveList.get(i).setInCoreDataCurve(new BigDecimal(socDigital));
            }
            if (pcsDigital == null) {
                powerCurveList.get(i).setPcsRealTimeCurve(null);
            } else {
                powerCurveList.get(i).setPcsRealTimeCurve(new BigDecimal(pcsDigital));
            }
        }
        return powerCurveList;
    }


    @Override
    public List<AppRealTimeCurveRespVo> getPcsCurve(MonitorQuery monitorQuery) {
        //总有功，总无工
        return getAppRealTimeCurveRespVos(monitorQuery, "outputPower", "reactivePowerPCS");
    }

    private List<AppRealTimeCurveRespVo> getAppRealTimeCurveRespVos(MonitorQuery monitorQuery, String modelCol1, String modelCol2) {
        //创建返回值
        List<AppRealTimeCurveRespVo> pcsCurveCurveList = new ArrayList<>();
        //查询电站
        Station station = stationService.selectById(monitorQuery.getStationId());
        if (station == null) {
            return new ArrayList<>();
        }
        //根据电站id和srcId查询 拿到col的部分数据
        Device device = deviceService.selectByStationIdAndSrcId(monitorQuery.getStationId(), monitorQuery.getSrcId());
        List<DeviceRespVO> list = new ArrayList<>();
        DeviceRespVO deviceRespVO = new DeviceRespVO();
        BeanUtils.copyProperties(device, deviceRespVO);
        list.add(deviceRespVO);
        //查询devicecol数据（总有功（映射字段是outputPower）, 总无功(PCS交流母线总无功功率  YC0034  映射字段是reactivePowerPCS)）
        DeviceColData outputPowerData = getDeviceColData(list, modelCol1);
        DeviceColData reactivePowerData = getDeviceColData(list, modelCol2);
        //查询开始时间结束时间
        MonitorQuery queryTime = getStartEndTime(monitorQuery.getSampleTime());
        //获取返回时间
        //通过size拿到循环的个数
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.parse(queryTime.getBeginTime(), CommonConstant.DATE), DateUtil.parse(queryTime.getEndTime(), CommonConstant.DATE), DateField.MINUTE, monitorQuery.getSampleTime());
        //查询时间
        List<String> hourList = dateTimes.stream().map(s -> {
            return DateUtil.format(s, CommonConstant.DATE);
        }).collect(Collectors.toList());

        for (int i = 0; i < hourList.size(); i++) {
            AppRealTimeCurveRespVo vo = new AppRealTimeCurveRespVo();
            vo.setData(hourList.get(i));
            pcsCurveCurveList.add(vo);

        }
        //抽样率拼接
        String samlRate = monitorQuery.getSampleTime() + "m";

        //直接组查询超级表的入参
        TdBaseTimeQuery tdBaseQuery = new TdBaseTimeQuery();
        tdBaseQuery.setBeginTime(queryTime.getBeginTime());
        tdBaseQuery.setEndTime(queryTime.getEndTime());
        tdBaseQuery.setMap(outputPowerData.getMap());
        tdBaseQuery.setTime(samlRate);
        if (outputPowerData != null || !outputPowerData.getDeviceIdList().isEmpty()) {
            List<PointCurveSrcCol> deviceIdList = outputPowerData.getDeviceIdList();
            if (!deviceIdList.isEmpty()) {
                tdBaseQuery.setSrcId(deviceIdList.get(0).getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }

        }
        tdBaseQuery.setStationId(monitorQuery.getStationId());
        tdBaseQuery.setGroupId(station.getGroupId());
        //数据查询
        DataResult<List<PointData>> pscData = tdFeignClient.getPointData(tdBaseQuery);

        //直接组查询超级表的入参
        tdBaseQuery.setBeginTime(queryTime.getBeginTime());
        tdBaseQuery.setEndTime(queryTime.getEndTime());
        tdBaseQuery.setTime(samlRate);
        tdBaseQuery.setMap(reactivePowerData.getMap());
        if (reactivePowerData != null || !reactivePowerData.getDeviceIdList().isEmpty()) {
            List<PointCurveSrcCol> deviceIdList = reactivePowerData.getDeviceIdList();
            if (!deviceIdList.isEmpty()) {
                tdBaseQuery.setSrcId(deviceIdList.get(0).getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }
        }
        tdBaseQuery.setStationId(monitorQuery.getStationId());
        tdBaseQuery.setGroupId(station.getGroupId());
        //数据查询
        DataResult<List<PointData>> reactiveList = tdFeignClient.getPointData(tdBaseQuery);
        //进行查询数据返回
        //数据组成返回
        if (!reactiveList.isSuccess() || reactiveList.getData() == null && !pscData.isSuccess() || pscData.getData() == null) {
            log.error("feignClient.queryStack ,Error!");
            return pcsCurveCurveList;
        }
        for (int i = 0; i < pcsCurveCurveList.size(); i++) {
            Double socDigital = new Double("0");
            Double pcsDigital = new Double("0");
            if (!reactiveList.getData().isEmpty()) {
                socDigital = reactiveList.getData().get(i).getDigital();
            }
            if (!pscData.getData().isEmpty()) {
                pcsDigital = pscData.getData().get(i).getDigital();
            }
            if (socDigital == null) {
                pcsCurveCurveList.get(i).setInCoreDataCurve(null);
            } else {
                pcsCurveCurveList.get(i).setInCoreDataCurve(new BigDecimal(socDigital));
            }
            if (pcsDigital == null) {
                pcsCurveCurveList.get(i).setPcsRealTimeCurve(null);
            } else {
                pcsCurveCurveList.get(i).setPcsRealTimeCurve(new BigDecimal(pcsDigital));
            }
        }
        return pcsCurveCurveList;
    }
    @Override
    public List<AppRealTimeCurveRespVo> pvCurve(MonitorQuery monitorQuery) {
        //mppt总发电量、有功功率
        List<AppRealTimeCurveRespVo> appRealTimeCurveRespVos = getAppRealTimeCurveRespVos(monitorQuery, "totalRelease", "pvActivePower");
        return appRealTimeCurveRespVos;
    }
    @Override
    public List<AppRealTimeCurveRespVo> getOpticalStorageCurve(MonitorQuery monitorQuery) {
        //逆变有功功率、PV输出功率
        List<AppRealTimeCurveRespVo> appRealTimeCurveRespVos = getAppRealTimeCurveRespVos(monitorQuery, "outputPower", "acActivePower");
        return appRealTimeCurveRespVos;
    }

    //温度湿度的deviceId 是间隔id
    @Override
    public List<TemperatureHumidityResp> getTemperatureHumidityCurve(MonitorQuery monitorQuery) {
        //创建返回对象
        List<TemperatureHumidityResp> temperList = new ArrayList<>();
        //查询电站
        Station station = stationService.selectById(monitorQuery.getStationId());
        if (station == null) {
            return new ArrayList<>();
        }
        //抽样率拼接
        String samlRate = monitorQuery.getSampleTime() + "m";
        //根据电站id和srcId查询 拿到col的部分数据
        //根据设备pid查询下面的温度
        List<DeviceRespVO> list = deviceService.getListByDeviceTypeAndPid(monitorQuery.getStationId(), monitorQuery.getSrcId(), DeviceTypeConstant.TRANSMITTER);

        //获取开始结束时间
        MonitorQuery queryTime = getStartEndTime(monitorQuery.getSampleTime());
        //获取返回时间
        //通过size拿到循环的个数
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.parse(queryTime.getBeginTime(), CommonConstant.DATE), DateUtil.parse(queryTime.getEndTime(), CommonConstant.DATE), DateField.MINUTE, monitorQuery.getSampleTime());

        List<String> hourList = dateTimes.stream().map(s -> {
            return DateUtil.format(s, CommonConstant.DATE);
        }).collect(Collectors.toList());
        //查询devicecol数据（总有功(映射字段是temperature)）


        for (DeviceRespVO deviceRespVO : list) {
            List<TemperatureValue> temperatureValueList = new ArrayList<>();
            for (int i = 0; i < hourList.size(); i++) {
                TemperatureValue temperatureValue = new TemperatureValue();
                temperatureValue.setData(hourList.get(i));
                temperatureValueList.add(temperatureValue);

            }
            List<DeviceRespVO> deviceList = new ArrayList<>();
            deviceList.add(deviceRespVO);
            DeviceColData temperatureData = getDeviceColData(deviceList, "temperature");
            //湿度
            DeviceColData wetData = getDeviceColData(deviceList, "wet");
            //组td查询入参
            //直接组查询超级表的入参
            TdBaseTimeQuery tdBaseQuery = new TdBaseTimeQuery();
            tdBaseQuery.setBeginTime(queryTime.getBeginTime());
            tdBaseQuery.setEndTime(queryTime.getEndTime());
            tdBaseQuery.setTime(samlRate);
            if (temperatureData != null || !temperatureData.getDeviceIdList().isEmpty()) {
                List<PointCurveSrcCol> deviceIdList = temperatureData.getDeviceIdList();
                tdBaseQuery.setSrcId(deviceRespVO.getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }
            tdBaseQuery.setMap(temperatureData.getMap());
            tdBaseQuery.setStationId(monitorQuery.getStationId());
            tdBaseQuery.setGroupId(station.getGroupId());
            //数据查询
            DataResult<List<PointData>> pointData = tdFeignClient.getPointData(tdBaseQuery);
            List<PointData> data = pointData.getData();


            //组td查询入参
            //直接组查询超级表的入参
            tdBaseQuery.setBeginTime(queryTime.getBeginTime());
            tdBaseQuery.setEndTime(queryTime.getEndTime());
            tdBaseQuery.setTime(samlRate);
            if (wetData != null || !wetData.getDeviceIdList().isEmpty()) {
                List<PointCurveSrcCol> deviceIdList = wetData.getDeviceIdList();
                tdBaseQuery.setSrcId(deviceRespVO.getSrcId());
                if (deviceIdList != null || !deviceIdList.isEmpty()) {
                    List<String> cols = deviceIdList.get(0).getCols();
                    if (!cols.isEmpty()) {
                        tdBaseQuery.setCol(cols.get(0));
                    }
                }
            }
            tdBaseQuery.setMap(temperatureData.getMap());
            tdBaseQuery.setStationId(monitorQuery.getStationId());
            tdBaseQuery.setGroupId(station.getGroupId());
            //数据查询
            DataResult<List<PointData>> wetDataList = tdFeignClient.getPointData(tdBaseQuery);
            List<PointData> dataWet = wetDataList.getData();
            //数据组成返回
            if (data != null || dataWet != null) {
                for (int i = 0; i < temperatureValueList.size(); i++) {
                    Double temDigital = new Double("0");
                    Double wetDigital = new Double("0");
                    if (!data.isEmpty()) {
                        temDigital = data.get(i).getDigital();
                    }
                    if (!dataWet.isEmpty()) {
                        wetDigital = dataWet.get(i).getDigital();
                    }
                    if (temDigital == null) {
                        temperatureValueList.get(i).setTemperature(null);
                    } else {
                        temperatureValueList.get(i).setTemperature(new BigDecimal(temDigital));
                    }
                    if (wetDigital == null) {
                        temperatureValueList.get(i).setHumidity(null);
                    } else {
                        temperatureValueList.get(i).setHumidity(new BigDecimal(wetDigital));
                    }
                }
                TemperatureHumidityResp temperatureHumidityResp = new TemperatureHumidityResp();
                temperatureHumidityResp.setList(temperatureValueList);
                temperList.add(temperatureHumidityResp);
            }
        }


        return temperList;
    }

    /**
     * 获取日充日放总充总放
     *
     * @param req
     * @return
     */
    @Override
    public CountEleData getCountEleData(StationReq req) {
        String deviceType = req.getDeviceType() == null ? DeviceTypeConstant.BMS : req.getDeviceType();
        Integer stationId = req.getStationId();
        CountEleData countEleData = new CountEleData();
        //总充电量
        BigDecimal totalChargeElec = BigDecimal.ZERO;
        //总放电量
        BigDecimal totalDischargeElec = BigDecimal.ZERO;

        //日充电量
        BigDecimal dailyChargeElec = BigDecimal.ZERO;
        //日放电量
        BigDecimal dailyDischargeElec = BigDecimal.ZERO;

        //日充电量开始
        BigDecimal dailyChargeStartElec = BigDecimal.ZERO;
        //日放电量开始
        BigDecimal dailyDischargeStartElec = BigDecimal.ZERO;
        int startNum = 0;
        //总充,总放来自于BMS ,日充, 日放也来自于BMS
        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
        if (deviceRespVOS.isEmpty()) {
            deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
        }
        //从缓存中获取累计充电量与放电量
        boolean flag = true;
        boolean hasTotalCharge = false, hasTotalDischarge = false;
        String nowDay = DateUtil.format(new Date(), CommonConstant.DATE_YMD);
        int totalNum = 0;
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //拼接电表缓存key
            String redisKey = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
            //判断电表换是否存在
            if (redisService.hasKey(redisKey)) {
                Map<Object, Object> map = redisService.hgetall(redisKey);
                if (map != null) {
                    //总充, 总放
                    Object objTotalCharge = map.get(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                    if (objTotalCharge instanceof DeviceTransfer) {
                        hasTotalCharge = true;
                        DeviceTransfer totalCharge = (DeviceTransfer) map.get(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                        if (totalCharge != null && totalCharge.getUpdateTime().getTime()>beginOfDay.getTime()) {
                            totalNum++;
                        }
                        totalChargeElec = totalCharge.getValue() != null ? totalChargeElec.add(totalCharge.getValue()) : totalChargeElec;
                    }
                    Object objTotalDischarge = map.get(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                    if (objTotalDischarge instanceof DeviceTransfer) {
                        hasTotalDischarge = true;
                        DeviceTransfer totalDischarge = (DeviceTransfer) map.get(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                        if (totalDischarge != null && totalDischarge.getUpdateTime().getTime()>beginOfDay.getTime()) {
                            totalNum++;
                        }
                        totalDischargeElec = totalDischarge.getValue() != null ? totalDischargeElec.add(totalDischarge.getValue()) : totalDischargeElec;
                    }
                    //日充
                    DeviceTransfer dailyChargeObj = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.dailyCharge);
                    log.info("dailyChargeObj：{},stationId:{}", dailyChargeObj, stationId);
                    if (null != dailyChargeObj) {
                        DeviceTransfer dailyChargeTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.dailyCharge);
                        String format = DateUtil.format(dailyChargeTransfer.getUpdateTime(), CommonConstant.DATE_YMD);
                        if (nowDay.equals(format)) {
                            dailyChargeElec = dailyChargeTransfer.getValue() != null ? dailyChargeElec.add(dailyChargeTransfer.getValue()) : dailyChargeElec;
                        }
                        flag = false;
                    }
                    //日放
                    Object dailyDischargeObj = map.get(DataCollectConstant.PCS_POINT.dailyDischarge);
                    if (dailyDischargeObj instanceof DeviceTransfer) {
                        DeviceTransfer dailyDischargeTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.dailyDischarge);
                        String format = DateUtil.format(dailyDischargeTransfer.getUpdateTime(), CommonConstant.DATE_YMD);
                        if (nowDay.equals(format)) {
                            dailyDischargeElec = dailyDischargeTransfer.getValue() != null ? dailyDischargeElec.add(dailyDischargeTransfer.getValue()) : dailyDischargeElec;
                        }
                    }
                    //日充电量开始
                    DeviceTransfer dailyChargeStart = (DeviceTransfer) map.get(DeviceTypeConstant.DAILY_CHARGE_START);
                    if (dailyChargeStart != null) {
                        Date updateTime = dailyChargeStart.getUpdateTime();
                        if (updateTime.getTime() == beginOfDay.getTime()) {
                            dailyChargeStartElec = dailyChargeStart.getValue() != null ? dailyChargeStartElec.add(dailyChargeStart.getValue()) : dailyChargeStartElec;
                            startNum++;
                        }
                    }
                    //日放电量开始
                    DeviceTransfer dailyDischargeStart = (DeviceTransfer) map.get(DeviceTypeConstant.DAILY_DISCHARGE_START);
                    if (dailyDischargeStart != null) {
                        Date updateTime = dailyDischargeStart.getUpdateTime();
                        if (updateTime.getTime() == beginOfDay.getTime()) {
                            dailyDischargeStartElec = dailyDischargeStart.getValue() != null ? dailyDischargeStartElec.add(dailyDischargeStart.getValue()) : dailyDischargeStartElec;
                            startNum++;
                        }
                    }
                }
            }
        }
        //若查不到，走计算
        if (flag) {
            if (startNum>0 && startNum%CommonConstant.TWO == 0 && totalNum==startNum) {
                dailyChargeElec = hasTotalCharge ? totalChargeElec.subtract(dailyChargeStartElec) : BigDecimal.ZERO;
                dailyDischargeElec = hasTotalDischarge ? totalDischargeElec.subtract(dailyDischargeStartElec) : BigDecimal.ZERO;
                dailyChargeElec = dailyChargeElec.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : dailyChargeElec;
                dailyDischargeElec = dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : dailyDischargeElec;
            } else {
                MonitorQuery monitorQuery = new MonitorQuery();
                monitorQuery.setStationId(stationId);
                monitorQuery.setEndTime(req.getEndTime());
                monitorQuery.setDeviceRespVOS(deviceRespVOS);
                JSONObject info = outApiService.getDayChargeDeal(monitorQuery, deviceType);
                DeviceTransfer dailyChargeTransfer = (DeviceTransfer) info.get(DataCollectConstant.PCS_POINT.dailyCharge);
                dailyChargeElec = dailyChargeTransfer.getValue();
                DeviceTransfer dailyDischargeTransfer = (DeviceTransfer) info.get(DataCollectConstant.PCS_POINT.dailyDischarge);
                dailyDischargeElec = dailyDischargeTransfer.getValue();
            }
        }
        countEleData.setDailyChargeElec(dailyChargeElec);
        countEleData.setDailyDischargeElec(dailyDischargeElec);
        countEleData.setTotalChargeElec(totalChargeElec);
        countEleData.setTotalDischargeElec(totalDischargeElec);
        countEleData.setDeviceList(deviceRespVOS);
        return countEleData;
    }

    /**
     * 获取日光伏
     *
     * @param req
     * @return
     */
    public DeviceTransfer getCountPvData(StationReq req) {
        String deviceType = req.getDeviceType() == null ? DeviceTypeConstant.BMS : req.getDeviceType();
        Integer stationId = req.getStationId();
        //总充,总放来自于BMS ,日充, 日放也来自于BMS
        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
        if (deviceRespVOS.isEmpty()) {
            deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
        }
        //从缓存中获取数据
        DeviceTransfer pvTransfer = new DeviceTransfer();
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //拼接电表缓存key
            String redisKey = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
            //判断电表换是否存在
            if (redisService.hasKey(redisKey)) {
                Map<Object, Object> map = redisService.hgetall(redisKey);
                if (map != null) {
                    //日放
                    Object dailyDischargeObj = map.get(DataCollectConstant.PV_CHARGE_POINT.PV_DAILY_CHARGING_ENERGY);
                    if (dailyDischargeObj instanceof DeviceTransfer) {
                        pvTransfer = (DeviceTransfer) map.get(DataCollectConstant.PV_CHARGE_POINT.PV_DAILY_CHARGING_ENERGY);
                    }
                }
            }
        }
        return pvTransfer;
    }


}
