package com.ho.business.controller;

import com.alibaba.fastjson.JSON;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.Station;
import com.ho.business.service.*;
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.dynamicConfig.DynamicConfigQuery;
import com.ho.business.vo.req.pcsStation.PcsStationReq;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.InverterResp.PowerGenerateRespVO;
import com.ho.business.vo.resp.cabin.CircleCtrlResp;
import com.ho.business.vo.resp.cabin.EarningsCalculateCountResp;
import com.ho.business.vo.resp.openStationHome.OpenStationMiddle;
import com.ho.business.vo.resp.openStationHome.OpenStationMiddleOrig;
import com.ho.business.vo.resp.openStationHome.StatusMonitorVo;
import com.ho.business.vo.resp.pcsStation.HomePageStationDataResp;
import com.ho.business.vo.resp.pcsStation.PcsElecData;
import com.ho.business.vo.resp.pcsStation.PcsStationData;
import com.ho.business.vo.resp.pcsStation.PcsTotalData;
import com.ho.business.vo.resp.point.WareHouse;
import com.ho.business.vo.resp.station.ActiveReactivePower;
import com.ho.business.vo.resp.station.NewRealTimeCurveVo;
import com.ho.common.tools.annotation.TokenIgnore;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
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.vo.req.StationHomeRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fancl
 * @desc: OPEN环境的站首页
 * @date 2023/4/17
 */

@RestController
@RequestMapping(ContextConstant.BUSINESS + "openStation")
@Api(tags = "一体柜站首页")
@Slf4j
@Data
public class OpenStationController {
    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @Autowired
    StationHomeService stationHomeService;

    @Autowired
    StatusMonitorService statusMonitorService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    RedisService redisService;

    @Autowired
    StationService stationService;

    @Autowired
    OpenStationService openStationService;

    @Autowired
    CommonService commonService;

    @Autowired
    ColCountService colCountService;

    @Autowired
    EarningsCalculateService earningsCalculateService;

    @PostMapping("statusMonitor")
    @ApiOperation(value = "状态监控")
    public DataResult<StatusMonitorVo> statusMonitor(@RequestBody StationReq stationReq) {
        StatusMonitorVo statusMonitor = statusMonitorService.getStatusMonitor(stationReq.getStationId());
        bigDecimalUtil.keepTwoDecimalPlaces(statusMonitor);
        bigDecimalUtil.ifIsNUll(statusMonitor);
        return DataResult.success(statusMonitor);

    }


    @PostMapping("/realtimeCurve")
    @ApiOperation(value = "实时曲线")
    //@Cacheable(cacheManager = "towMinuteCacheManager", value = "stationRealtimeCurve", key = "#stationReq.stationId", sync = true)
    public DataResult<List<NewRealTimeCurveVo>> realtimeCurve(@RequestBody StationReq stationReq) {
        log.info("realtimeCurve.stationRealtimeCurve:" + stationReq);
        List<NewRealTimeCurveVo> resList = stationHomeService.getRealtimeCurve(stationReq);
        //返回值的BigDecimal类型保留两位小数
        for (NewRealTimeCurveVo newRealTimeCurveVo : resList) {
            List<StationHomeRespVo> list = newRealTimeCurveVo.getList();
            if (list != null && !CommonConstant.ZERO.equals(list.size())) {
                for (StationHomeRespVo stationHomeRespVo : list) {

                    BigDecimal digit = stationHomeRespVo.getDigital();
                    if (digit != null) {
                        String result = String.format("%.3f", digit);
                        stationHomeRespVo.setDigital(new BigDecimal(result));
                        ;
                    }
                    if (newRealTimeCurveVo.getDeviceName() == null) {
                        newRealTimeCurveVo.setDeviceName("");
                    }
                    //bigDecimalUtil.keepTwoDecimalPlaces(stationHomeRespVo);
                    //bigDecimalUtil.ifIsNUll(stationHomeRespVo);
                }
            }
        }
        return DataResult.success(resList);
    }

