package com.ho.business.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FileCenterFeignClient;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.feignclient.TdFeignClient;
import com.ho.business.feignclient.UserFeignClient;
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.StationReq;
import com.ho.business.vo.req.carbin.ElecMeterReq;
import com.ho.business.vo.req.chargepile.DataProcessReqVO;
import com.ho.business.vo.req.colCount.ColCountReq;
import com.ho.business.vo.req.device.DeviceTypeQuery;
import com.ho.business.vo.req.xxjob.RefreshHisDataReq;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.colCount.ColCountResp;
import com.ho.business.vo.resp.pcsStation.PcsTotalData;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.EnvConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.PointCurveSrcCol;
import com.ho.common.tools.entity.WeatherRespVo;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
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.flow.vo.Event;
import com.ho.flow.vo.req.AlarmConfig.AlarmConfigQueryVo;
import com.ho.td.api.entity.elecMeter.ElecPowerGeneration;
import com.ho.td.api.entity.query.TdBaseTimeQuery;
import com.ho.user.api.vo.req.SysSubDictVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * @author fancl
 * @desc: 外部请求处理类
 * @date 2023/5/6
 */
@Service
@Slf4j
public class OutApiServiceImpl implements OutApiService {

    @Autowired
    StationService stationService;

    @Autowired
    StationHomeService stationHomeService;

    @Autowired
    private FileCenterFeignClient fileCenterFeignClient;

    @Autowired
    private FlowFeignClient flowFeignClient;

    @Autowired
    private CommonService commonService;

    @Autowired
    StationStatusService stationStatusService;

    @Autowired
    private StationSnService stationSnService;

    @Autowired
    ColCountService colCountService;


    @Autowired
    ElecMeterValueService elecMeterValueService;

    @Autowired
    ModelDeviceService modelDeviceService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    private ModelDeviceColService modelDeviceColService;

    @Autowired
    private ModelTypeColService modelTypeColService;

    @Autowired
    private DeviceTypeColService deviceTypeColService;

    @Autowired
    private DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    RedisService redisService;

    @Autowired
    TdFeignClient tdFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    PcsService pcsService;

    @Autowired
    ForwardColTemplateService forwardColTemplateService;

    @Value("${spring.profiles.active}")
    private String env;


