package com.ho.business.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.feignclient.TdFeignClient;
import com.ho.business.mapper.ElecTemplateSubMapper;
import com.ho.business.service.*;
import com.ho.business.util.ExcelUtil;
import com.ho.business.vo.DeviceTransfer;
import com.ho.business.vo.req.DeviceReqVO;
import com.ho.business.vo.req.StationReq;
import com.ho.business.vo.req.colCount.ColCountReq;
import com.ho.business.vo.req.pcsStation.PcsStationReq;
import com.ho.business.vo.resp.DeviceColData;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.VirtualDeviceColResp;
import com.ho.business.vo.resp.cabin.CircleCtrlResp;
import com.ho.business.vo.resp.colCount.ColCountResp;
import com.ho.business.vo.resp.mppt.MpptActiveVo;
import com.ho.business.vo.resp.mppt.MpptVo;
import com.ho.business.vo.resp.openStationHome.OpenStationMiddleOrig;
import com.ho.business.vo.resp.pcsStation.*;
import com.ho.business.vo.resp.station.ActiveReactivePower;
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.PageResult;
import com.ho.common.tools.util.PageUtils;
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.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fancl
 * @desc:
 * @date 2023/4/27
 */
@Service
@Slf4j
public class OpenStationServiceImpl implements OpenStationService {

    private final static Logger logger = LoggerFactory.getLogger(OpenStationServiceImpl.class);

    @Autowired
    DeviceService deviceService;

    @Autowired
    RedisService redisService;

    @Autowired
    CommonService commonService;

    @Autowired
    private StationService stationService;

    @Autowired
    StationHomeService stationHomeService;

    @Autowired
    TdFeignClient tdFeignClient;

    @Autowired
    private ElecTemplateSubMapper elecMapper;

    @Autowired
    VirtualDeviceColService virtualDeviceColService;

    @Autowired
    ColCountService colCountService;