    @PostMapping("/strategyCurve")
    @ApiOperation(value = "策略总览曲线")
    public DataResult<List<NewRealTimeCurveVo>> strategyCurve(@RequestBody StationReq stationReq) {
        log.info("strategyCurve.stationRealtimeCurve:" + stationReq);
        List<NewRealTimeCurveVo> resList = stationHomeService.getStrategyCurve(stationReq);
        //返回值的BigDecimal类型保留两位小数
        for (NewRealTimeCurveVo newRealTimeCurveVo : resList) {
            List<StationHomeRespVo> list = newRealTimeCurveVo.getList();
            if (list != null && !CommonConstant.ZERO.equals(list.size())) {
                for (StationHomeRespVo stationHomeRespVo : list) {
                    BigDecimal digit = stationHomeRespVo.getDigital();
                    if (digit != null) {
                        String result = String.format("%.3f", digit);
                        stationHomeRespVo.setDigital(new BigDecimal(result));
                    }
                }
            }
        }
        return DataResult.success(resList);
    }

    @PostMapping("/dynamicRealtimeCurve")
    @ApiOperation(value = "动态配置-实时曲线")
    @TokenIgnore
    public DataResult<List<NewRealTimeCurveVo>> dynamicRealtimeCurve(@RequestBody DynamicConfigQuery vo, HttpServletRequest request) {
        //默认隐藏曲线不显示
        vo.setIsHide(CommonConstant.ZERO);
        vo.setLang(request.getHeader(CommonConstant.LANG));
        List<NewRealTimeCurveVo> resList = stationHomeService.getDynamicRealtimeCurve(vo);
        //返回值的BigDecimal类型保留两位小数
        for (NewRealTimeCurveVo newRealTimeCurveVo : resList) {
            List<StationHomeRespVo> list = newRealTimeCurveVo.getList();
            if (list != null && !CommonConstant.ZERO.equals(list.size())) {
                for (StationHomeRespVo stationHomeRespVo : list) {
                    BigDecimal digit = stationHomeRespVo.getDigital();
                    if (digit != null) {
                        String result = String.format("%.3f", digit);
                        stationHomeRespVo.setDigital(new BigDecimal(result));
                    }
                }
            }
        }
        return DataResult.success(resList);
    }

    @PostMapping("/pcsStationData")
    @ApiOperation(value = "电站信息")
    public DataResult<PcsStationData> getPcsStationData(@RequestBody StationReq req,HttpServletRequest request) {
        String lang = request.getHeader(CommonConstant.LANG);
        PcsStationData data = stationHomeService.getPcsStationData(req.getStationId(),lang);
        return DataResult.success(data);
    }

    @PostMapping("/pcsTotalData")
    @ApiOperation(value = "数据总览")
    public DataResult<PcsTotalData> pcsTotalData(@RequestBody StationReq req,HttpServletRequest request) {
        req.setLang(request.getHeader(CommonConstant.LANG));
        if (req.getDeviceType() == null) {
            String deviceType = colCountService.getDeviceType(req.getStationId());
            req.setDeviceType(deviceType);
        }
        PcsTotalData data = stationHomeService.getPcsTotalData(req);
        BigDecimal systemEfficiency = data.getSystemEfficiency();
        bigDecimalUtil.keepTwoDecimalPlaces(data);
        bigDecimalUtil.ifIsNUll(data);
        //保持精度
        data.setSystemEfficiency(systemEfficiency);
        return DataResult.success(data);
    }

    @PostMapping("/getEleTotalData")
    @ApiOperation(value = "数据总览（取电表计算）")
    public DataResult<PcsTotalData> getEleTotalData(@RequestBody StationReq req) {
        req.setDeviceType(DeviceTypeConstant.ELE_METER);
        PcsTotalData data = stationHomeService.getPcsTotalData(req);
        BigDecimal systemEfficiency = data.getSystemEfficiency();
        bigDecimalUtil.keepTwoDecimalPlaces(data);
        bigDecimalUtil.ifIsNUll(data);
        //保持精度
        data.setSystemEfficiency(systemEfficiency);
        return DataResult.success(data);
    }