    //加工昨天充放电量
    @Override
    public void dayChargeDeal(MonitorQuery monitorQuery) {
        //根据参数计算 beginTime 这天的起止时间
        SimpleDateFormat sdfDay = new SimpleDateFormat(CommonConstant.DATE_YMD);
        SimpleDateFormat sdfDateTime = new SimpleDateFormat(CommonConstant.DATE);
        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = null;
        if (monitorQuery != null) {
            if (monitorQuery.getBeginTime() != null) {
                transDayStr = monitorQuery.getBeginTime();
                try {
                    transDay = sdfDay.parse(monitorQuery.getBeginTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                DateTime yesterdayTime = DateUtil.yesterday();
                transDayStr = sdfDay.format(yesterdayTime);
                transDay = yesterdayTime;
            }
        } else {
            DateTime yesterdayTime = DateUtil.yesterday();
            transDayStr = sdfDay.format(yesterdayTime);
            transDay = yesterdayTime;
        }
        log.info("dayChargeDeal transDay:" + transDay);
        //昨天的开始时间,昨天的结束时间
        DateTime beginOfDay = DateUtil.beginOfDay(transDay);
        DateTime endOfDay = DateUtil.endOfDay(transDay);
        String beginTime = sdfDateTime.format(beginOfDay);
        String endTime = sdfDateTime.format(endOfDay);
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(beginTime);
        dataProcessReqVO.setEndDayTime(endTime);
        //业务发生日期
        dataProcessReqVO.setDay(transDayStr);
        //查所有集团
        List<Station> stations = new ArrayList<>();
        if (monitorQuery.getStationIds() == null) {
            stations = stationService.selectAll();
        } else {
            for (Integer stationId : monitorQuery.getStationIds()) {
                Station station = stationService.selectById(stationId);
                stations.add(station);
            }
        }
        String deviceType = DeviceTypeConstant.BMS;
        log.info("stations.size:" + stations.size());
        for (Station station : stations) {
            try {
                //先删除站的当日数据
                List<Integer> typeList = Arrays.asList(
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE,
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE,
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CF_CHARGE
                );
                //使用elecMeterValue
                elecMeterValueService.deleteByStationAndDay(station.getId(), transDayStr, typeList);
                //以下方法可以抽取为公共方法
                //215标准柜子
                ColCountReq colCountReq = new ColCountReq();
                colCountReq.setStationId(station.getId());
                colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                //总充
                List<ColCountResp> chargeList = colCountService.selectByParam(colCountReq);
                if (null != chargeList && chargeList.size() > 0) {
                    deviceType = chargeList.get(0).getDeviceType();
                    log.info("dayChargeDeal:stationId:{},deviceType:{}", station.getId(), deviceType);
                }
                List<DeviceRespVO> deviceRespVOS = null;
                //因为联城电站（电站id:349）储能单元也需要展示（日充日放）日冻结值，所以在计算时候，先查bms,再计算外部电表接入
                if (station.getId() == 349) {
                    deviceRespVOS = deviceService.getListByDeviceType(station.getId(), DeviceTypeConstant.BMS);
                    deviceRespVOS.addAll(deviceService.getListByDeviceType(station.getId(), deviceType));
                } else {
                    deviceRespVOS = deviceService.getListByDeviceType(station.getId(), deviceType);
                    if (deviceRespVOS.isEmpty()) {
                        deviceRespVOS = deviceService.getListByFuzzyDeviceType(station.getId(), deviceType);
                    }
                }
                //判断是否存在电表设备
                if (deviceRespVOS.isEmpty()) {
                    continue;
                }
                log.info("deviceRespVOS.size():" + deviceRespVOS.size());
                for (DeviceRespVO deviceRespVO : deviceRespVOS) {
                    //日充电量
                    BigDecimal dailyChargeElec = BigDecimal.ZERO;
                    //日放电量
                    BigDecimal dailyDischargeElec = BigDecimal.ZERO;
                    //创建远程调用的查询参数
                    TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
                    //充电量来自BMS日充,日放
                    List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                    List<ModelDeviceColComp> totalDisChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                    Map<String, String> colNameMap = new HashMap<>();
                    if (!totalChargeList.isEmpty()) {
                        colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, totalChargeList.get(0).getDeviceCol());
                    }
                    if (!totalDisChargeList.isEmpty()) {
                        colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, totalDisChargeList.get(0).getDeviceCol());
                    }
                    tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
                    tdBaseTimeQuery.setColNameMap(colNameMap);
                    tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
                    tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());

                    //当日的零点时间
                    tdBaseTimeQuery.setBegin(beginOfDay);
                    tdBaseTimeQuery.setEnd(endOfDay);
                    //查询模型表
                    DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
                    if (deviceTypeConfig == null) {
                        log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                        continue;
                    }
                    tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
                    //远程调用查询
                    log.info("查设备数据: start :" + new Date());
                    try {
                        Thread.sleep(500);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
                    log.info("dayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
                    if (result.isSuccess()) {
                        ElecPowerGeneration elecPowerGeneration = result.getData();
                        dailyChargeElec = elecPowerGeneration.getTodayChargePowerGeneration() != null ? dailyChargeElec.add(elecPowerGeneration.getTodayChargePowerGeneration()) : dailyChargeElec;
                        dailyDischargeElec = elecPowerGeneration.getTodayDisChargePowerGeneration() != null ? dailyDischargeElec.add(elecPowerGeneration.getTodayDisChargePowerGeneration()) : dailyDischargeElec;
                        if (dailyChargeElec.compareTo(BigDecimal.ZERO) < 0) {
                            dailyChargeElec = new BigDecimal("65536").add(dailyChargeElec);
                        }
                        if (dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0) {
                            dailyDischargeElec = new BigDecimal("65536").add(dailyDischargeElec);
                        }
                    }
                    //按照设备进行入库   //将结果入库
                    //日充电量入库 dailyChargeElec
                    //dailyChargeElec = countOffset(dailyChargeElec, chargeList);
                    //dailyDischargeElec = countOffset(dailyDischargeElec, disChargeList);
                    ElecMeterValue elecMeterValue = new ElecMeterValue();
                    elecMeterValue.setDigital(dailyChargeElec);
                    elecMeterValue.setSrcId(deviceRespVO.getSrcId());
                    //elecMeterValue.setDeptId(station.getDeptId());
                    elecMeterValue.setStationId(station.getId());
                    elecMeterValue.setGroupId(station.getGroupId());
                    elecMeterValue.setDay(dataProcessReqVO.getDay());
                    elecMeterValue.setCreateTime(new Date());
                    elecMeterValue.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
                    elecMeterValue.setStatus(CommonConstant.STATUS_FLAG);
                    elecMeterValueService.insert(elecMeterValue);
                    //日放电量 dailyDischargeElec
                    ElecMeterValue elecMeterValues = new ElecMeterValue();
                    elecMeterValues.setDigital(dailyDischargeElec);
                    elecMeterValues.setSrcId(deviceRespVO.getSrcId());
                    //elecMeterValues.setDeptId(station.getDeptId());
                    elecMeterValues.setStationId(station.getId());
                    elecMeterValues.setGroupId(station.getGroupId());
                    elecMeterValues.setCreateTime(new Date());
                    elecMeterValues.setDay(dataProcessReqVO.getDay());
                    elecMeterValues.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
                    elecMeterValues.setStatus(CommonConstant.STATUS_FLAG);
                    elecMeterValueService.insert(elecMeterValues);
                    log.info("dayChargeDeal elecMeterValueService.insert OK");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 插入柴发冻结数据
     * @param beginOfDay
     * @param endOfDay
     * @param dataProcessReqVO
     * @param station
     * @param deviceRespVOS
     */
    private void cfInsert(DateTime beginOfDay, DateTime endOfDay, DataProcessReqVO dataProcessReqVO, Station station, List<DeviceRespVO> deviceRespVOS) {
        log.info("begin to cf,stationId:{}",station.getId());
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //日充电量
            BigDecimal dailyChargeElec = BigDecimal.ZERO;
            //创建远程调用的查询参数
            TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
            List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
            Map<String, String> colNameMap = new HashMap<>();
            if (!totalChargeList.isEmpty()) {
                colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, totalChargeList.get(0).getDeviceCol());
            }
            tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
            tdBaseTimeQuery.setColNameMap(colNameMap);
            tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
            tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());

            //当日的零点时间
            tdBaseTimeQuery.setBegin(beginOfDay);
            tdBaseTimeQuery.setEnd(endOfDay);
            //查询模型表
            DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
            if (deviceTypeConfig == null) {
                log.info("cf电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                continue;
            }
            tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
            log.info("cf dayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
            if (result.isSuccess()) {
                ElecPowerGeneration elecPowerGeneration = result.getData();
                dailyChargeElec = elecPowerGeneration.getTodayChargePowerGeneration() != null ? dailyChargeElec.add(elecPowerGeneration.getTodayChargePowerGeneration()) : dailyChargeElec;
            }
            //按照设备进行入库   //将结果入库
            ElecMeterValue elecMeterValue = new ElecMeterValue();
            elecMeterValue.setDigital(dailyChargeElec);
            elecMeterValue.setSrcId(deviceRespVO.getSrcId());
            elecMeterValue.setStationId(station.getId());
            elecMeterValue.setGroupId(station.getGroupId());
            elecMeterValue.setDay(dataProcessReqVO.getDay());
            elecMeterValue.setCreateTime(new Date());
            elecMeterValue.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CF_CHARGE);
            elecMeterValue.setStatus(CommonConstant.STATUS_FLAG);
            elecMeterValueService.insert(elecMeterValue);
        }
    }

    //加工天小时充放电量
    @Override
    public void hourChargeDeal(MonitorQuery monitorQuery) throws ParseException {
        //根据参数计算 beginTime 这天的起止时间
        Date date = new Date();
        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;
        Date newHourDate = dfFormat.parse(newHour);

        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = null;
        if (monitorQuery != null) {
            if (monitorQuery.getBeginTime() != null) {
                transDayStr = monitorQuery.getBeginTime();
                transDay = dfFormat.parse(sdfDateHTime.format(transDayStr) + CommonConstant.MINUTES_SECONDS_BEGIN);
            } else {
                transDay = dfFormat.parse(sdfDateHTime.format(new Date()) + CommonConstant.MINUTES_SECONDS_BEGIN);
                ;
            }
        } else {
            transDay = dfFormat.parse(sdfDateHTime.format(new Date()) + CommonConstant.MINUTES_SECONDS_BEGIN);

        }
        log.info("hourChargeDeal transDay:" + transDay);
        //开始时间 （当前时间的的小时-1）
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.setTime(transDay);
        calendar.add(Calendar.HOUR_OF_DAY, -1);
        Date time = calendar.getTime();
        String end = sdfDateHTime.format(time) + CommonConstant.MINUTES_SECONDS_BEGIN;

        //昨天的开始时间,昨天的结束时间
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(end);
        dataProcessReqVO.setEndDayTime(newHour);
        //业务发生日期
        dataProcessReqVO.setDay(end);
        //查所有集团
       /* List<Station> stations = stationService.selectAll();
        List<Integer> groupIds = new ArrayList<>();
        Map<Integer, List<Station>> groupMap = new HashMap<>();
        groupIds = stations.stream().map(s -> {
            return s.getGroupId();
        }).distinct().collect(Collectors.toList());*/
        if (EnvConstant.EXP.equals(env) || EnvConstant.DEV.equals(env)) {
            //只增加集团为1的
            //groupIds = new ArrayList<>();
            //groupIds.add(1);
        }
      /*  groupMap = stations.stream().collect(Collectors.groupingBy(Station::getGroupId));
        log.info("groupMap:" + groupMap);*/
        //todo 目前只有新凤鸣电站有功能需求
//        List<Station> stations = new ArrayList<>();
//        Station s418 = stationService.selectById(418);
//        stations.add(s418);
        List<Integer> ids = new ArrayList<>();
        ids.add(418);//新凤鸣电站
        ids.add(551);//江苏暨阳电力科技发展有限公司（1号柜）
        ids.add(564);//江苏暨阳电力科技发展有限公司（2号柜）
        List<Station> stations = stationService.selectStationsByIds(ids,null);
        String deviceType = DeviceTypeConstant.PCS;
        for (Station station : stations) {
            //先删除站的当日数据
            List<Integer> typeList = Arrays.asList(
                    DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE,
                    DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE
            );
            //使用elecMeterValue
            elecMeterValueService.deleteByStationAndDay(station.getId(), end, typeList);
            //以下方法可以抽取为公共方法
            //215标准柜子
            ColCountReq colCountReq = new ColCountReq();
            colCountReq.setStationId(station.getId());
            colCountReq.setCol(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
            //总充
            List<ColCountResp> chargeList = colCountService.selectByParam(colCountReq);
            if (null != chargeList && chargeList.size() > 0) {
                deviceType = chargeList.get(0).getDeviceType();
                log.info("hourChargeDeal:stationId:{},deviceType:{}", station.getId(), deviceType);
            }
            List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(station.getId(), deviceType);
            //判断是否存在电表设备
            if (deviceRespVOS.isEmpty()) {
                continue;
            }
            for (DeviceRespVO deviceRespVO : deviceRespVOS) {
                //日充电量
                BigDecimal dailyChargeElec = BigDecimal.ZERO;
                //日放电量
                BigDecimal dailyDischargeElec = BigDecimal.ZERO;
                //创建远程调用的查询参数
                TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
                //充电量来自BMS日充,日放
                List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                List<ModelDeviceColComp> totalDisChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                Map<String, String> colNameMap = new HashMap<>();
                if (!totalChargeList.isEmpty()) {
                    colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, totalChargeList.get(0).getDeviceCol());
                }
                if (!totalDisChargeList.isEmpty()) {
                    colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, totalDisChargeList.get(0).getDeviceCol());
                }
                tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
                tdBaseTimeQuery.setColNameMap(colNameMap);
                tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
                tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());

                //当日的零点时间
                tdBaseTimeQuery.setBegin(time);
                tdBaseTimeQuery.setEnd(newHourDate);
                //查询模型表
                DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
                if (deviceTypeConfig == null) {
                    log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                    continue;
                }
                tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
                //远程调用查询
                DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
                log.info("hourChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
                if (result.isSuccess()) {
                    ElecPowerGeneration elecPowerGeneration = result.getData();
                    dailyChargeElec = elecPowerGeneration.getTodayChargePowerGeneration() != null ? dailyChargeElec.add(elecPowerGeneration.getTodayChargePowerGeneration()) : dailyChargeElec;
                    dailyDischargeElec = elecPowerGeneration.getTodayDisChargePowerGeneration() != null ? dailyDischargeElec.add(elecPowerGeneration.getTodayDisChargePowerGeneration()) : dailyDischargeElec;
                    if (dailyChargeElec.compareTo(BigDecimal.ZERO) < 0) {
                        dailyChargeElec = new BigDecimal("65536").add(dailyChargeElec);
                    }
                    if (dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0) {
                        dailyDischargeElec = new BigDecimal("65536").add(dailyDischargeElec);
                    }
                }
                //按照设备进行入库   //将结果入库
                //日充电量入库 dailyChargeElec
                //dailyChargeElec = countOffset(dailyChargeElec, chargeList);
                //dailyDischargeElec = countOffset(dailyDischargeElec, disChargeList);
                ElecMeterValue elecMeterValue = new ElecMeterValue();
                elecMeterValue.setDigital(dailyChargeElec);
                elecMeterValue.setSrcId(deviceRespVO.getSrcId());
                //elecMeterValue.setDeptId(station.getDeptId());
                elecMeterValue.setStationId(station.getId());
                elecMeterValue.setGroupId(station.getGroupId());
                elecMeterValue.setDay(dataProcessReqVO.getDay());
                elecMeterValue.setCreateTime(new Date());
                elecMeterValue.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_CHARGE);
                elecMeterValue.setStatus(CommonConstant.STATUS_FLAG);
                elecMeterValueService.insert(elecMeterValue);
                //日放电量 dailyDischargeElec
                ElecMeterValue elecMeterValues = new ElecMeterValue();
                elecMeterValues.setDigital(dailyDischargeElec);
                elecMeterValues.setSrcId(deviceRespVO.getSrcId());
                //elecMeterValues.setDeptId(station.getDeptId());
                elecMeterValues.setStationId(station.getId());
                elecMeterValues.setGroupId(station.getGroupId());
                elecMeterValues.setCreateTime(new Date());
                elecMeterValues.setDay(dataProcessReqVO.getDay());
                elecMeterValues.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.HOUR_DISCHARGE);
                elecMeterValues.setStatus(CommonConstant.STATUS_FLAG);
                elecMeterValueService.insert(elecMeterValues);
                log.info("hourChargeDeal elecMeterValueService.insert OK");
            }
        }
    }