    @Autowired
    EarningsCalculateService earningsCalculateService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    //获取总有功,总无功
    @Override
    public List<ActiveReactivePower> getAcPowers(Integer stationId) {
        List<ActiveReactivePower> acList = new ArrayList<>();

        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> pcsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.PCS);
        if (!pcsList.isEmpty()) {
            //总有功, 总无功
            BigDecimal activePowerPCS = BigDecimal.ZERO;
            BigDecimal reactivePowerPCS = BigDecimal.ZERO;
            for (DeviceRespVO deviceRespVO : pcsList) {
                String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
                if (redisService.hasKey(key)) {
                    Map<Object, Object> pcsMap = redisService.hgetall(key);
                    if (pcsMap != null) {
                        OpenStationMiddleOrig middleOrig = JSON.parseObject(JSON.toJSONString(pcsMap), OpenStationMiddleOrig.class);
                        if (middleOrig != null) {
                            BigDecimal activePowerPCS1 = middleOrig.getOutputPower() == null ? BigDecimal.ZERO : middleOrig.getOutputPower().getValue();
                            BigDecimal reactivePowerPCS1 = middleOrig.getReactivePowerPCS() == null ? BigDecimal.ZERO : middleOrig.getReactivePowerPCS().getValue();
                            ActiveReactivePower activeReactivePower = new ActiveReactivePower();
                            activeReactivePower.setActivePowerPCS(activePowerPCS1);
                            activeReactivePower.setReactivePowerPCS(reactivePowerPCS1);
                            acList.add(activeReactivePower);
                            //activePowerPCS = activePowerPCS.add(activePowerPCS1);
                            //reactivePowerPCS = reactivePowerPCS.add(reactivePowerPCS1);
                        }
                    }
                }
            }
            //activeReactivePower.setActivePowerPCS(activePowerPCS);
            //activeReactivePower.setReactivePowerPCS(reactivePowerPCS);
        }
        return acList;
    }
    public MpptActiveVo getPvActivePower(Integer stationId){
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> pcsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.MPPT);
        if(pcsList.isEmpty()){
            pcsList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.MPPT);
        }
        MpptActiveVo mpptActiveVo =new MpptActiveVo();
        BigDecimal pvActivePower = new BigDecimal(CommonConstant.ZERO);
        BigDecimal totalRelease = new BigDecimal(CommonConstant.ZERO);
        BigDecimal dailyReleaseElec = new BigDecimal(CommonConstant.ZERO);
        if (!pcsList.isEmpty()) {
            for (DeviceRespVO deviceRespVO : pcsList) {
                //在缓存里拿映射字段
                String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
                if (redisService.hasKey(key)) {
                    Map<Object, Object> mpptMap = redisService.hgetall(key);
                    if (mpptMap != null) {
                        MpptVo vo = JSON.parseObject(JSON.toJSONString(mpptMap), MpptVo.class);
                        if (vo != null) {
                            BigDecimal pvActivePowerMppt = vo.getPvActivePower() == null ? BigDecimal.ZERO : vo.getPvActivePower().getValue();
                            BigDecimal totalReleaseMppt = vo.getTotalRelease() == null ? BigDecimal.ZERO : vo.getTotalRelease().getValue();
                            BigDecimal pvDailyReleaseStart = vo.getPvDailyReleaseStart() == null ? BigDecimal.ZERO : vo.getPvDailyReleaseStart().getValue();
                            BigDecimal dailyReleaseElecMppt = totalReleaseMppt.subtract(pvDailyReleaseStart);
                            dailyReleaseElecMppt = dailyReleaseElecMppt.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:dailyReleaseElecMppt;
                            pvActivePower = pvActivePower.add(pvActivePowerMppt);
                            totalRelease = totalRelease.add(totalReleaseMppt);
                            dailyReleaseElec = dailyReleaseElec.add(dailyReleaseElecMppt);
                        }
                    }
                }
            }
        }
        mpptActiveVo.setPvActivePower(pvActivePower);
        mpptActiveVo.setTotalRelease(totalRelease);
        mpptActiveVo.setDailyReleaseElec(dailyReleaseElec);
        return mpptActiveVo;
    }

    @Override
    public ActiveReactivePower getAcPower(Integer stationId) {
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        ActiveReactivePower activeReactivePower = new ActiveReactivePower();
        List<DeviceRespVO> pcsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.PCS);
        if(pcsList.isEmpty()){
            pcsList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.PCS);
        }
        if (!pcsList.isEmpty()) {
            //总有功, 总无功
            BigDecimal activePowerPCS = BigDecimal.ZERO;
            BigDecimal reactivePowerPCS = BigDecimal.ZERO;
            Map<String, Device> map = new HashMap<>();
            Map<Integer, String> keyMap = new HashMap<>();
            boolean flag = false;
            for (DeviceRespVO deviceRespVO : pcsList) {
                String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
                if (redisService.hasKey(key)) {
                    Map<Object, Object> pcsMap = redisService.hgetall(key);
                    if (pcsMap != null) {
                        OpenStationMiddleOrig middleOrig = JSON.parseObject(JSON.toJSONString(pcsMap), OpenStationMiddleOrig.class);
                        if (middleOrig != null) {
                            BigDecimal activePowerPCS1 = middleOrig.getOutputPower() == null ? BigDecimal.ZERO : middleOrig.getOutputPower().getValue();
                            BigDecimal reactivePowerPCS1 = middleOrig.getReactivePowerPCS() == null ? BigDecimal.ZERO : middleOrig.getReactivePowerPCS().getValue();
                            activeReactivePower.setActivePowerPCS(activePowerPCS1);
                            activeReactivePower.setReactivePowerPCS(reactivePowerPCS1);
                            activePowerPCS = activePowerPCS.add(activePowerPCS1);
                            reactivePowerPCS = reactivePowerPCS.add(reactivePowerPCS1);
                        }
                    }
                }else {
                    //若是虚拟设备
                    if(CommonConstant.ONE.equals(deviceRespVO.getVirtual())){
                        flag = true;
                        Device device = map.get(stationId + CommonConstant.JOIN + deviceRespVO.getFromId());
                        if(device == null){
                            device = deviceService.selectByStationIdAndSrcId(stationId,deviceRespVO.getFromId());
                            map.put(stationId + CommonConstant.JOIN + deviceRespVO.getFromId(),device);
                        }
                        key = device.getDeviceType() + ":" + stationId + ":" + device.getSrcId();
                        keyMap.put(deviceRespVO.getSrcId(),key);
                    }
                }
            }
            //若是虚拟设备则叠加
            if(flag){
                VirtualDeviceCol vo = new VirtualDeviceCol();
                vo.setStationId(stationId);
                List<String> typeList = new ArrayList<>();
                typeList.add(DeviceTypeConstant.JING_KE_TYPE.ACTIVE_POWER_PCS);
                vo.setTypeList(typeList);
                List<VirtualDeviceColResp> list = virtualDeviceColService.getList(vo);
                Map<String, String> colMap = list.stream().collect(Collectors.toMap(s -> s.getSrcId() + CommonConstant.JOIN + s.getType(), s -> s.getCol(), (k1, k2) -> k2));
                for (DeviceRespVO d : pcsList) {
                    DeviceTransfer deviceTransfer = (DeviceTransfer) redisService.hget(keyMap.get(d.getSrcId()), colMap.get(d.getSrcId()+CommonConstant.JOIN+DeviceTypeConstant.JING_KE_TYPE.ACTIVE_POWER_PCS));
                    activePowerPCS = activePowerPCS.add(deviceTransfer==null? BigDecimal.ZERO:deviceTransfer.getValue());
                }
            }
            activeReactivePower.setActivePowerPCS(activePowerPCS);
            activeReactivePower.setReactivePowerPCS(reactivePowerPCS);
        }
        return activeReactivePower;
    }

    @Override
    public List<CircleCtrlResp> getCircle(List<DeviceRespVO> deviceList) {
        List<CircleCtrlResp> list = new ArrayList<>();
        if (deviceList.size() != 4) {
            return list;
        }
        //前两个是1号仓
        DeviceRespVO device0 = deviceList.get(0);
        DeviceRespVO device1 = deviceList.get(1);
        DeviceRespVO device2 = deviceList.get(2);
        DeviceRespVO device3 = deviceList.get(3);
        Map<Object, Object> redis0 = commonService.getInfoFromRedis(device0);
        Map<Object, Object> redis1 = commonService.getInfoFromRedis(device1);
        Map<Object, Object> redis2 = commonService.getInfoFromRedis(device2);
        Map<Object, Object> redis3 = commonService.getInfoFromRedis(device3);
        CircleCtrlResp circle1 = new CircleCtrlResp();
        CircleCtrlResp circle2 = new CircleCtrlResp();
        DeviceTransfer temperature = null;
        DeviceTransfer wet = null;
        BigDecimal temperatureValue = null;
        BigDecimal wetValue = null;
        //设备0的缓存
        temperature = (DeviceTransfer) redis0.get("temperature");
        wet = (DeviceTransfer) redis0.get("wet");
        if (temperature != null) {
            temperatureValue = temperature.getValue();
        }
        if (wet != null) {
            wetValue = wet.getValue();
        }
        if (device0 != null && device0.getDeviceName() != null && device0.getDeviceName().contains("左")) {
            circle1.setCabinetHumidityLeft(wetValue);
            circle1.setCabinetTemperatureLeft(temperatureValue);
        } else if (device0 != null && device0.getDeviceName() != null && device0.getDeviceName().contains("右")) {
            circle1.setCabinetHumidityRight(wetValue);
            circle1.setCabinetTemperatureRight(temperatureValue);
        }
        //缓存1
        temperature = (DeviceTransfer) redis1.get("temperature");
        wet = (DeviceTransfer) redis1.get("wet");
        if (temperature != null) {
            temperatureValue = temperature.getValue();
        }
        if (wet != null) {
            wetValue = wet.getValue();
        }
        //设备1
        if (device1 != null && device1.getDeviceName() != null && device1.getDeviceName().contains("左")) {
            circle1.setCabinetHumidityLeft(wetValue);
            circle1.setCabinetTemperatureLeft(temperatureValue);
        } else if (device1 != null && device1.getDeviceName() != null && device1.getDeviceName().contains("右")) {
            circle1.setCabinetHumidityRight(wetValue);
            circle1.setCabinetTemperatureRight(temperatureValue);
        }
        //缓存2
        temperature = (DeviceTransfer) redis2.get("temperature");
        wet = (DeviceTransfer) redis2.get("wet");
        if (temperature != null) {
            temperatureValue = temperature.getValue();
        }
        if (wet != null) {
            wetValue = wet.getValue();
        }
        //设备2
        if (device2 != null && device2.getDeviceName() != null && device2.getDeviceName().contains("左")) {
            circle2.setCabinetHumidityLeft(wetValue);
            circle2.setCabinetTemperatureLeft(temperatureValue);
        } else if (device2 != null && device2.getDeviceName() != null && device2.getDeviceName().contains("右")) {
            circle2.setCabinetHumidityRight(wetValue);
            circle2.setCabinetTemperatureRight(temperatureValue);
        }
        //缓存3
        temperature = (DeviceTransfer) redis3.get("temperature");
        wet = (DeviceTransfer) redis3.get("wet");
        if (temperature != null) {
            temperatureValue = temperature.getValue();
        }
        if (wet != null) {
            wetValue = wet.getValue();
        }
        //设备3
        if (device3 != null && device3.getDeviceName() != null && device3.getDeviceName().contains("左")) {
            circle2.setCabinetHumidityLeft(wetValue);
            circle2.setCabinetTemperatureLeft(temperatureValue);
        } else if (device3 != null && device3.getDeviceName() != null && device3.getDeviceName().contains("右")) {
            circle2.setCabinetHumidityRight(wetValue);
            circle2.setCabinetTemperatureRight(temperatureValue);
        }
        list.add(circle1);
        list.add(circle2);
        return list;
    }

    @Override
    public String getPcsState(Map<Object, Object> redisInfo ) {
        //查6个状态
        DeviceTransfer deviceStateStand = (DeviceTransfer) redisInfo.get("deviceStateStand");//PCS系统待机状态
        DeviceTransfer deviceStateFault =  (DeviceTransfer) redisInfo.get("deviceStateFault");//PCS系统故障状态
        DeviceTransfer deviceStateFull =  (DeviceTransfer) redisInfo.get("deviceStateFull");//PCS系统充满状态
        DeviceTransfer deviceStateEmpty =  (DeviceTransfer) redisInfo.get("deviceStateEmpty");//PCS系统放空状态
        DeviceTransfer stateCharging =  (DeviceTransfer) redisInfo.get("stateCharging");//PCS系统充电状态
        DeviceTransfer stateDischarging =  (DeviceTransfer) redisInfo.get("stateDischarging");//PCS系统放电状态
        if(deviceStateStand != null && BigDecimal.ONE.compareTo(deviceStateStand.getValue()) ==0){
            return "deviceStateStand";
        }else if(deviceStateFault != null && BigDecimal.ONE.compareTo(deviceStateFault.getValue()) ==0){
            return "deviceStateFault";
        }else if(deviceStateFull != null && BigDecimal.ONE.compareTo(deviceStateFull.getValue()) ==0){
            return "deviceStateFull";
        }else if(deviceStateEmpty != null && BigDecimal.ONE.compareTo(deviceStateEmpty.getValue()) ==0){
            return "deviceStateEmpty";
        }else if(stateCharging != null && BigDecimal.ONE.compareTo(stateCharging.getValue()) ==0){
            return "stateCharging";
        }else if(stateDischarging != null && BigDecimal.ONE.compareTo(stateDischarging.getValue()) ==0){
            return "stateDischarging";
        }
        //以上6中状态没有取到的情况下，默认给停机状态
        return "deviceStop";
    }

    @Override
    public int jobDataManage() {
        // 每半个小时跑一次，如果在每天凌晨的12点-1点之间就跑前一天的数据
        DateTime beginTime = null;
        DateTime endTime = null;
        DateTime date = DateUtil.date();
        DateTime beginOfDay = DateUtil.beginOfDay(date);
        if ( DateUtil.isIn(date,beginOfDay,DateUtil.offsetHour(beginOfDay,1)) ) {
            beginTime = DateUtil.beginOfDay(DateUtil.yesterday());
            endTime = DateUtil.beginOfDay(date);
        } else {
            beginTime = beginOfDay;
            endTime = date;
        }
        logger.info("定时任务获取到的开始时间：{}", beginTime);
        logger.info("定时任务获取到的结束时间：{}", endTime);
        /**
         * 测试用
         * DateTime beginTime = DateUtil.beginOfDay(DateUtil.parse("2023-05-13 00:00:00"));
         * DateTime endTime = DateUtil.endOfDay(DateUtil.parse("2023-05-13 23:59:59"));
         */
        List<Station> stations = stationService.selectAll();
        for (Station station : stations) {
            List<DeviceRespVO> bmsDeviceList = deviceService.getListByDeviceTypeAndPid(station.getId(), null, DeviceTypeConstant.BMS);
            if(bmsDeviceList.isEmpty()){
                continue;
            }
            DeviceColData dailyCharge = stationHomeService.getDeviceColData(bmsDeviceList, "dailyCharge");
            DeviceColData dailyDischarge = stationHomeService.getDeviceColData(bmsDeviceList, "dailyDischarge");
            //直接组查询超级表的入参
            TdBaseTimeQuery tdBaseQuery = null;
            if ( null != dailyCharge && null != dailyCharge.getMap() && dailyCharge.getMap().size() > 0 ) {
                tdBaseQuery = new TdBaseTimeQuery();
                tdBaseQuery.setBeginTime(beginTime.toMsStr());
                tdBaseQuery.setEndTime(endTime.toMsStr());
                tdBaseQuery.setTime("1m");
                tdBaseQuery.setStationId(station.getId());
                tdBaseQuery.setGroupId(station.getGroupId());
                tdBaseQuery.setMap(dailyCharge.getMap());
                if (dailyCharge != null || !dailyCharge.getDeviceIdList().isEmpty()) {
                    List<PointCurveSrcCol> deviceIdList = dailyCharge.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.setDeviceIdList(dailyCharge.getDeviceIdList());
                //数据TD查询(soc)
                DataResult<List<StationHomeRespVo>> pointDataList = tdFeignClient.queryHisValueList(tdBaseQuery);
                List<ElecTemplateSub> elecTemplateSubs = elecMapper.selectByStationId(station.getId());
                this.processDatasAndPushDB(tdBaseQuery, pointDataList,1,elecTemplateSubs);
            }

            // 日放
            if ( null != dailyDischarge && null != dailyDischarge.getMap() && dailyDischarge.getMap().size() > 0 ) {
                tdBaseQuery = new TdBaseTimeQuery();
                tdBaseQuery.setBeginTime(beginTime.toMsStr());
                tdBaseQuery.setEndTime(endTime.toMsStr());
                tdBaseQuery.setTime("1m");
                tdBaseQuery.setStationId(station.getId());
                tdBaseQuery.setGroupId(station.getGroupId());
                tdBaseQuery.setMap(dailyDischarge.getMap());
                if (dailyDischarge != null || !dailyDischarge.getDeviceIdList().isEmpty()) {
                    List<PointCurveSrcCol> deviceIdList = dailyDischarge.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.setDeviceIdList(dailyDischarge.getDeviceIdList());
                //数据TD查询(soc)
                DataResult<List<StationHomeRespVo>> dailyDischargeList = tdFeignClient.queryHisValueList(tdBaseQuery);
                List<ElecTemplateSub> elecTemplateSubs = elecMapper.selectByStationId(station.getId());
                this.processDatasAndPushDB(tdBaseQuery, dailyDischargeList,2,elecTemplateSubs);
            }
        }
        return 0;
    }


    /**
     * 处理数据并进行入库操作
     * @param tdBaseQuery
     * @param list
     */
    private void processDatasAndPushDB(TdBaseTimeQuery tdBaseQuery,DataResult<List<StationHomeRespVo>> list,int type,List<ElecTemplateSub> elecTemplateSubs){
        if( list.getCode() != 200 ){
            return;
        }
        List<StationHomeRespVo> datas = list.getData();
        // 根据tdBaseQuery里stationId查询费率信息
        Integer stationId = tdBaseQuery.getStationId();
        String queryBeginTime = tdBaseQuery.getBeginTime().substring(0,10);
        String queryEndTime = tdBaseQuery.getEndTime().substring(0,10);
        // 先删除表里前一天的数据
        elecMapper.deleteRateMeterValue(queryBeginTime,queryEndTime,type);
        logger.info("定时任务查询到的数据长度：{}", datas.size());
        if( datas.size() > 0 && elecTemplateSubs.size() > 0 ){
            // 遍历数据并判断数据时间，按照费率累加入库
            List<ElecRateMeterValue> values = new ArrayList<>(0);
            ElecRateMeterValue value = null;
            int index = 1;
            BigDecimal data = null;
            for (int i = 0; i < elecTemplateSubs.size(); i++) {
                value = new ElecRateMeterValue();
                data = new BigDecimal("0");
                String beginTime = elecTemplateSubs.get(i).getBeginTime();
                String endTime = elecTemplateSubs.get(i).getEndTime();
                DateTime beginDate = DateUtil.parse(queryBeginTime+" "+beginTime);
                DateTime endDate = null;
                if ( !endTime.equals("24:00") ) {
                    endDate = DateUtil.parse(queryBeginTime+" "+endTime);
                } else {
                    endDate = DateUtil.parse(queryEndTime+" 00:00:00");
                }
                // 获取费率类型
                String rateType = elecTemplateSubs.get(i).getType();
                BigDecimal price = elecTemplateSubs.get(i).getPrice();
                // 基准值
                BigDecimal baseDigital = new BigDecimal("0");
                // 最后值
                BigDecimal lastDigital = new BigDecimal("0");
                if( index == datas.size() - 1 ) {
                    break;
                }
                for (int j = index; j < datas.size(); j++) {
                    String dataTime = datas.get(j).getDate();
                    DateTime dataDate = DateUtil.parse(dataTime);
                    BigDecimal digital = datas.get(j).getDigital();
                    // 取进来的第一个值
                    if( j == index ){
                        baseDigital = digital;
                    }
                    if( DateUtil.isIn( dataDate,beginDate,endDate ) ){
                        lastDigital = digital;
                    }
                    //else {
                    //    lastDigital = baseDigital;
                    //}
                    if( j+1 < datas.size() && !DateUtil.isIn( dataDate,beginDate,endDate ) ){
                        //BigDecimal subtract = lastDigital.subtract(baseDigital);
                        //data = subtract.multiply(price);
                        data = data.add((lastDigital.subtract(baseDigital)).multiply(price).divide(new BigDecimal("10000")));
                        index = j;
                        value.setDay(queryBeginTime);
                        value.setDigital(new BigDecimal( String.format("%.6f",data) ));
                        value.setStationId(stationId);
                        value.setRateType(rateType);
                        value.setType(type);
                        values.add(value);
                        break;
                    }
                    if( j+1 == datas.size() ){
                        data = data.add((lastDigital.subtract(baseDigital)).multiply(price).divide(new BigDecimal("10000")));
                        index = j;
                        value.setDay(queryBeginTime);
                        value.setDigital(new BigDecimal( String.format("%.6f",data) ));
                        value.setStationId(stationId);
                        value.setRateType(rateType);
                        value.setType(type);
                        values.add(value);
                    }
                }
            }
            // 入库
            //System.out.println("****************************************************");
            //System.out.println(values);
            //System.out.println("****************************************************");
            elecMapper.insertRateMeterValue(values);
            //System.out.println("结束时间： "+System.currentTimeMillis());
        }
    }

    @Override
    public List<Map<String, Object>> getPcsIncomeData(PcsStationReq req) {
        //当前时间
        Date end = new Date();
        String endTime = DateUtil.format(end, CommonConstant.DATE_YMD);
        String beginTime = null;
        //根据传入类型判断
        String type = req.getType();
        if (CommonConstant.MONTH.equals(type)) {
            //一个月前的时间
            DateTime begin = DateUtil.beginOfMonth(end);
            beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
        }else if (CommonConstant.YEAR.equals(type)) {
            DateTime begin = DateUtil.beginOfYear(end);
            beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
        } else {
            //查询最近七天
            //七天前的时间
            DateTime begin = DateUtil.offsetDay(end, -6);
            beginTime = DateUtil.format(begin, CommonConstant.DATE_YMD);
        }
        return elecMapper.getPcsIncomeData(req, beginTime,endTime);
    }

    @Override
    public Map<String, Object> getPcsRealTimeIncomeData(StationReq req) {
        // 充
        String dailyCharge = "dailyCharge";
        // 放
        String dailyDischarge = "dailyDischarge";
        Map<String,Object> result = new HashMap<>(0);
        // 存放充电数据
        LinkedList<Object> chargeList = new LinkedList<>();
        // 存放放电数据
        LinkedList<Object> disChargeList = new LinkedList<>();
        // 存放横坐标数据
        LinkedList<Object> xAxisList = new LinkedList<>();
        // 查询的数据时间
        DateTime dateTime = DateUtil.date();
        List<ElecRateMeterValue> values = elecMapper.queryRealTimePcsIncomeData(req.getStationId(), dateTime.toMsStr());
        for (ElecRateMeterValue v : values) {
            if( v.getType() == 1 ){
                chargeList.add(v.getDigital());
                xAxisList.add(v.getRateType());
            } else {
                disChargeList.add(v.getDigital());
            }
        }
        result.put(dailyCharge,chargeList);
        result.put(dailyDischarge,disChargeList);
        result.put("xAxisList",xAxisList);
        return result;
    }

    @Override
    public void exportEleData(PcsStationReq req, HttpServletResponse response,String lang) {
        try {
            List<Integer> stationIds = req.getStationIds();
            List<Station> stations = stationService.selectStationsByIds(stationIds,lang);
            Map<Integer, String> idNameMap = getStationMap(stations);
            List<Map<String, Object>> sheetsList = new ArrayList<>();
            //汇总
            BigDecimal charge = BigDecimal.ZERO;
            BigDecimal discharge = BigDecimal.ZERO;
            String segmentType = req.getSegmentType();
            String name = "";
            String summary = DefineConstant.SUMMARY;
            String summaryData = DefineConstant.SUMMARY_DATA_STATION;
            if(CommonConstant.langTemp.EN_US.equals(lang)){
                summary = DefineConstant.SUMMARY_EN;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_EN;
            }
            if(CommonConstant.langTemp.FR_FR.equals(lang)){
                summary = DefineConstant.SUMMARY_FRA;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_FRA;
            }
            if(CommonConstant.langTemp.ES_ES.equals(lang)){
                summary = DefineConstant.SUMMARY_SPA;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_SPA;
            }
            if(CommonConstant.langTemp.AR_EG.equals(lang)){
                summary = DefineConstant.SUMMARY_ARA;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_ARA;
            }
            if(CommonConstant.langTemp.DE_DE.equals(lang)){
                summary = DefineConstant.SUMMARY_DE;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_DE;
            }
            if(CommonConstant.langTemp.PL_PL.equals(lang)){
                summary = DefineConstant.SUMMARY_PL;
                summaryData = DefineConstant.SUMMARY_DATA_STATION_PL;
            }
            if("segment".equals(segmentType)){
                List<EarningsCalculateData> totalList = new ArrayList<>();
                BigDecimal chargeTip = BigDecimal.ZERO;
                BigDecimal chargePeak = BigDecimal.ZERO;
                BigDecimal chargeFlat = BigDecimal.ZERO;
                BigDecimal chargeValley = BigDecimal.ZERO;
                BigDecimal dischargeTip = BigDecimal.ZERO;
                BigDecimal dischargePeak = BigDecimal.ZERO;
                BigDecimal dischargeFlat = BigDecimal.ZERO;
                BigDecimal dischargeValley = BigDecimal.ZERO;
                for (Integer stationId : stationIds) {
                    req.setStationId(stationId);
                    List<EarningsCalculateData> dataList = earningsCalculateService.getEarningsList(req);
                    EarningsCalculateData calculateData = new EarningsCalculateData();
                    calculateData.setDate(summary);
                    calculateData.setChargeTip(dataList.stream().map(EarningsCalculateData::getChargeTip).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargePeak(dataList.stream().map(EarningsCalculateData::getChargePeak).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeFlat(dataList.stream().map(EarningsCalculateData::getChargeFlat).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeValley(dataList.stream().map(EarningsCalculateData::getChargeValley).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeElec(dataList.stream().map(EarningsCalculateData::getChargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeTip(dataList.stream().map(EarningsCalculateData::getDischargeTip).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargePeak(dataList.stream().map(EarningsCalculateData::getDischargePeak).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeFlat(dataList.stream().map(EarningsCalculateData::getDischargeFlat).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeValley(dataList.stream().map(EarningsCalculateData::getDischargeValley).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeElec(dataList.stream().map(EarningsCalculateData::getDischargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    name = idNameMap.get(stationId);
                    if(dataList.size()>0){
                        dataList.add(calculateData);
                        setSheetEarningsData(sheetsList, name==null?"":name.replaceAll("/", " "), dataList,lang);
                    }
                    charge = charge.add(calculateData.getChargeElec());
                    discharge = discharge.add(calculateData.getDischargeElec());
                    chargeTip = chargeTip.add(calculateData.getChargeTip());
                    chargePeak = chargePeak.add(calculateData.getChargePeak());
                    chargeFlat = chargeFlat.add(calculateData.getChargeFlat());
                    chargeValley = chargeValley.add(calculateData.getChargeValley());
                    dischargeTip = dischargeTip.add(calculateData.getDischargeTip());
                    dischargePeak = dischargePeak.add(calculateData.getDischargePeak());
                    dischargeFlat = dischargeFlat.add(calculateData.getDischargeFlat());
                    dischargeValley = dischargeValley.add(calculateData.getDischargeValley());
                    EarningsCalculateData newData = new EarningsCalculateData();
                    BeanUtils.copyProperties(calculateData,newData);
                    newData.setDate(name);
                    totalList.add(newData);
                }
                if(stationIds.size()>0){
                    EarningsCalculateData calculateData = new EarningsCalculateData();
                    calculateData.setChargeTip(chargeTip);
                    calculateData.setChargePeak(chargePeak);
                    calculateData.setChargeFlat(chargeFlat);
                    calculateData.setChargeValley(chargeValley);
                    calculateData.setDischargeTip(dischargeTip);
                    calculateData.setDischargePeak(dischargePeak);
                    calculateData.setDischargeFlat(dischargeFlat);
                    calculateData.setDischargeValley(dischargeValley);
                    calculateData.setChargeElec(charge);
                    calculateData.setDischargeElec(discharge);
                    calculateData.setDate(summary);
                    totalList.add(calculateData);
                    setSheetEarningsData(sheetsList, summaryData, totalList,lang);
                }
                ExcelUtil.exportExcel(sheetsList,response);
            }else{
                List<PcsElecData> totalList = new ArrayList<>();
                for (Integer stationId : stationIds) {
                    //转成导出vo类型
                    String deviceType = colCountService.getDeviceType(stationId);
                    if (null == deviceType) {
                        deviceType = DeviceTypeConstant.PCS;
                    }
                    req.setDeviceType(deviceType);
                    req.setStationId(stationId);
                    List<PcsElecData> dataList = stationHomeService.getElecData(req,null);
                    Integer unitType = getInteger(stationId, deviceType);
                    dataList.stream().forEach(i-> changeData(unitType, i));
                    PcsElecData pcsElecData = new PcsElecData();
                    pcsElecData.setChargeElec(dataList.stream().map(PcsElecData::getChargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    pcsElecData.setDischargeElec(dataList.stream().map(PcsElecData::getDischargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    pcsElecData.setDate(summary);
                    name = idNameMap.get(stationId);
                    if(dataList.size()>0){
                        dataList.add(pcsElecData);
                        setSheetElecData(sheetsList, name==null?"":name.replaceAll("/", " "), dataList,lang);
                    }
                    charge = charge.add(pcsElecData.getChargeElec());
                    discharge = discharge.add(pcsElecData.getDischargeElec());
                    PcsElecData newData = new PcsElecData();
                    BeanUtils.copyProperties(pcsElecData,newData);
                    newData.setDate(name);
                    totalList.add(newData);
                }
                if(stationIds.size()>0){
                    PcsElecData pcsElecData = new PcsElecData();
                    pcsElecData.setChargeElec(charge);
                    pcsElecData.setDischargeElec(discharge);
                    pcsElecData.setDate(summary);
                    totalList.add(pcsElecData);
                    setSheetElecData(sheetsList, summaryData, totalList,lang);
                }
                ExcelUtil.exportExcel(sheetsList,response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @NotNull
    private Map<Integer, String> getStationMap(List<Station> stations) {
        Map<Integer, String> idNameMap = stations.stream().collect(Collectors.toMap(Station::getId, Station::getName));
        return idNameMap;
    }

    @Override
    public PageResult getElecData(PcsStationReq req) {
        PageResult pageResult = new PageResult<>();
        try {
            List<Integer> stationIds = req.getStationIds();
            List<Station> stations = stationService.selectStationsByIds(stationIds,null);
            Map<Integer, String> idNameMap = stations.stream().collect(Collectors.toMap(Station::getId, Station::getName));
            List<PcsElecData> result = new ArrayList<>();
            String name = null;
            for (int i = 0; i < stationIds.size(); i++) {
                Integer stationId = stationIds.get(i);
                String deviceType = colCountService.getDeviceType(stationId);
                if (null == deviceType) {
                    deviceType = DeviceTypeConstant.PCS;
                }
                req.setDeviceType(deviceType);
                req.setStationId(stationId);
                name = idNameMap.get(stationId);
                List<PcsElecData> dataList = stationHomeService.getElecData(req,name);
                result.addAll(dataList);
            }
            if (!result.isEmpty()) {
                List list = PageUtils.dealList(result, req.getPageNum(), req.getPageSize());
                pageResult = PageUtils.getPageResult(new PageInfo<>(list));
                pageResult.setTotalRows(result.size());
                pageResult.setTotalPages(result.size() / req.getPageSize() + 1);
            } else {
                pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageResult;
    }

    @Override
    public Object getElecMeterList(PcsStationReq req) {
        Object obj = new Object();
        try {
            List<Integer> stationIds = req.getStationIds();
            List<Station> stations = stationService.selectStationsByIds(stationIds,req.getLang());
            Map<Integer, String> idNameMap = getStationMap(stations);
            //汇总
            BigDecimal charge = BigDecimal.ZERO;
            BigDecimal discharge = BigDecimal.ZERO;
            String segmentType = req.getSegmentType();
            String name = "";
            String summary = DefineConstant.SUMMARY;
            if(CommonConstant.langTemp.EN_US.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_EN;
            }else if(CommonConstant.langTemp.FR_FR.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_FRA;
            }else if(CommonConstant.langTemp.ES_ES.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_SPA;
            }else if(CommonConstant.langTemp.DE_DE.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_DE;
            }else if(CommonConstant.langTemp.PL_PL.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_PL;
            }else if(CommonConstant.langTemp.AR_EG.equals(req.getLang())){
                summary = DefineConstant.SUMMARY_ARA;
            }
            if(CommonConstant.SEGMENT.equals(segmentType)){
                List<EarningsCalculateData> resultList = new ArrayList<>();
                BigDecimal chargeTip = BigDecimal.ZERO;
                BigDecimal chargePeak = BigDecimal.ZERO;
                BigDecimal chargeFlat = BigDecimal.ZERO;
                BigDecimal chargeValley = BigDecimal.ZERO;
                BigDecimal dischargeTip = BigDecimal.ZERO;
                BigDecimal dischargePeak = BigDecimal.ZERO;
                BigDecimal dischargeFlat = BigDecimal.ZERO;
                BigDecimal dischargeValley = BigDecimal.ZERO;
                for (Integer stationId : stationIds) {
                    name = idNameMap.get(stationId);
                    req.setStationId(stationId);
                    List<EarningsCalculateData> dataList = earningsCalculateService.getEarningsList(req);
                    EarningsCalculateData calculateData = new EarningsCalculateData();
                    calculateData.setStationId(stationId);
                    calculateData.setDate(summary);
                    calculateData.setChargeTip(dataList.stream().map(EarningsCalculateData::getChargeTip).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargePeak(dataList.stream().map(EarningsCalculateData::getChargePeak).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeFlat(dataList.stream().map(EarningsCalculateData::getChargeFlat).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeValley(dataList.stream().map(EarningsCalculateData::getChargeValley).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setChargeElec(dataList.stream().map(EarningsCalculateData::getChargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeTip(dataList.stream().map(EarningsCalculateData::getDischargeTip).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargePeak(dataList.stream().map(EarningsCalculateData::getDischargePeak).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeFlat(dataList.stream().map(EarningsCalculateData::getDischargeFlat).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeValley(dataList.stream().map(EarningsCalculateData::getDischargeValley).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setDischargeElec(dataList.stream().map(EarningsCalculateData::getDischargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    calculateData.setName(name);
                    resultList.add(calculateData);
                    charge = charge.add(calculateData.getChargeElec());
                    discharge = discharge.add(calculateData.getDischargeElec());
                    chargeTip = chargeTip.add(calculateData.getChargeTip());
                    chargePeak = chargePeak.add(calculateData.getChargePeak());
                    chargeFlat = chargeFlat.add(calculateData.getChargeFlat());
                    chargeValley = chargeValley.add(calculateData.getChargeValley());
                    dischargeTip = dischargeTip.add(calculateData.getDischargeTip());
                    dischargePeak = dischargePeak.add(calculateData.getDischargePeak());
                    dischargeFlat = dischargeFlat.add(calculateData.getDischargeFlat());
                    dischargeValley = dischargeValley.add(calculateData.getDischargeValley());
                }
                if(stationIds.size()>0){
                    EarningsCalculateData calculateData = new EarningsCalculateData();
                    calculateData.setChargeTip(chargeTip);
                    calculateData.setChargePeak(chargePeak);
                    calculateData.setChargeFlat(chargeFlat);
                    calculateData.setChargeValley(chargeValley);
                    calculateData.setDischargeTip(dischargeTip);
                    calculateData.setDischargePeak(dischargePeak);
                    calculateData.setDischargeFlat(dischargeFlat);
                    calculateData.setDischargeValley(dischargeValley);
                    calculateData.setChargeElec(charge);
                    calculateData.setDischargeElec(discharge);
                    calculateData.setDate(summary);
                    calculateData.setName(summary);
                    resultList.add(calculateData);
                    obj = resultList;
                }
            }else{
                List<PcsElecData> resultList = new ArrayList<>();
                for (Integer stationId : stationIds) {
                    //转成导出vo类型
                    String deviceType = colCountService.getDeviceType(stationId);
                    if (null == deviceType) {
                        deviceType = DeviceTypeConstant.PCS;
                    }
                    req.setDeviceType(deviceType);
                    req.setStationId(stationId);
                    name = idNameMap.get(stationId);
                    List<PcsElecData> dataList = stationHomeService.getElecData(req,name);
                    PcsElecData pcsElecData = new PcsElecData();
                    pcsElecData.setChargeElec(dataList.stream().map(PcsElecData::getChargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    pcsElecData.setDischargeElec(dataList.stream().map(PcsElecData::getDischargeElec).reduce(BigDecimal.ZERO, BigDecimal::add));
                    pcsElecData.setStationId(stationId);
                    pcsElecData.setName(name);
                    pcsElecData.setDate(summary);
                    changeData(getInteger(stationId, deviceType), pcsElecData);
                    resultList.add(pcsElecData);
//                    dataList.add(pcsElecData);
                    charge = charge.add(pcsElecData.getChargeElec());
                    discharge = discharge.add(pcsElecData.getDischargeElec());
                }
                if(stationIds.size()>0){
                    PcsElecData pcsElecData = new PcsElecData();
                    pcsElecData.setChargeElec(charge);
                    pcsElecData.setDischargeElec(discharge);
                    pcsElecData.setName(summary);
                    pcsElecData.setDate(summary);
                    resultList.add(pcsElecData);
                }
                obj = resultList;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 根据单位放大数据
     * @param unitType
     * @param pcsElecData
     */
    private void changeData(Integer unitType, PcsElecData pcsElecData) {
        pcsElecData.setChargeElec(bigDecimalUtil.unitConversion(pcsElecData.getChargeElec(),unitType));
        pcsElecData.setDischargeElec(bigDecimalUtil.unitConversion(pcsElecData.getDischargeElec(),unitType));
    }

    /**
     * 获取单位
     * @param stationId
     * @param deviceType
     * @return
     */
    @NotNull
    private Integer getInteger(Integer stationId, String deviceType) {
        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
        if (deviceRespVOS.isEmpty()) {
            deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
        }
        Integer unitType = deviceRespVOS != null && deviceRespVOS.size() > 0 && deviceRespVOS.get(0).getUnitType() != null ? deviceRespVOS.get(0).getUnitType() : 1;
        return unitType;
    }

    @Override
    public Object getElecMeterDetailList(PcsStationReq req) {
        Object obj = new Object();
        try {
            List<Integer> stationIds = req.getStationIds();
            List<Station> stations = stationService.selectStationsByIds(stationIds,req.getLang());
            Map<Integer, String> idNameMap = getStationMap(stations);
            //汇总
            String segmentType = req.getSegmentType();
            String name = "";
            Integer stationId = req.getStationId();
            if(null == stationId){
                return obj;
            }
            if(CommonConstant.SEGMENT.equals(segmentType)){
                List<EarningsCalculateData> resultList = new ArrayList<>();
                name = idNameMap.get(stationId);
                req.setStationId(stationId);
                req.setStationName(name);
                List<EarningsCalculateData> dataList = earningsCalculateService.getEarningsList(req);
                resultList.addAll(dataList);
                obj = resultList;
            }else{
                List<PcsElecData> resultList = new ArrayList<>();
                String deviceType = colCountService.getDeviceType(stationId);
                if (null == deviceType) {
                    deviceType = DeviceTypeConstant.PCS;
                }
                req.setDeviceType(deviceType);
                req.setStationId(stationId);
                name = idNameMap.get(stationId);
                List<PcsElecData> dataList = stationHomeService.getElecData(req,name);
                Integer unitType = getInteger(stationId, deviceType);
                dataList.stream().forEach(i-> changeData(unitType, i));
                resultList.addAll(dataList);
                obj = resultList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Override
    public HomePageStationDataResp getHomePageStationData(StationReq req) {
        Integer stationId = req.getStationId();
        //根据id查询电站
        Station station = stationService.selectById(stationId);
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        //查总充总放用的那个类型
        String deviceType = req.getDeviceType();
        if (deviceType == null) {
            deviceType = colCountService.getDeviceType(req.getStationId());
            req.setDeviceType(deviceType);
        }
        deviceType = deviceType == null?DeviceTypeConstant.PCS:deviceType;

        //计算运行天数
        long operationDays = DateUtil.between(station.getGridTime(), new Date(), DateUnit.DAY);

        //计算系统转化效率
        BigDecimal systemEfficiency = BigDecimal.ZERO;
        //总充电量
        BigDecimal totalChargeElec = BigDecimal.ZERO;
        //总放电量
        BigDecimal totalDischargeElec = BigDecimal.ZERO;
        //当前功率
        BigDecimal currentPower = BigDecimal.ZERO;
        //日发电量(光伏)
        BigDecimal dailyPowerGeneration = BigDecimal.ZERO;
        //总发电量(光伏)
        BigDecimal pvTotalPowerGeneration = BigDecimal.ZERO;
        //本地负载日用电量
        BigDecimal dailyElecOfLocal = BigDecimal.ZERO;
        //本地负载总用电量
        BigDecimal totalElecOfLocal = BigDecimal.ZERO;

        List<DeviceRespVO> deviceRespVOS = deviceService.getListByDeviceType(stationId, deviceType);
        if(deviceRespVOS.isEmpty()){
            deviceRespVOS = deviceService.getListByFuzzyDeviceType(stationId, deviceType);
        }
        //是否是pcs
        boolean flag = DeviceTypeConstant.PCS.equals(deviceType);

        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(flag){
                        Object objOutputPower = map.get(DataCollectConstant.PCS_POINT.OUTPUT_POWER);
                        if (objOutputPower instanceof DeviceTransfer) {
                            DeviceTransfer outputPower = (DeviceTransfer) objOutputPower;
                            currentPower = outputPower.getValue() != null ? currentPower.add(outputPower.getValue()) : currentPower;
                        }
                    }
                    Object objPvDaily = map.get(DataCollectConstant.PCS_POINT.DAILY_POWER_GENERATION);
                    if (objPvDaily instanceof DeviceTransfer) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer) objPvDaily;
                        dailyPowerGeneration = deviceTransfer.getValue() != null ? dailyPowerGeneration.add(deviceTransfer.getValue()) : dailyPowerGeneration;
                    }
                    Object objPVTotal = map.get(DataCollectConstant.PCS_POINT.PV_TOTAL_POWER_GENERATION);
                    if (objPVTotal instanceof DeviceTransfer) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer) objPVTotal;
                        pvTotalPowerGeneration = deviceTransfer.getValue() != null ? pvTotalPowerGeneration.add(deviceTransfer.getValue()) : pvTotalPowerGeneration;
                    }
                    Object objElecDaily = map.get(DataCollectConstant.PCS_POINT.DAILY_ELEC_OF_LOCAL);
                    if (objElecDaily instanceof DeviceTransfer) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer) objElecDaily;
                        dailyElecOfLocal = deviceTransfer.getValue() != null ? dailyElecOfLocal.add(deviceTransfer.getValue()) : dailyElecOfLocal;
                    }
                    Object objElecTotal = map.get(DataCollectConstant.PCS_POINT.TOTAL_ELEC_OF_LOCAL);
                    if (objElecTotal instanceof DeviceTransfer) {
                        DeviceTransfer totalDischarge = (DeviceTransfer) objElecTotal;
                        totalElecOfLocal = totalDischarge.getValue() != null ? totalElecOfLocal.add(totalDischarge.getValue()) : totalElecOfLocal;
                    }
                }
            }
        }

        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);
        if (BigDecimal.ZERO.compareTo(totalChargeElec)!=0) {
            systemEfficiency = totalDischargeElec.divide(totalChargeElec, 4, BigDecimal.ROUND_HALF_UP);
        }
        //创建返回值并赋值
        HomePageStationDataResp data = new HomePageStationDataResp();
        data.setTotalCapacity(station.getCapacity());
        data.setRateCapacity(station.getCapacity());
        data.setOperationDays((int) operationDays);
        data.setTotalChargeElec(totalChargeElec);
        data.setTotalDischargeElec(totalDischargeElec);
        data.setRatePower(station.getRatePower());
        data.setSystemEfficiency(systemEfficiency);
        data.setCurrentPower(currentPower);
        data.setDailyElecOfLocal(dailyElecOfLocal);
        data.setDailyPowerGeneration(dailyPowerGeneration);
        data.setPvTotalPowerGeneration(pvTotalPowerGeneration);
        data.setTotalElecOfLocal(totalElecOfLocal);
        //当前功率
        if(!flag && currentPower.compareTo(BigDecimal.ZERO) == 0){
            ActiveReactivePower acPower = getAcPower(stationId);
            if (acPower != null) {
                data.setCurrentPower(acPower.getActivePowerPCS());
            }
        }
        return data;
    }

    private void setSheetElecData(List<Map<String, Object>> sheetsList, String name, List<PcsElecData> dataList,String lang) {
        // 创建参数对象（用来设定excel的sheet1内容等信息）
        ExportParams userExportParams = new ExportParams();
        // 设置sheet得名称
        userExportParams.setSheetName(name);
        // 创建sheet1使用得map
        Map<String, Object> userExportMap = new HashMap<>();
        // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
        userExportMap.put("title", userExportParams);
        // 模版导出对应得实体类型
        if(CommonConstant.langTemp.EN_US.equals(lang)){
            userExportMap.put("entity", PcsElecDataEn.class);
            List<PcsElecDataEn> enList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataEn en = new PcsElecDataEn();
                BeanUtils.copyProperties(s, en);
                enList.add(en);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", enList);
        }else if(CommonConstant.langTemp.FR_FR.equals(lang)){
            userExportMap.put("entity", PcsElecDataFra.class);
            List<PcsElecDataFra> fraList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataFra fra = new PcsElecDataFra();
                BeanUtils.copyProperties(s, fra);
                fraList.add(fra);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", fraList);
        }else if(CommonConstant.langTemp.ES_ES.equals(lang)){
            userExportMap.put("entity", PcsElecDataSpa.class);
            List<PcsElecDataSpa> spaList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataSpa spa = new PcsElecDataSpa();
                BeanUtils.copyProperties(s, spa);
                spaList.add(spa);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", spaList);
        }else if(CommonConstant.langTemp.AR_EG.equals(lang)){
            userExportMap.put("entity", PcsElecDataAra.class);
            List<PcsElecDataAra> araList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataAra ara = new PcsElecDataAra();
                BeanUtils.copyProperties(s, ara);
                araList.add(ara);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", araList);
        }else if(CommonConstant.langTemp.DE_DE.equals(lang)){
            userExportMap.put("entity", PcsElecDataDe.class);
            List<PcsElecDataDe> deList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataDe de = new PcsElecDataDe();
                BeanUtils.copyProperties(s, de);
                deList.add(de);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", deList);
        }else if(CommonConstant.langTemp.PL_PL.equals(lang)){
            userExportMap.put("entity", PcsElecDataPl.class);
            List<PcsElecDataPl> plList=new ArrayList<>();
            dataList.stream().forEach(s->{
                PcsElecDataPl pl = new PcsElecDataPl();
                BeanUtils.copyProperties(s, pl);
                plList.add(pl);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", plList);
        }

        else{
            userExportMap.put("entity", PcsElecData.class);
            // sheet1中要填充得数据
            userExportMap.put("data", dataList);
        }
        sheetsList.add(userExportMap);
    }

    private void setSheetEarningsData(List<Map<String, Object>> sheetsList, String name, List<EarningsCalculateData> dataList,String lang) {
        // 创建参数对象（用来设定excel的sheet1内容等信息）
        ExportParams userExportParams = new ExportParams();
        // 设置sheet得名称
        userExportParams.setSheetName(name);
        // 创建sheet1使用得map
        Map<String, Object> userExportMap = new HashMap<>();
        // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
        userExportMap.put("title", userExportParams);
        // 模版导出对应得实体类型
        if(CommonConstant.langTemp.EN_US.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataEn.class);
            List<EarningsCalculateDataEn> enList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataEn en = new EarningsCalculateDataEn();
                BeanUtils.copyProperties(s, en);
                enList.add(en);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", enList);
        }else if(CommonConstant.langTemp.FR_FR.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataFra.class);
            List<EarningsCalculateDataFra> fraList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataFra fra = new EarningsCalculateDataFra();
                BeanUtils.copyProperties(s, fra);
                fraList.add(fra);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", fraList);
        }else if(CommonConstant.langTemp.ES_ES.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataSpa.class);
            List<EarningsCalculateDataSpa> spaList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataSpa spa = new EarningsCalculateDataSpa();
                BeanUtils.copyProperties(s, spa);
                spaList.add(spa);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", spaList);
        }else if(CommonConstant.langTemp.AR_EG.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataAra.class);
            List<EarningsCalculateDataAra> araList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataAra ara = new EarningsCalculateDataAra();
                BeanUtils.copyProperties(s, ara);
                araList.add(ara);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", araList);
        }else if(CommonConstant.langTemp.DE_DE.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataDe.class);
            List<EarningsCalculateDataDe> deList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataDe de = new EarningsCalculateDataDe();
                BeanUtils.copyProperties(s, de);
                deList.add(de);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", deList);
        }else if(CommonConstant.langTemp.PL_PL.equals(lang)){
            userExportMap.put("entity", EarningsCalculateDataPl.class);
            List<EarningsCalculateDataPl> plList=new ArrayList<>();
            dataList.stream().forEach(s->{
                EarningsCalculateDataPl pl = new EarningsCalculateDataPl();
                BeanUtils.copyProperties(s, pl);
                plList.add(pl);
            });
            // sheet1中要填充得数据
            userExportMap.put("data", plList);
        }else{
            userExportMap.put("entity", EarningsCalculateData.class);
            // sheet1中要填充得数据
            userExportMap.put("data", dataList);
        }
        sheetsList.add(userExportMap);
    }
}