    @PostMapping("/getPcsTotalData")
    @ApiOperation(value = "数据总览（取PCS计算）")
    @TokenIgnore
    public DataResult<PcsTotalData> getPcsTotalData(@RequestBody StationReq req,HttpServletRequest request) {
        req.setLang(request.getHeader(CommonConstant.LANG));
        if (req.getDeviceType() == null) {
            String deviceType = colCountService.getDeviceType(req.getStationId());
            if (null == deviceType) {
                deviceType = DeviceTypeConstant.PCS;
            }
            req.setDeviceType(deviceType);
        }
        PcsTotalData data = stationHomeService.getPcsTotalData(req);
        BigDecimal systemEfficiency = data.getSystemEfficiency();
        bigDecimalUtil.keepTwoDecimalPlaces(data);
        bigDecimalUtil.ifIsNUll(data);
        //保持精度
        data.setSystemEfficiency(systemEfficiency);
        return DataResult.success(data);
    }


    @PostMapping("/elecData")
    @ApiOperation(value = "充放电量")
    public DataResult<List<PcsElecData>> elecData(@RequestBody PcsStationReq req) throws ParseException {
        if (req.getDeviceType() == null) {
            String deviceType = colCountService.getDeviceType(req.getStationId());
            req.setDeviceType(deviceType);
        }
        List<PcsElecData> list = stationHomeService.getPcsElecData(req);
        for (PcsElecData pcsElecData : list) {
            bigDecimalUtil.keepTwoDecimalPlaces(pcsElecData);
            bigDecimalUtil.ifIsNUll(pcsElecData);
        }
        return DataResult.success(list);
    }

    @PostMapping("/getElecData")
    @ApiOperation(value = "充放电量(使用电表计算)")
    public DataResult<List<PcsElecData>> getElecData(@RequestBody PcsStationReq req) throws ParseException {
        req.setDeviceType(DeviceTypeConstant.ELE_METER);
        List<PcsElecData> list = stationHomeService.getPcsElecData(req);
        for (PcsElecData pcsElecData : list) {
            bigDecimalUtil.keepTwoDecimalPlaces(pcsElecData);
            bigDecimalUtil.ifIsNUll(pcsElecData);
        }
        return DataResult.success(list);
    }

    @PostMapping("/getPCSElecData")
    @ApiOperation(value = "充放电量(使用PCS计算)")
    @TokenIgnore
    public DataResult<List<PcsElecData>> getPCSElecData(@RequestBody PcsStationReq req) throws ParseException {
        if (req.getDeviceType() == null) {
            String deviceType = colCountService.getDeviceType(req.getStationId());
            if (null == deviceType) {
                deviceType = DeviceTypeConstant.PCS;
            }
            req.setDeviceType(deviceType);
        }
        List<PcsElecData> list = stationHomeService.getPcsElecData(req);

        for (PcsElecData pcsElecData : list) {
            bigDecimalUtil.keepTwoDecimalPlaces(pcsElecData);
            bigDecimalUtil.ifIsNUll(pcsElecData);
        }
        return DataResult.success(list);
    }

    @PostMapping("/getPvData")
    @ApiOperation(value = "mppt放电、收益(使用mppt计算)")
    public DataResult<List<PowerGenerateRespVO>> getPvData(@RequestBody PcsStationReq req) throws ParseException {
        //获取光伏放电、收益
        List<PowerGenerateRespVO> pvList = stationHomeService.getPvData(req);
        for (PowerGenerateRespVO pcsElecData : pvList) {
            bigDecimalUtil.keepTwoDecimalPlaces(pcsElecData);
            bigDecimalUtil.ifIsNUll(pcsElecData);
        }
        return DataResult.success(pvList);
    }