    //
    @Override
    public void currentMonthYearDeal(MonitorQuery monitorQuery) {
        //查当月充放电量 ,将数据存储到BMS对应字段
        //计算当月(除了当天,因为当天的数据还没生成)
        ElecMeterReq elecMeterReq = new ElecMeterReq();
        //todo 先查349电站
        Integer stationId = 349;
        List<String> deviceTypes = new ArrayList<>();
        //查电站下的BMS
        deviceTypes.add(DeviceTypeConstant.BMS);
        deviceTypes.add(DeviceTypeConstant.BMS + "_" + stationId);
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setDeviceTypeList(deviceTypes);
        deviceReqVO.setNeedFilter(CommonConstant.ONE);
        List<DeviceRespVO> deviceRespVOS = deviceService.getList(deviceReqVO);
        if (deviceRespVOS.isEmpty()) {
            return;
        }
        Date now = new Date();
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //月度发电量,年度发电量
            BigDecimal monthCharge = BigDecimal.ZERO;
            BigDecimal monthDischarge = BigDecimal.ZERO;
            BigDecimal yearCharge = BigDecimal.ZERO;
            BigDecimal yearDischarge = BigDecimal.ZERO;
            //月初时间
            DateTime beginMonthTime = DateUtil.beginOfMonth(now);
            DateTime beginYearTime = DateUtil.beginOfYear(now);
            //昨天截至时间
            DateTime dateTime = DateUtil.offsetDay(now, -1);
            //昨天截至时间
            DateTime yesterdayEndTime = DateUtil.endOfDay(dateTime);
            //先查月度发电量
            ElecPowerGeneration monthPowerGeneration = pcsService.dealPowerBetween(deviceRespVO, beginMonthTime, yesterdayEndTime);
            ElecPowerGeneration yearPowerGeneration = pcsService.dealPowerBetween(deviceRespVO, beginYearTime, yesterdayEndTime);
            if (monthPowerGeneration != null) {
                monthCharge = monthPowerGeneration.getTodayChargePowerGeneration();
                monthDischarge = monthPowerGeneration.getTodayDisChargePowerGeneration();
            }
            if (yearPowerGeneration != null) {
                yearCharge = yearPowerGeneration.getTodayChargePowerGeneration();
                yearDischarge = yearPowerGeneration.getTodayDisChargePowerGeneration();
            }
            //月发电量 ,年发电量
            //将这4个值更新到redis缓存
            Device device = deviceService.selectByStationIdAndSrcId(stationId, deviceRespVO.getSrcId());
            log.info("device:{},", device);
            if (device != null) {
                String key = device.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
                if (redisService.hasKey(key)) {
                    DeviceTransfer deviceTransfer = new DeviceTransfer();
                    deviceTransfer.setValue(monthCharge);
                    deviceTransfer.setUpdateTime(now);
                    redisService.hset(key, RedisKeyConstant.BMS_DEVICE.MONTH_CHARGE, deviceTransfer);
                    deviceTransfer = new DeviceTransfer();
                    deviceTransfer.setValue(monthDischarge);
                    deviceTransfer.setUpdateTime(now);
                    redisService.hset(key, RedisKeyConstant.BMS_DEVICE.MONTH_DISCHARGE, deviceTransfer);
                    deviceTransfer = new DeviceTransfer();
                    deviceTransfer.setValue(yearCharge);
                    deviceTransfer.setUpdateTime(now);
                    redisService.hset(key, RedisKeyConstant.BMS_DEVICE.YEAR_CHARGE, deviceTransfer);
                    deviceTransfer = new DeviceTransfer();
                    deviceTransfer.setValue(yearDischarge);
                    deviceTransfer.setUpdateTime(now);
                    redisService.hset(key, RedisKeyConstant.BMS_DEVICE.YEAR_DISCHARGE, deviceTransfer);
                }
            }
        }


    }

    @Override
    public ElecPowerGeneration getDayPower(DeviceRespVO deviceRespVO, Date begin, Date end) {
        ElecPowerGeneration elecPowerGeneration = new ElecPowerGeneration();
        //创建远程调用的查询参数
        TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
        //充电量来自BMS日充,日放
        List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
        List<ModelDeviceColComp> totalDisChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
        Map<String, String> colNameMap = new HashMap<>();
        if (!totalChargeList.isEmpty()) {
            colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, totalChargeList.get(0).getDeviceCol());
        } else {
            return elecPowerGeneration;
        }
        if (!totalDisChargeList.isEmpty()) {
            colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, totalDisChargeList.get(0).getDeviceCol());
        } else {
            return elecPowerGeneration;
        }
        tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
        tdBaseTimeQuery.setColNameMap(colNameMap);
        tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
        tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());

        //当日的零点时间
        tdBaseTimeQuery.setBegin(begin);
        tdBaseTimeQuery.setEnd(end);
        //远程调用查询
        DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
        if (result.isSuccess() && result.getData() != null) {
            elecPowerGeneration = result.getData();
        }
        return elecPowerGeneration;
    }


    @Override
    public JSONObject getDayChargeDeal(MonitorQuery monitorQuery) {
        return getDayChargeDeal(monitorQuery, DeviceTypeConstant.BMS);
    }

    @Override
    public JSONObject getDayChargeDeal(MonitorQuery monitorQuery, String deviceType) {
        SimpleDateFormat sdfDateTime = new SimpleDateFormat(CommonConstant.DATE);
        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = new Date();
        //昨天的开始时间,昨天的结束时间
        DateTime beginOfDay = DateUtil.beginOfDay(transDay);
        DateTime endOfDay = new DateTime(DateUtils.addDays(beginOfDay,1));
        if (monitorQuery.getEndTime() != null) {
            endOfDay = new DateTime(monitorQuery.getEndTime());
            beginOfDay = new DateTime(DateUtils.addDays(endOfDay, -1));
        }
        String beginTime = sdfDateTime.format(beginOfDay);
        String endTime = sdfDateTime.format(endOfDay);
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(beginTime);
        dataProcessReqVO.setEndDayTime(endTime);
        //业务发生日期
        dataProcessReqVO.setDay(transDayStr);

        Integer stationId = monitorQuery.getStationId();

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

        //以下方法可以抽取为公共方法
        List<DeviceRespVO> deviceRespVOS = monitorQuery.getDeviceRespVOS();
        if(deviceRespVOS == null || deviceRespVOS.isEmpty()){
            deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
            if (deviceRespVOS.isEmpty()) {
                deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
            }
        }
        //判断是否存在电表设备
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //创建远程调用的查询参数
            TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
            //充电量来自BMS日充,日放
            List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
            List<ModelDeviceColComp> totalDisChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
            Map<String, String> colNameMap = new HashMap<>();
            if (!totalChargeList.isEmpty()) {
                colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, totalChargeList.get(0).getDeviceCol());
            }
            if (!totalDisChargeList.isEmpty()) {
                colNameMap.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, totalDisChargeList.get(0).getDeviceCol());
            }
            tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
            tdBaseTimeQuery.setColNameMap(colNameMap);
            tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
            tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());
            tdBaseTimeQuery.setDeviceType(deviceRespVO.getDeviceType());
            //当日的零点时间
            tdBaseTimeQuery.setBegin(beginOfDay);
            tdBaseTimeQuery.setEnd(endOfDay);
            //查询模型表
            DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
            if (deviceTypeConfig == null) {
                log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                continue;
            }
            tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
            //远程调用查询
            DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
            log.info("getDayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
            if (result.isSuccess()) {
                ElecPowerGeneration elecPowerGeneration = result.getData();
                dailyChargeElec = elecPowerGeneration.getTodayChargePowerGeneration() != null ? dailyChargeElec.add(elecPowerGeneration.getTodayChargePowerGeneration()) : dailyChargeElec;
                dailyDischargeElec = elecPowerGeneration.getTodayDisChargePowerGeneration() != null ? dailyDischargeElec.add(elecPowerGeneration.getTodayDisChargePowerGeneration()) : dailyDischargeElec;
                if (dailyChargeElec.compareTo(BigDecimal.ZERO) < 0) {
                    dailyChargeElec = new BigDecimal("65536").add(dailyChargeElec);
                }
                if (dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0) {
                    dailyDischargeElec = new BigDecimal("65536").add(dailyDischargeElec);
                }
            }
        }
        log.info("dailyChargeElec: {},dailyDischargeElec:{}", dailyChargeElec, dailyDischargeElec);
        JSONObject info = new JSONObject();
        Date date = new Date();
        DeviceTransfer deviceTransfer = new DeviceTransfer();
        deviceTransfer.setValue(dailyChargeElec);
        deviceTransfer.setUpdateTime(date);
        info.put(DataCollectConstant.PCS_POINT.dailyCharge, deviceTransfer);
        deviceTransfer = new DeviceTransfer();
        deviceTransfer.setValue(dailyDischargeElec);
        deviceTransfer.setUpdateTime(date);
        info.put(DataCollectConstant.PCS_POINT.dailyDischarge, deviceTransfer);
        return info;
    }

    @Override
    public void dayChargeValue(MonitorQuery monitorQuery, List<Station> stationList) {
        for (Station station : stationList) {
            //查询每个电站的pcs模块温度
            //散热器值
            //时间（昨天开始 -- 昨天结束）
            DateTime yesterday = new DateTime();
            SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATE);
            String begin = sdf.format(DateUtil.beginOfDay(yesterday));
            String endDay = sdf.format(DateUtil.endOfDay(yesterday));
            //根据的deviceType（根据电站查询所有的设备，将每个设备类型等于null和重复的数据进行过滤）
            Map<Integer, String> map = new HashMap<>();
            Device device = new Device();
            device.setStationId(station.getId());
            device.setVirtual(CommonConstant.ZERO);
            device.setCategory(CommonConstant.THREE);
            List<Device> deviceList = deviceService.getRealDevice(device);
            List<Device> collect = deviceList.stream().filter(s -> s.getDeviceType() != null).distinct().collect(Collectors.toList());
            ModelTypeCol modelTypeCol = modelTypeColService.selectByCol("radiatorTemperature");
            TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
            // modelcol查询 一起进行查询 是否存在关联关系
            Double pcsMaxTemperature = new Double(0);
            for (Device device1 : collect) {
                ModelDeviceCol modelDeviceCol = modelDeviceColService.selectByModelId(device1.getDeviceType(), modelTypeCol.getId());
                DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
                DeviceTypeCol deviceTypeCol = new DeviceTypeCol();
                if (null != modelDeviceCol) {
                    //存在则进行字典查询（拿到真正的col）
                    deviceTypeCol = deviceTypeColService.selectById(modelDeviceCol.getDeviceColId());
                    if (null != deviceTypeCol) {
                        deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(modelDeviceCol.getDeviceType(), null);
                        map.put(device1.getSrcId(), deviceTypeConfig.getModelName());
                        tdBaseTimeQuery.setCol(deviceTypeCol.getCol());
                        tdBaseTimeQuery.setSrcId(device1.getSrcId());
                        // 组装数据进行td查询
                        //根据map做判断分别调用不同的mapper查询
                        tdBaseTimeQuery.setBeginTime(begin);
                        tdBaseTimeQuery.setEndTime(endDay);
                        tdBaseTimeQuery.setStationId(station.getId());
                        tdBaseTimeQuery.setGroupId(station.getGroupId());
                        DataResult<PointData> pointDataDataResult = new DataResult<>();
                        PointData pointData = new PointData();
                        if (!map.isEmpty()) {
                            tdBaseTimeQuery.setMap(map);
                            //不存在，则查询下一个
                            pointDataDataResult = tdFeignClient.selectMaxValue(tdBaseTimeQuery);
                            if (pointDataDataResult.isSuccess() || pointDataDataResult.getData() != null) {
                                pointData = pointDataDataResult.getData();
                                //数据进行比大小
                                //1.使用BigDecimal
                                BigDecimal bdL = new BigDecimal(pcsMaxTemperature);
                                BigDecimal bdR = new BigDecimal(pointData.getDigital());
                                if (bdL.compareTo(bdR) <= 0) {
                                    pcsMaxTemperature = pointData.getDigital();
                                }
                            }
                        }
                    }
                } else {
                    continue;
                }
            }

            //天气的最大值/最小值
            BigDecimal maxTemperature = new BigDecimal(0);
            BigDecimal minTemperature = new BigDecimal(0);
            StationReq stationReq = new StationReq();
            stationReq.setStationId(station.getId());
            String key = RedisKeyConstant.WEATHER_PROVINCE_CITY + station.getAdCode();
            WeatherRespVo info = (WeatherRespVo) redisService.get(key);
            if (null != info) {
                maxTemperature = info.getMaxTemperature();
                minTemperature = info.getMinTemperature();
            }


            //查询总充总放的设备类型

            StationReq req = new StationReq();
            String deviceType = colCountService.getDeviceType(station.getId());
            if (null == deviceType) {
                deviceType = DeviceTypeConstant.PCS;
            }
            req.setDeviceType(deviceType);
            req.setStationId(station.getId());
            PcsTotalData data = stationHomeService.getPcsTotalData(req);
            //将结果存入缓存
            String redisKey = "maintenance:" + station.getId();
            JSONObject modifyDataObject = new JSONObject();
            //日充
            modifyDataObject.put(DataCollectConstant.PCS_POINT.dailyCharge, data.getDailyChargeElec());
            //日放
            modifyDataObject.put(DataCollectConstant.PCS_POINT.dailyDischarge, data.getDailyDischargeElec());
            if (station.getId() == 418) {
                //总充
                modifyDataObject.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, data.getTotalChargeElec());
                //总放
                modifyDataObject.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, data.getTotalDischargeElec());
            } else {
                //总充
                modifyDataObject.put(DataCollectConstant.Elec_Meter.TOTAL_CHARGE, data.getTotalChargeElec().divide(new BigDecimal(1000)));
                //总放
                modifyDataObject.put(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE, data.getTotalDischargeElec().divide(new BigDecimal(1000)));
            }
            //pcs模块温度
            modifyDataObject.put("pcsMaxTemperature", pcsMaxTemperature);
            //天气的最大值/
            modifyDataObject.put("maxTemperature", maxTemperature);
            //最小值
            modifyDataObject.put("minTemperature", minTemperature);
            String format = DateFormatUtils.format(new Date(), CommonConstant.DATE);
            modifyDataObject.put("updateTime", format);
            redisService.hmset(redisKey, modifyDataObject);
            log.info("elecMeterValueService.insert OK");
        }
    }


    @Override
    public void getJobStationState(List<Station> stationList) {
        for (Station station : stationList) {
            StationStatus stationStatus = new StationStatus();
            // 在线 1
            // 故障停机 2
            // 离线 3
            // 失联 4
            //先查询每个电站的SN编号
            List<StationSn> stationSns = stationSnService.selectByStationId(station.getId());
            for (StationSn stationSn : stationSns) {
                //true 没有心跳 （离线 --> 判断时长是否大于七天，大于则是失联，小于则是离线）
                //false 有心跳  (在线 --> 查询是否存在故障，存在则是故障停机，不存在则是在线)
                Boolean bySnIsOnline = fileCenterFeignClient.getBySnIsOnline(stationSn.getSn());
                if (bySnIsOnline == true) {
                    //取电站最后的一条告警数据 的时间 对其进行对比 看是否大于七天
                    AlarmConfigQueryVo stationStatusReq = new AlarmConfigQueryVo();
                    stationStatusReq.setStationId(station.getId());
                    DataResult<Event> notRecovered = flowFeignClient.getNotRecovered(stationStatusReq);
                    if (notRecovered.isSuccess() || notRecovered.getData() != null) {
                        Event data = notRecovered.getData();
                        Date timeStamp = data.getTimeStamp();
                        Date date = new Date();
                        int days = (int) ((date.getTime() - timeStamp.getTime()) / (1000 * 3600 * 24));
                        if (7 <= days) {
                            //则是失联
                            stationStatus.setStationStatus(CommonConstant.AlarmStatus.Loss);
                        } else {
                            //则是离线
                            stationStatus.setStationStatus(CommonConstant.AlarmStatus.offline);
                        }
                        stationStatus.setStationId(station.getId());
                        SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATE);
                        stationStatus.setTime(sdf.format(new Date()));
                        int i = stationStatusService.insertSelective(stationStatus);
                        log.info("stationStatusService:insertSelective" + i);
                    } else {
                        stationStatus.setStationStatus(CommonConstant.AlarmStatus.Loss);
                        stationStatus.setStationId(station.getId());
                        SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATE);
                        stationStatus.setTime(sdf.format(new Date()));
                        int i = stationStatusService.insertSelective(stationStatus);
                        log.info("stationStatusService:insertSelective" + i);
                    }
                } else {
                    Device device = new Device();
                    device.setStationId(station.getId());
                    device.setVirtual(CommonConstant.ZERO);
                    device.setCategory(CommonConstant.THREE);
                    List<Device> deviceList = deviceService.getRealDevice(device);
                    List<Device> collect = deviceList.stream().filter(s -> s.getDeviceType() != null).distinct().collect(Collectors.toList());
                    ModelTypeCol modelTypeCol = modelTypeColService.selectByCol("deviceStateFault");
                    for (Device device1 : collect) {
                        ModelDeviceCol modelDeviceCol = modelDeviceColService.selectByModelId(device1.getDeviceType(), modelTypeCol.getId());
                        DeviceTypeCol deviceTypeCol = new DeviceTypeCol();
                        if (null != modelDeviceCol) {
                            //存在则进行字典查询（拿到真正的col）
                            deviceTypeCol = deviceTypeColService.selectById(modelDeviceCol.getDeviceColId());
                            if (null != deviceTypeCol) {
                                device.setSrcId(device1.getSrcId());
                                device.setDeviceType(device1.getDeviceType());
                            }
                        }
                    }
                    device.setStationId(station.getId());
                    List<String> cols = new ArrayList<>();
                    cols.add("deviceStateFault");
                    cn.hutool.json.JSONObject realInfo = commonService.getRealInfo(device, cols);
                    cn.hutool.json.JSONObject deviceTransfer = (cn.hutool.json.JSONObject) realInfo.get("deviceStateFault");
                    if (null != deviceTransfer) {
                        String string1 = deviceTransfer.get("value").toString();
                        Integer value = NumberUtil.parseInt(string1);
                        //1:故障
                        if (CommonConstant.ONE.equals(value)) {
                            stationStatus.setStationStatus(CommonConstant.AlarmStatus.faultShutdown);
                        }
                        //0:未发生故障
                        else if (CommonConstant.ZERO.equals(value)) {
                            stationStatus.setStationStatus(CommonConstant.AlarmStatus.onLine);
                        }
                    } else {
                        stationStatus.setStationStatus(CommonConstant.AlarmStatus.onLine);
                    }

                    stationStatus.setStationId(station.getId());
                    SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATE);
                    stationStatus.setTime(sdf.format(new Date()));
                    int i = stationStatusService.insertSelective(stationStatus);
                    log.info("stationStatusService:insertSelective" + i);
                }
            }
        }
    }


    @Override
    public void day(MonitorQuery monitorQuery, List<Station> stationList) {

        List<Integer> ids = stationList.stream().map(Station::getId)
                .collect(Collectors.toList());
        //查询sn
        List<StationSn> stationSns = stationSnService.selectByStationIds(ids);
//        Map<Integer, StationSn> otherLevelMap = stationSns.stream().collect(Collectors.toMap(StationSn::getStationId, StationSn -> StationSn));
        Map<Integer, List<StationSn>> otherLevelMap = stationSns.stream().collect(Collectors.groupingBy(StationSn::getStationId));
        for (Station station : stationList) {
            ElecMeterReq elecMeterReq = new ElecMeterReq();
            elecMeterReq.setStationId(station.getId());
            elecMeterReq.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.CHARGE);
            String string = DateUtil.yesterday().toString();
            elecMeterReq.setBeginTime(string.substring(0, 10));
            elecMeterReq.setEndTime(string.substring(0, 10));
            //充电量
            BigDecimal dailyCharge = new BigDecimal(0);
            BigDecimal dailyDischarge = new BigDecimal(0);
            List<ElecMeterValue> chargeList = elecMeterValueService.selectListByStationAndSrcId(elecMeterReq);
            for (ElecMeterValue elecMeterValue : chargeList) {
                if (elecMeterValue.getStationId().equals(349)) {
                    dailyCharge = elecMeterValue.getDigital();
                } else {
                    dailyCharge = dailyCharge.add(elecMeterValue.getDigital());
                }
            }
            elecMeterReq.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.DISCHARGE);
            List<ElecMeterValue> dischargeList = elecMeterValueService.selectListByStationAndSrcId(elecMeterReq);
            for (ElecMeterValue elecMeterValue : dischargeList) {
                if (elecMeterValue.getStationId().equals(349)) {
                    dailyDischarge = elecMeterValue.getDigital();
                } else {
                    dailyDischarge = dailyDischarge.add(elecMeterValue.getDigital());
                }
            }
            if (station.getId() == 418) {
                dailyCharge = dailyCharge.multiply(new BigDecimal(1000));
                dailyDischarge = dailyDischarge.multiply(new BigDecimal(1000));
            }
            //
            BigDecimal divide = new BigDecimal(0.0);
            if (CommonConstant.ZERO != new BigDecimal(0.0).compareTo(dailyCharge)) {
                divide = dailyDischarge.divide(dailyCharge, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            }


            //redisService.hasKey()

            Device device = new Device();
            device.setStationId(station.getId());
            device.setVirtual(CommonConstant.ZERO);
            device.setCategory(CommonConstant.THREE);
            List<Device> deviceList = deviceService.getRealDevice(device);
            List<Device> collect = deviceList.stream().filter(s -> s.getDeviceType() != null).distinct().collect(Collectors.toList());
            ModelTypeCol modelTypeCol = modelTypeColService.selectByCol("deviceStateFault");
            for (Device device1 : collect) {
                ModelDeviceCol modelDeviceCol = modelDeviceColService.selectByModelId(device1.getDeviceType(), modelTypeCol.getId());
                DeviceTypeCol deviceTypeCol = new DeviceTypeCol();
                if (null != modelDeviceCol) {
                    //存在则进行字典查询（拿到真正的col）
                    deviceTypeCol = deviceTypeColService.selectById(modelDeviceCol.getDeviceColId());
                    if (null != deviceTypeCol) {
                        device.setSrcId(device1.getSrcId());
                        device.setDeviceType(device1.getDeviceType());
                    }
                }
            }
            List<DeviceRespVO> pcsList = deviceService.getListByDeviceType(station.getId(), "pcs");

            //将结果存入缓存
            String redisKey = "dmaintenance:" + station.getId();
            JSONObject modifyDataObject = new JSONObject();
//            StationSn stationSn = otherLevelMap.get(station.getId());
            List<StationSn> stationSn = otherLevelMap.get(station.getId());
            if (stationSn != null) {
                if(stationSn.size()==1){
                    modifyDataObject.put(CommonConstant.sn, stationSn.get(0).getSn());
                }else{
                    List<String> stringStream = stationSn.stream().map(StationSn::getSn).collect(Collectors.toList());
                    modifyDataObject.put(CommonConstant.SN_LIST, stringStream);
                }
            }
            String pcsDeviceType = "";
            String pcsSrcId = "";
            for (DeviceRespVO deviceRespVO : pcsList) {
                pcsDeviceType += deviceRespVO.getDeviceType() + ",";
                pcsSrcId += deviceRespVO.getSrcId() + ",";
            }

            modifyDataObject.put(CommonConstant.pcsDeviceType, pcsDeviceType == "" ? "" : pcsDeviceType.substring(0, pcsDeviceType.length() - 1));
            modifyDataObject.put(CommonConstant.pcsSrcId, pcsSrcId == "" ? "" : pcsSrcId.substring(0, pcsSrcId.length() - 1));
            //日充
            modifyDataObject.put(CommonConstant.deviceType, device.getDeviceType());
            modifyDataObject.put(CommonConstant.srcId, device.getSrcId());
            //日放
            modifyDataObject.put(DataCollectConstant.PCS_POINT.dailyDischarge, dailyDischarge);
            //日充
            modifyDataObject.put(DataCollectConstant.PCS_POINT.dailyCharge, dailyCharge);

            // "pcs交流侧转换效率%")
            modifyDataObject.put(CommonConstant.pcsConversion, divide);

            String format = DateFormatUtils.format(new Date(), CommonConstant.DATE);
            modifyDataObject.put("updateTime", format);
            redisService.hmset(redisKey, modifyDataObject);
            log.info("day elecMeterValueService.insert OK");
        }
    }

    @Override
    public BigDecimal getDayChargeDeal(MonitorQuery monitorQuery, Integer srcId, String col, String colAlias) {
        SimpleDateFormat sdfDateTime = new SimpleDateFormat(CommonConstant.DATE);
        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = new Date();
        //昨天的开始时间,昨天的结束时间
        DateTime beginOfDay = DateUtil.beginOfDay(transDay);
        DateTime endOfDay = DateUtil.endOfDay(transDay);
        if (monitorQuery.getEndTime() != null) {
            endOfDay = new DateTime(monitorQuery.getEndTime());
            beginOfDay = new DateTime(DateUtils.addDays(endOfDay, -1));
        }
        String beginTime = sdfDateTime.format(beginOfDay);
        String endTime = sdfDateTime.format(endOfDay);
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(beginTime);
        dataProcessReqVO.setEndDayTime(endTime);
        //业务发生日期
        dataProcessReqVO.setDay(transDayStr);

        Integer stationId = monitorQuery.getStationId();

        //日充电量
        BigDecimal dailyChargeElec = BigDecimal.ZERO;
        BigDecimal dailyDischargeElec = BigDecimal.ZERO;
        //以下方法可以抽取为公共方法
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setSrcId(srcId);
        List<DeviceRespVO> deviceRespVOS = deviceService.getList(deviceReqVO);
        //判断是否存在电表设备
        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
            //创建远程调用的查询参数
            TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
            Map<String, String> colNameMap = new HashMap<>();
            colNameMap.put(colAlias, col);
            tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
            tdBaseTimeQuery.setColNameMap(colNameMap);
            tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
            tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());
            tdBaseTimeQuery.setDeviceType(deviceRespVO.getDeviceType());
            //当日的零点时间
            tdBaseTimeQuery.setBegin(beginOfDay);
            tdBaseTimeQuery.setEnd(endOfDay);
            //查询模型表
            DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
            if (deviceTypeConfig == null) {
                log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                continue;
            }
            tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
            //远程调用查询
            DataResult<ElecPowerGeneration> result = tdFeignClient.getTodayPowerGeneration(tdBaseTimeQuery);
            log.info("getDayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
            if (result.isSuccess()) {
                ElecPowerGeneration elecPowerGeneration = result.getData();
                dailyChargeElec = elecPowerGeneration.getTodayChargePowerGeneration() != null ? dailyChargeElec.add(elecPowerGeneration.getTodayChargePowerGeneration()) : dailyChargeElec;
                dailyDischargeElec = elecPowerGeneration.getTodayDisChargePowerGeneration() != null ? dailyDischargeElec.add(elecPowerGeneration.getTodayDisChargePowerGeneration()) : dailyDischargeElec;
                if (dailyChargeElec.compareTo(BigDecimal.ZERO) < 0) {
                    dailyChargeElec = new BigDecimal("65536").add(dailyChargeElec);
                }
                if (dailyDischargeElec.compareTo(BigDecimal.ZERO) < 0) {
                    dailyDischargeElec = new BigDecimal("65536").add(dailyDischargeElec);
                }
            }
        }
        log.info("dailyChargeElec: {}", dailyChargeElec);
        if (colAlias.equals(DataCollectConstant.Elec_Meter.TOTAL_CHARGE)) {
            return dailyChargeElec;
        } else if (colAlias.equals(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE)) {
            return dailyDischargeElec;
        }
        return BigDecimal.ZERO;
    }

    @Override
    public void getSystemEfficiency() {
        ColCountReq vo = new ColCountReq();
        vo.setCol(DeviceTypeConstant.TOTAL_SOC);
        List<ColCountResp> colCountResps = colCountService.selectByParam(vo);
        String totalKey = null;
        if (null != colCountResps && colCountResps.size() > 0) {
            List<Integer> stationIds = colCountResps.stream().map(ColCountResp::getStationId).collect(Collectors.toList());
            vo.setCol(DeviceTypeConstant.TOTAL_CHARGE);
            vo.setIds(stationIds);
            List<ColCountResp> chargeList = colCountService.selectByParam(vo);
            Map<Integer, String> stationIdDeviceTypeMap = chargeList.stream().collect(Collectors.toMap(ColCountResp::getStationId, ColCountResp::getDeviceType, (k1, k2) -> k2));
            BigDecimal systemEfficiency = BigDecimal.ZERO;
            for (ColCountResp colCountResp:colCountResps) {
                boolean flag = false;
                Integer stationId = colCountResp.getStationId();
                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 != null && identifyNum.compareTo(setVal)>0){
                        flag = true;
                    }
                }
                if(flag){
                    String deviceType = stationIdDeviceTypeMap.get(stationId);
                    if(deviceType != null){
                        DeviceReqVO deviceReqVO = new DeviceReqVO();
                        deviceReqVO.setStationId(stationId);
                        deviceReqVO.setFuzzyDeviceType(deviceType);
                        //总充,总放来自于BMS ,日充, 日放也来自于BMS
                        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
                        if (deviceRespVOS.isEmpty()) {
                            deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
                        }
                        //总充电量
                        BigDecimal totalChargeElec = BigDecimal.ZERO;
                        //总放电量
                        BigDecimal totalDischargeElec = BigDecimal.ZERO;
                        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) {
                                        DeviceTransfer totalCharge = (DeviceTransfer) map.get(DataCollectConstant.Elec_Meter.TOTAL_CHARGE);
                                        totalChargeElec = totalCharge.getValue() != null ? totalChargeElec.add(totalCharge.getValue()) : totalChargeElec;
                                    }
                                    Object objTotalDischarge = map.get(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                                    if (objTotalDischarge instanceof DeviceTransfer) {
                                        DeviceTransfer totalDischarge = (DeviceTransfer) map.get(DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE);
                                        totalDischargeElec = totalDischarge.getValue() != null ? totalDischargeElec.add(totalDischarge.getValue()) : totalDischargeElec;
                                    }
                                }
                            }
                        }
                        if (BigDecimal.ZERO.compareTo(totalChargeElec) != 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);
                            }
                        }
                    }
                }
            }

        }
    }

    @Override
    public void dayPVMpptCharge(MonitorQuery monitorQuery){
        //根据参数计算 beginTime 这天的起止时间
        SimpleDateFormat sdfDay = new SimpleDateFormat(CommonConstant.DATE_YMD);
        SimpleDateFormat sdfDateTime = new SimpleDateFormat(CommonConstant.DATE);
        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = null;
        if (monitorQuery != null) {
            if (monitorQuery.getBeginTime() != null) {
                transDayStr = monitorQuery.getBeginTime();
                try {
                    transDay = sdfDay.parse(monitorQuery.getBeginTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                DateTime yesterdayTime = DateUtil.yesterday();
                transDayStr = sdfDay.format(yesterdayTime);
                transDay = yesterdayTime;
            }
        } else {
            DateTime yesterdayTime = DateUtil.yesterday();
            transDayStr = sdfDay.format(yesterdayTime);
            transDay = yesterdayTime;
        }
        log.info("dayChargeDeal transDay:" + transDay);
        //昨天的开始时间,昨天的结束时间
        DateTime beginOfDay = DateUtil.beginOfDay(transDay);
        DateTime endOfDay = DateUtil.endOfDay(transDay);
        String beginTime = sdfDateTime.format(beginOfDay);
        String endTime = sdfDateTime.format(endOfDay);
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(beginTime);
        dataProcessReqVO.setEndDayTime(endTime);
        //业务发生日期
        dataProcessReqVO.setDay(transDayStr);
        List<Station> stations = stationService.selectAll();
        stations = stations.stream().filter(i->CommonConstant.ONE.equals(i.getInverterFlag())).collect(Collectors.toList());
        for (Station station :stations){
            //先删除站的当日数据
            List<Integer> typeList = Arrays.asList(
                    DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE
            );
            //使用elecMeterValue
            elecMeterValueService.deleteByStationAndDay(station.getId(), transDayStr, typeList);
            //光伏总发电量
            List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(station.getId(), DeviceTypeConstant.MPPT);
            if (deviceRespVOS.isEmpty()) {
                deviceRespVOS = deviceService.getListByFuzzyDeviceType(station.getId(), DeviceTypeConstant.MPPT);
            }
            //判断是否存在电表设备
            if (deviceRespVOS.isEmpty()) {
                continue;
            }
            log.info("deviceRespVOS.size():" + deviceRespVOS.size());
            for (DeviceRespVO deviceRespVO : deviceRespVOS) {
                //创建远程调用的查询参数
                TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
                //由于mppt没有日发总电量，走计算  昨日最晚总发-昨日做早总发=昨日总发
                List<ModelDeviceColComp> totalRelease = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.PV_CHARGE_POINT.TOTAL_RELEASE);
                Map<Integer, String> colNameMap = new HashMap<>();
                if (!totalRelease.isEmpty()) {
                    colNameMap.put(deviceRespVO.getSrcId(), totalRelease.get(0).getDeviceCol());
                }
                tdBaseTimeQuery.setBeginTime(beginTime);
                tdBaseTimeQuery.setEndTime(endTime);
                tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
                tdBaseTimeQuery.setMap(colNameMap);
                tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
                tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());
                tdBaseTimeQuery.setDeviceType(deviceRespVO.getDeviceType());

                //当日的零点时间
                tdBaseTimeQuery.setBegin(beginOfDay);
                tdBaseTimeQuery.setEnd(endOfDay);
                //查询模型表
                DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
                if (deviceTypeConfig == null) {
                    log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                    continue;
                }
                tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
                //远程调用查询
                log.info("查设备数据: start :" + new Date());
                DataResult<StationHomeRespVo> result = tdFeignClient.getToDayPVMpptCharge(tdBaseTimeQuery);
                log.info("dayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
                StationHomeRespVo data = result.getData();
                ElecMeterValue elecMeterValue = new ElecMeterValue();
                elecMeterValue.setDigital(data.getDigital());
                elecMeterValue.setSrcId(deviceRespVO.getSrcId());
                elecMeterValue.setDeptId(station.getDeptId());
                elecMeterValue.setStationId(station.getId());
                elecMeterValue.setGroupId(station.getGroupId());
                elecMeterValue.setDay(dataProcessReqVO.getDay());
                elecMeterValue.setCreateTime(new Date());
                elecMeterValue.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE);
                elecMeterValue.setStatus(CommonConstant.STATUS_FLAG);
                elecMeterValueService.insert(elecMeterValue);
                log.info("dayChargeDeal elecMeterValueService.insert OK");
            }
        }
    }
    //加工昨天光伏充放电量
    @Override
    public void dayPVCharge(MonitorQuery monitorQuery) {
        //根据参数计算 beginTime 这天的起止时间
        SimpleDateFormat sdfDay = new SimpleDateFormat(CommonConstant.DATE_YMD);
        SimpleDateFormat sdfDateTime = new SimpleDateFormat(CommonConstant.DATE);
        //转成Date格式
        String transDayStr = null;
        //时间格式的交易日期
        Date transDay = null;
        if (monitorQuery != null) {
            if (monitorQuery.getBeginTime() != null) {
                transDayStr = monitorQuery.getBeginTime();
                try {
                    transDay = sdfDay.parse(monitorQuery.getBeginTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                DateTime yesterdayTime = DateUtil.yesterday();
                transDayStr = sdfDay.format(yesterdayTime);
                transDay = yesterdayTime;
            }
        } else {
            DateTime yesterdayTime = DateUtil.yesterday();
            transDayStr = sdfDay.format(yesterdayTime);
            transDay = yesterdayTime;
        }
        log.info("dayChargeDeal transDay:" + transDay);
        //昨天的开始时间,昨天的结束时间
        DateTime beginOfDay = DateUtil.beginOfDay(transDay);
        DateTime endOfDay = DateUtil.endOfDay(transDay);
        String beginTime = sdfDateTime.format(beginOfDay);
        String endTime = sdfDateTime.format(endOfDay);
        DataProcessReqVO dataProcessReqVO = new DataProcessReqVO();
        dataProcessReqVO.setStartDayTime(beginTime);
        dataProcessReqVO.setEndDayTime(endTime);
        //业务发生日期
        dataProcessReqVO.setDay(transDayStr);
        //查所有集团
        List<Station> stations = new ArrayList<>();
/*        if (monitorQuery.getStationIds() == null) {
            stations = stationService.selectAll();
        } else {
            for (Integer stationId : monitorQuery.getStationIds()) {
                Station station = stationService.selectById(stationId);
                stations.add(station);
            }
        }*/

        List<Integer> groupIds = new ArrayList<>();
        Map<Integer, List<Station>> groupMap = new HashMap<>();
        groupIds = stations.stream().map(s -> {
            return s.getGroupId();
        }).distinct().collect(Collectors.toList());
        if (EnvConstant.EXP.equals(env) || EnvConstant.DEV.equals(env)) {
            //只增加集团为1的
            //groupIds = new ArrayList<>();
            //groupIds.add(1);
        }
        //groupMap = stations.stream().collect(Collectors.groupingBy(Station::getGroupId));
        log.info("dayChargeDeal groupMap:" + groupMap);
        //todo 先用349来跑
        Station s349 = stationService.selectById(422);
        stations.add(s349);
        String deviceType = DeviceTypeConstant.PLANCURVE;
        log.info("stations.size:" + stations.size());
        for (Station station : stations) {
            try {
                //先删除站的当日数据
                List<Integer> typeList = Arrays.asList(
                        DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE
                );
                //使用elecMeterValue
                elecMeterValueService.deleteByStationAndDay(station.getId(), transDayStr, typeList);
                //以下方法可以抽取为公共方法
                //215标准柜子
                ColCountReq colCountReq = new ColCountReq();
                colCountReq.setStationId(station.getId());
                colCountReq.setCol(DataCollectConstant.PV_CHARGE_POINT.PV_DAILY_CHARGING_ENERGY);
                //总充
                List<ColCountResp> chargeList = colCountService.selectByParam(colCountReq);
                if (null != chargeList && chargeList.size() > 0) {
                    deviceType = chargeList.get(0).getDeviceType();
                    log.info("dayChargeDeal:stationId:{},deviceType:{}", station.getId(), deviceType);
                }
                List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(station.getId(), deviceType);
                if (deviceRespVOS.isEmpty()) {
                    deviceRespVOS = deviceService.getListByFuzzyDeviceType(station.getId(), deviceType);
                }
                //判断是否存在电表设备
                if (deviceRespVOS.isEmpty()) {
                    continue;
                }
                log.info("deviceRespVOS.size():" + deviceRespVOS.size());
                for (DeviceRespVO deviceRespVO : deviceRespVOS) {
                    //创建远程调用的查询参数
                    TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
                    //充电量来自BMS日充,日放
                    List<ModelDeviceColComp> totalChargeList = modelDeviceService.getCompListByType("device", deviceRespVO.getDeviceType(), DataCollectConstant.PV_CHARGE_POINT.PV_DAILY_CHARGING_ENERGY);
                    Map<Integer, String> colNameMap = new HashMap<>();
                    if (!totalChargeList.isEmpty()) {
                        colNameMap.put(deviceRespVO.getSrcId(), totalChargeList.get(0).getDeviceCol());
                    }

                    tdBaseTimeQuery.setBeginTime(beginTime);
                    tdBaseTimeQuery.setEndTime(endTime);
                    tdBaseTimeQuery.setSrcId(deviceRespVO.getSrcId());
                    tdBaseTimeQuery.setMap(colNameMap);
                    tdBaseTimeQuery.setGroupId(deviceRespVO.getGroupId());
                    tdBaseTimeQuery.setStationId(deviceRespVO.getStationId());

                    //当日的零点时间
                    tdBaseTimeQuery.setBegin(beginOfDay);
                    tdBaseTimeQuery.setEnd(endOfDay);
                    //查询模型表
                    DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(deviceRespVO.getDeviceType(), deviceRespVO.getGroupId());
                    if (deviceTypeConfig == null) {
                        log.info("电站{}未匹配到模型{}", deviceRespVO.getStationId(), deviceRespVO.getDeviceType());
                        continue;
                    }
                    tdBaseTimeQuery.setModelName(deviceTypeConfig.getModelName());
                    //远程调用查询
                    log.info("查设备数据: start :" + new Date());
                    try {
                        Thread.sleep(500);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }

                    DataResult<StationHomeRespVo> result = tdFeignClient.getToDayPVCharge(tdBaseTimeQuery);
                    log.info("dayChargeDeal tdFeignClient.getTodayPowerGeneration, result: {}", result);
                    StationHomeRespVo data = result.getData();
                    //按照设备进行入库   //将结果入库
                    //日充电量入库 dailyChargeElec
                    //dailyChargeElec = countOffset(dailyChargeElec, chargeList);
                    //dailyDischargeElec = countOffset(dailyDischargeElec, disChargeList);
                    ElecMeterValue elecMeterValue = new ElecMeterValue();
                    elecMeterValue.setDigital(data.getDigital());
                    elecMeterValue.setSrcId(deviceRespVO.getSrcId());
                    //elecMeterValue.setDeptId(station.getDeptId());
                    elecMeterValue.setStationId(station.getId());
                    elecMeterValue.setGroupId(station.getGroupId());
                    elecMeterValue.setDay(dataProcessReqVO.getDay());
                    elecMeterValue.setCreateTime(new Date());
                    elecMeterValue.setType(DeviceTypeConstant.ELEC_METER_VALUE_TYPE.PV_CHARGE);
                    elecMeterValue.setStatus(CommonConstant.STATUS_FLAG);
                    elecMeterValueService.insert(elecMeterValue);
                    log.info("dayChargeDeal elecMeterValueService.insert OK");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public String getTempId(Integer stationId) {
        SysSubDictVO sysSubDictVO = new SysSubDictVO();
        sysSubDictVO.setType(CommonConstant.FORWARD_DATA);
        sysSubDictVO.setKeyVal(CommonConstant.ONE);
        Map<String, String> sysSubDict = userFeignClient.getSysSubDict(sysSubDictVO);
        String tempId = sysSubDict.get(String.valueOf(stationId));
        return tempId;
    }

    @Override
    public Map<Object, Object> getForwardPushData(Integer stationId,Integer tempId) {
        Map<Object, Object> resultMap = new HashMap<>();
        //查询测点对应的设备所属的设备id
        Device device = new Device();
        device.setStationId(stationId);
        device.setVirtual(CommonConstant.ZERO);
        device.setCategory(CommonConstant.THREE);
        List<Device> realDevice = deviceService.getRealDevice(device);
        if(!realDevice.isEmpty()){
            List<String> typeList = realDevice.stream().filter(s -> s.getDeviceType() != null).map(Device::getDeviceType).collect(Collectors.toList());
            //查询模板下该电站的实际点
            List<DeviceTypeCol> forwardCol = forwardColTemplateService.getForwardCol(typeList, tempId);
            Map<String, List<DeviceTypeCol>> typeColMap = forwardCol.stream().collect(Collectors.groupingBy(DeviceTypeCol::getDeviceType));
            //根据设备信息，去缓存中拿数据，按照特定要求组装成格式返回
            List<JSONObject> list = new ArrayList<>();
            for (Device d:realDevice) {
                String deviceType = d.getDeviceType();
                if(deviceType == null){
                    continue;
                }
                List<DeviceTypeCol> deviceTypeCols = typeColMap.get(deviceType);
                if(deviceTypeCols!= null && deviceTypeCols.size()>0){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",d.getSrcId());
                    String redisKey = deviceType + ":" + d.getStationId() + ":" + d.getSrcId();
                    if (!redisService.hasKey(redisKey)) {
                        continue;
                    }
                    Map<Object, Object> hgetall = redisService.hgetall(redisKey);
                    JSONObject dataSet = new JSONObject();
                    for (DeviceTypeCol t:deviceTypeCols) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer)hgetall.get(t.getCol());
                        if(deviceTransfer==null){
                            continue;
                        }
                        dataSet.put(t.getCol(),deviceTransfer.getValue());
                    }
                    jsonObject.put("dataSet",dataSet);
                    list.add(jsonObject);
                }
            }
            resultMap.put("freezeTime",DateUtil.format(new Date(),CommonConstant.MQTT_DATE));
            JSONObject object = new JSONObject();
            object.put("list",list);
            resultMap.put("device",object);
        }
        return resultMap;
    }

}