    /**
     * 导出累计充放电量数据
     *
     * @param response
     */
    @PostMapping("/exportExcel")
    @ApiOperation(value = "多电站导出累计充放电量数据")
    //@LogAnnotation(title = "累计充放电量", action = "导出累计充放电量数据")
    //@HzPermission(value = {PermissionConstant.REMOTECONTROL_COMMAND_EXPORT,PermissionConstant.DATA_SHOW_EXPORT,PermissionConstant.REMOTECONTROL_COMMAND_EXPORT})
    public void exportExcel(@RequestBody @Valid PcsStationReq req, HttpServletResponse response,HttpServletRequest request) {
        String lang = request.getHeader(CommonConstant.LANG);

        //功能描述：把同一个表格多个sheet测试结果重新输出，
        openStationService.exportEleData(req, response,lang);
    }


    @PostMapping("/getElecMeterValue")
    @ApiOperation(value = "获取多电站累计充放电量数据(分页)")
    public DataResult<PageResult<PcsElecData>> getElecMeterValue(@RequestBody PcsStationReq req) throws ParseException {
        PageResult elecData = openStationService.getElecData(req);
        return DataResult.success(elecData);
    }

    @PostMapping("/getElecMeterList")
    @ApiOperation(value = "获取多电站累计充放电量数据(不分页)")
    public DataResult<Object> getElecMeterList(@RequestBody PcsStationReq req,HttpServletRequest request) {
        req.setLang(request.getHeader(CommonConstant.LANG));
        Object obj = openStationService.getElecMeterList(req);
        return DataResult.success(obj);
    }

    @PostMapping("/getElecMeterDetailList")
    @ApiOperation(value = "获取电站累计充放电量详细数据(不分页)")
    public DataResult<Object> getElecMeterDetailList(@RequestBody PcsStationReq req) {
        Object obj = openStationService.getElecMeterDetailList(req);
        return DataResult.success(obj);
    }

    @PostMapping("/middle")
    @ApiOperation(value = "站首页的中间部分")
    public DataResult<OpenStationMiddle> middle(@RequestBody StationReq req) {

        Integer stationId = req.getStationId();
        //电网几个数据
        //查EMU
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);

        List<DeviceRespVO> emuList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.EMU);
        OpenStationMiddle middle = new OpenStationMiddle();
        if (!emuList.isEmpty()) {
            //只取第一个
            DeviceRespVO deviceEmu = emuList.get(0);
            //查redis缓存
            String emuKey = deviceEmu.getDeviceType() + ":" + stationId + ":" + deviceEmu.getSrcId();
            middle.setSrcId(deviceEmu.getSrcId());
            if (redisService.hasKey(emuKey)) {
                Map<Object, Object> emuMap = redisService.hgetall(emuKey);
                if (emuMap != null) {
                    OpenStationMiddleOrig middleOrig = JSON.parseObject(JSON.toJSONString(emuMap), OpenStationMiddleOrig.class);
                    if (middleOrig != null) {
                        //合位
                        middle.setCabinSwitch(middleOrig.getCabinSwitch() == null ? BigDecimal.ZERO : middleOrig.getCabinSwitch().getValue());
                        //有功功率 ,无功功率
                        BigDecimal activeAPowerEMU = middleOrig.getActiveAPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getActiveAPowerEMU().getValue();
                        BigDecimal activeBPowerEMU = middleOrig.getActiveBPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getActiveBPowerEMU().getValue();
                        BigDecimal activeCPowerEMU = middleOrig.getActiveCPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getActiveCPowerEMU().getValue();
                        BigDecimal activePowerEMU = activeAPowerEMU.add(activeBPowerEMU).add(activeCPowerEMU);
                        BigDecimal reactiveAPowerEMU = middleOrig.getReactiveAPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getReactiveAPowerEMU().getValue();
                        BigDecimal reactiveBPowerEMU = middleOrig.getReactiveBPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getReactiveBPowerEMU().getValue();
                        BigDecimal reactiveCPowerEMU = middleOrig.getReactiveCPowerEMU() == null ? BigDecimal.ZERO : middleOrig.getReactiveCPowerEMU().getValue();
                        BigDecimal reactivePowerEMU = reactiveAPowerEMU.add(reactiveBPowerEMU).add(reactiveCPowerEMU);
                        //这个值要除以1000
                        //边端已处理 ,不用除以1000了
                        //activePowerEMU = activePowerEMU.divide(new BigDecimal("1000"), 4, BigDecimal.ROUND_HALF_UP);
                        //reactivePowerEMU = reactivePowerEMU.divide(new BigDecimal("1000"), 4, BigDecimal.ROUND_HALF_UP);
                        middle.setActivePowerEMU(activePowerEMU);
                        middle.setReactivePowerEMU(reactivePowerEMU);
                        //频率
                        middle.setGridEMU(middleOrig.getGridEMU() == null ? BigDecimal.ZERO : middleOrig.getGridEMU().getValue());
                    }
                }
            }
        }
        //pcs总有功,总无功
        ActiveReactivePower acPower = openStationService.getAcPower(stationId);
        middle.setActivePowerPCS(acPower.getActivePowerPCS());
        middle.setReactivePowerPCS(acPower.getReactivePowerPCS());
        //BMS值 SOC,SOH
        new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> bmsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.BMS);

        List<WareHouse> wareHouseList = new ArrayList<>();
        if (!bmsList.isEmpty()) {
            BigDecimal soc = BigDecimal.ZERO;
            BigDecimal soh = BigDecimal.ZERO;
            int num = 0;
            for (int i = 0; i < bmsList.size(); i++) {
                DeviceRespVO deviceRespVO = bmsList.get(i);
                String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
                if (redisService.hasKey(key)) {
                    //两个BMS就是两个舱
                    WareHouse wareHouse = new WareHouse();
                    num++;
                    Map<Object, Object> bmsMap = redisService.hgetall(key);
                    if (bmsMap != null) {
                        OpenStationMiddleOrig middleOrig = JSON.parseObject(JSON.toJSONString(bmsMap), OpenStationMiddleOrig.class);
                        if (middleOrig != null) {
                            BigDecimal soc1 = middleOrig.getSoc() == null ? BigDecimal.ZERO : middleOrig.getSoc().getValue();
                            BigDecimal soh1 = middleOrig.getSoh() == null ? BigDecimal.ZERO : middleOrig.getSoh().getValue();
                            //wareHouse.setActivePowerPCS(acPower != null ? acPower.getActivePowerPCS() : BigDecimal.ZERO);
                            //wareHouse.setReactivePowerPCS(acPower != null ? acPower.getReactivePowerPCS() : BigDecimal.ZERO);
                            //wareHouseList.add(wareHouse);
                            soc = soc.add(soc1);
                            soh = soh.add(soh1);

                        }
                    }
                }
            }
            //计算两个平均值
            if (BigDecimal.ZERO.compareTo(soc) != 0) {
                soc = soc.divide(new BigDecimal(num), 2, BigDecimal.ROUND_UP);
                soh = soh.divide(new BigDecimal(num), 2, BigDecimal.ROUND_UP);
            }
            middle.setSoc(soc);
            middle.setSoh(soh);
        }
        //查舱数据
        Station station = stationService.selectById(stationId);
        if (station != null) {
            Integer cabinNum = station.getCabinNum();
            middle.setCabinCount(cabinNum);
        }
        //负荷功率=电网总有功-储能总有功
        BigDecimal activePowerEMU = middle.getActivePowerEMU();
        BigDecimal activePowerPCS = BigDecimal.ZERO;
        //总有功循环合计
        /*for (ActiveReactivePower acPower : acPowers) {
            activePowerPCS = activePowerPCS.add(acPower.getActivePowerPCS());
        }*/
        //负荷功率
        if (activePowerEMU == null) {
            activePowerEMU = BigDecimal.ZERO;
        }
        //负载功率
        BigDecimal loadPower = activePowerEMU.subtract(activePowerPCS);
        middle.setLoadPower(loadPower);
        middle.setWareHouseList(wareHouseList);
        bigDecimalUtil.keepTwoDecimalPlaces(middle);
        bigDecimalUtil.ifIsNUll(middle);
        return DataResult.success(middle);
    }

    @PostMapping("/middlePart")
    @ApiOperation(value = "站首页的中间部分-分开的")
    public DataResult<List<WareHouse>> middlePart(@RequestBody StationReq req) {
        Integer stationId = req.getStationId();
        //BMS值 SOC,SOH
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> bmsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.BMS);
        if (bmsList.isEmpty()) {
            bmsList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.BMS);
        }
        List<WareHouse> wareHouseList = new ArrayList<>();
        for (int i = 0; i < bmsList.size(); i++) {
            DeviceRespVO deviceRespVO = bmsList.get(i);
            String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                WareHouse wareHouse = new WareHouse();
                wareHouse.setBmsSrcId(deviceRespVO.getSrcId());
                DeviceTransfer soc = (DeviceTransfer) redisService.hget(key, "soc");
                DeviceTransfer soh = (DeviceTransfer) redisService.hget(key, "soh");
                Date updateTime = (Date) redisService.hget(key, "updateTime");
                wareHouse.setUpdateTime(updateTime);
                if (soc != null) {
                    wareHouse.setSoc(soc.getValue());
                }
                if (soh != null) {
                    wareHouse.setSoh(soh.getValue());
                }
                wareHouseList.add(wareHouse);
            }
        }

        //防逆流电表 有功功率
        DeviceReqVO devices = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        //防逆流
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.AMMETER_FNL);
        List<DeviceRespVO> fnlDeviceList = deviceService.getList(deviceReqVO);
        for (int i = 0; i < fnlDeviceList.size(); i++) {
            DeviceRespVO deviceRespVO = fnlDeviceList.get(i);
            String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                WareHouse wareHouse = new WareHouse();
                wareHouse.setBmsSrcId(deviceRespVO.getSrcId());
                DeviceTransfer activePower = (DeviceTransfer) redisService.hget(key, "activePower");
                //DeviceTransfer activePower = (DeviceTransfer) redisService.hget(key, "YC0010");
                Date updateTime = (Date) redisService.hget(key, "updateTime");
                wareHouse.setUpdateTime(updateTime);
                if (activePower != null) {
                    wareHouse.setActivePowerFNL(activePower.getValue());
                }

                wareHouseList.add(wareHouse);
            }
        }

        deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> pcsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.PCS);
        if (pcsList.isEmpty()) {
            pcsList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.PCS);
        }
        int len = wareHouseList.size() - 1;
        if (!pcsList.isEmpty()) {
            //总有功, 总无功
            for (int i = 0; i < pcsList.size(); i++) {
                String key = pcsList.get(i).getDeviceType() + ":" + stationId + ":" + pcsList.get(i).getSrcId();
                if (redisService.hasKey(key)) {
                    Map<Object, Object> redisInfo = redisService.hgetall(key);
                    String pcsState = openStationService.getPcsState(redisInfo);
                    DeviceTransfer outputPower = (DeviceTransfer) redisService.hget(key, "outputPower");
                    DeviceTransfer reactivePowerPCS = (DeviceTransfer) redisService.hget(key, "reactivePowerPCS");
                    Date updateTime = (Date) redisService.hget(key, "updateTime");
                    //根据
                    WareHouse wareHouse = null;
                    if (i > len) {
                        wareHouse = new WareHouse();
                        wareHouseList.add(wareHouse);
                    } else {
                        wareHouse = wareHouseList.get(i);
                    }
                    //以pcs最后更新时间为准，当没有pcs时候，使用bms时间
                    wareHouse.setUpdateTime(updateTime);
                    wareHouse.setPcsSrcId(pcsList.get(i).getSrcId());
                    wareHouse.setPcsState(pcsState);
                    //增加电流流向
                    wareHouse.setFlowDirection(pcsList.get(i).getFlowDirection());
                    if (outputPower != null) {
                        wareHouse.setActivePowerPCS(outputPower.getValue());
                    }
                    if (reactivePowerPCS != null) {
                        wareHouse.setReactivePowerPCS(reactivePowerPCS.getValue());
                        bigDecimalUtil.keepTwoDecimalPlaces(wareHouse);
                        bigDecimalUtil.ifIsNUll(wareHouse);
                    }
                }
            }
        }
        return DataResult.success(wareHouseList);
    }

    @PostMapping("/middlePartInverter")
    @ApiOperation(value = "站首页的中间部分-光伏")
    public DataResult<List<Object>> middlePartInverter(@RequestBody StationReq req) {
        List<Object> list = new ArrayList<>();
        Integer stationId = req.getStationId();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setFuzzyDeviceType(DeviceTypeConstant.INVERTER);
        List<DeviceRespVO> deviceList = deviceService.getList(deviceReqVO);
        if (!deviceList.isEmpty()) {
            int len = deviceList.size();
            for (int i = 0; i < len; i++) {
                Map<String, Object> map = new HashMap<>();
                String key = deviceList.get(i).getDeviceType() + ":" + stationId + ":" + deviceList.get(i).getSrcId();
                if (redisService.hasKey(key)) {
                    DeviceTransfer outputPower = (DeviceTransfer) redisService.hget(key, "acActivePower");
                    DeviceTransfer acReactivePower = (DeviceTransfer) redisService.hget(key, "acReactivePower");
                    map.put("acActivePower", outputPower == null ? null : outputPower.getValue());
                    map.put("acReactivePower", acReactivePower == null ? null : acReactivePower.getValue());
                    list.add(map);
                }
            }
        }
        return DataResult.success(list);
    }

    @PostMapping("/circleCtr")
    @ApiOperation(value = "环控")
    public DataResult<List<CircleCtrlResp>> circleCtr(@RequestBody StationReq req) {
        //查站下的温湿度仪器
        List<DeviceRespVO> deviceList = deviceService.getListByDeviceType(req.getStationId(), DeviceTypeConstant.TRANSMITTER);
        deviceList = deviceList.stream().sorted(Comparator.comparing(DeviceRespVO::getPid)).collect(Collectors.toList());
        List<CircleCtrlResp> circleList = openStationService.getCircle(deviceList);

        return DataResult.success(circleList);
    }

    @PostMapping("/getEarnings")
    @ApiOperation(value = "获取电站收益")
    public DataResult<EarningsCalculateCountResp> getEarnings(@RequestBody StationReq req) {
        EarningsCalculateCountResp earningsCount = earningsCalculateService.getEarningsCount(req.getStationId());
        return DataResult.success(earningsCount);
    }

    @PostMapping("/getStationData")
    @ApiOperation(value = "站首页电站数据（光伏日发、总发以及本地负载数据）")
    public DataResult<HomePageStationDataResp> getStationData(@RequestBody StationReq req) {
        HomePageStationDataResp homePageStationData = openStationService.getHomePageStationData(req);
        return DataResult.success(homePageStationData);
    }


    @PostMapping("/incomeData")
    @ApiOperation(value = "充放电差值")
    @TokenIgnore
    public DataResult getPcsIncomeData(@RequestBody PcsStationReq req) {
        return DataResult.success(openStationService.getPcsIncomeData(req));
    }

    @PostMapping("/realTimeIncomeData")
    @ApiOperation(value = "实时充放电差值")
    @TokenIgnore
    public DataResult getPcsRealTimeIncomeData(@RequestBody StationReq req) {
        return DataResult.success(openStationService.getPcsRealTimeIncomeData(req));
    }

    @PostMapping("jobDataManage")
    @TokenIgnore
    public DataResult jobDataManage() {
        openStationService.jobDataManage();
        //15分钟收益计算结束
        return DataResult.success();
    }


}

