package com.ho.business.controller;

import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.service.DeviceService;
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.resp.DeviceRespVO;
import com.ho.business.vo.resp.bozhou.AirBozhouResp;
import com.ho.business.vo.resp.bozhou.BoZhouStationStatus;
import com.ho.business.vo.resp.bozhou.StationDataResp;
import com.ho.business.vo.resp.point.WareHouse;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.BigDecimalUtil;
import com.ho.datacollect.api.constant.DataCollectConstant;
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 java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author fancl
 * @desc: 亳州Controller
 * @date 2023/5/17
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "bozhou")
@Api(tags = "亳州首页")
@Slf4j
@Data
public class BoZhouController {

    @Autowired
    DeviceService deviceService;

    @Autowired
    RedisService redisService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @PostMapping("/status")
    @ApiOperation(value = "站首页的中间部分")
    public DataResult<BoZhouStationStatus> getStatus(@RequestBody StationReq req) {
        Integer stationId = req.getStationId();
        BoZhouStationStatus stationStatus = new BoZhouStationStatus();
        //先查这个站下的PCS
        List<DeviceRespVO> airList = deviceService.getListByDeviceType(req.getStationId(), DeviceTypeConstant.PCS);
        if (airList.isEmpty()) {
            airList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.PCS);
        }
        if (!airList.isEmpty()) {
            DeviceRespVO deviceRespVO = airList.get(0);
            //在缓存里拿映射字段
            String key = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
            stationStatus.setFlowDirection(deviceRespVO.getFlowDirection());
            Map<Object, Object> map = redisService.hgetall(key);
            if (map != null) {
                DeviceTransfer deviceStateStandDeviceTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.deviceStateStand);
                DeviceTransfer runningStateDeviceTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.runningState);
                DeviceTransfer remoteInPlaceDeviceTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.remoteInPlace);
                DeviceTransfer runStateDeviceTransfer = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.runState);
                //停机
                if (runStateDeviceTransfer != null && runStateDeviceTransfer.getValue() != null) {
                    if (BigDecimal.ONE.compareTo(runStateDeviceTransfer.getValue()) == 0) {
                        //
                        stationStatus.setWorkStatus(0);
                    }
                }
                //待机
                if (deviceStateStandDeviceTransfer != null && deviceStateStandDeviceTransfer.getValue() != null) {

                    if (BigDecimal.ONE.compareTo(deviceStateStandDeviceTransfer.getValue()) == 0) {
                        //
                        stationStatus.setWorkStatus(1);
                    }
                }
                //运行
                if (runningStateDeviceTransfer != null && runningStateDeviceTransfer.getValue() != null) {
                    if (BigDecimal.ONE.compareTo(runningStateDeviceTransfer.getValue()) == 0) {
                        //
                        stationStatus.setWorkStatus(2);
                    }
                }

                if (deviceStateStandDeviceTransfer != null && deviceStateStandDeviceTransfer.getValue() != null) {
                    //stationStatus.setDeviceStateStand(deviceStateStandDeviceTransfer.getValue().intValue());
                }

                if (runningStateDeviceTransfer != null && runningStateDeviceTransfer.getValue() != null) {
                    //stationStatus.setOnGrid(onGridDeviceTransfer.getValue().intValue());
                }
                if (remoteInPlaceDeviceTransfer != null && remoteInPlaceDeviceTransfer.getValue() != null) {
                    stationStatus.setRemoteInPlace(remoteInPlaceDeviceTransfer.getValue().intValue());
                }
                //另外4个
                WareHouse bms = getBms(stationId);
                if (bms != null) {
                    BigDecimal soc = bms.getSoc();
                    BigDecimal soh = bms.getSoh();
                    if (soc != null) {
                        String result = String.format("%.3f", soc);
                        stationStatus.setSoc(new BigDecimal(result));
                    }
                    if (soh != null) {
                        String result = String.format("%.3f", soh);
                        stationStatus.setSoh(new BigDecimal(result));
                    }
                }
                DeviceTransfer outputPower = (DeviceTransfer) redisService.hget(key, "outputPower");
                DeviceTransfer reactivePowerPCS = (DeviceTransfer) redisService.hget(key, "reactivePowerPCS");
                if (outputPower != null) {
                    stationStatus.setActivePowerPCS(outputPower.getValue().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                if (reactivePowerPCS != null) {
                    stationStatus.setReactivePowerPCS(reactivePowerPCS.getValue().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
        }

        return DataResult.success(stationStatus);
    }

    @PostMapping("/stationData")
    @ApiOperation(value = "电站数据")
    public DataResult<StationDataResp> stationData(@RequestBody StationReq stationReq) {
        StationDataResp bozhou = new StationDataResp();
        List<DeviceRespVO> deviceList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.PCS);
        //累计充放电量
        List<DeviceRespVO> bmsList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.BMS);

        if (!deviceList.isEmpty()) {
            for (DeviceRespVO deviceRespVO : deviceList) {
                String key = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
                Map<Object, Object> map = redisService.hgetall(key);
                DeviceTransfer allowableChargePower = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ALLOWABLE_CHARGE_POWER);
                DeviceTransfer allowableDischargePower = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ALLOWABLE_DISCHARGE_POWER);
                //DeviceTransfer accumulatedChargePowerLow = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ACCUMULATED_CHARGE_POWER_LOW);
                DeviceTransfer accumulatedChargePowerHigh = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ACCUMULATED_CHARGE_POWER_HIGH);
                //DeviceTransfer accumulatedDischargePowerLow = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ACCUMULATED_DISCHARGE_POWER_LOW);
                DeviceTransfer accumulatedDischargePowerHigh = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.ACCUMULATED_DISCHARGE_POWER_HIGH);

                if (allowableChargePower != null) {
                    bozhou.setAllowableChargePower(allowableChargePower.getValue());
                }
                if (allowableDischargePower != null) {
                    bozhou.setAllowableDischargePower(allowableDischargePower.getValue());
                }
//                if (accumulatedChargePowerLow != null) {
//                    bozhou.setAccumulatedChargePowerLow(accumulatedChargePowerLow.getValue());
//                }
                if (accumulatedChargePowerHigh != null) {
                    bozhou.setAccumulatedChargePowerHigh(accumulatedChargePowerHigh.getValue());
                }
                /*if (accumulatedDischargePowerLow != null) {
                    bozhou.setAccumulatedDischargePowerLow(accumulatedDischargePowerLow.getValue());
                }*/
                if (accumulatedDischargePowerHigh != null) {
                    bozhou.setAccumulatedDischargePowerHigh(accumulatedDischargePowerHigh.getValue());
                }
                //有功,无功
                DeviceTransfer outputPower = (DeviceTransfer) map.get("outputPower");
                DeviceTransfer reactivePowerPCS = (DeviceTransfer) map.get("reactivePowerPCS");
                if(outputPower!=null){
                    bozhou.setOutputPower(outputPower.getValue());
                }
                if(reactivePowerPCS!=null){
                    bozhou.setReactivePowerPCS(reactivePowerPCS.getValue());
                }
            }
        }
        //累计充放电
        if (!bmsList.isEmpty()) {
            DeviceRespVO deviceRespVO = bmsList.get(0);
            //累计充放电
            String key = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                DeviceTransfer totalCharge = (DeviceTransfer) redisService.hget(key, "totalCharge");
                DeviceTransfer totalDischarge = (DeviceTransfer) redisService.hget(key, "totalDischarge");
                if (totalCharge != null) {
                    BigDecimal value = totalCharge.getValue();
                    if (value.compareTo(BigDecimal.ZERO) < 0) {
                        value = new BigDecimal(65536).add(value);
                    }
                    bozhou.setAccumulatedChargePowerLow(value);
                }
                if (totalDischarge != null) {
                    BigDecimal value = totalDischarge.getValue();
                    if (value.compareTo(BigDecimal.ZERO) < 0) {
                        value = new BigDecimal(65536).add(value);
                    }
                    bozhou.setAccumulatedDischargePowerLow(value);
                }
                DeviceTransfer soc = (DeviceTransfer) redisService.hget(key, "soc");
                if(soc!=null){
                    bozhou.setSoc(soc.getValue());
                }
            }

        }
        deviceList = deviceService.getListByDeviceType(stationReq.getStationId(), DeviceTypeConstant.ELE_METER);
        if (!deviceList.isEmpty()) {
            for (DeviceRespVO deviceRespVO : deviceList) {
                String key = deviceRespVO.getDeviceType() + ":" + deviceRespVO.getStationId() + ":" + deviceRespVO.getSrcId();
                Map<Object, Object> map = redisService.hgetall(key);
                DeviceTransfer gridF = (DeviceTransfer) map.get(DataCollectConstant.PCS_POINT.GRID_F);
                if (gridF != null) {
                    bozhou.setGridF(gridF.getValue());
                }
            }
        }
        bigDecimalUtil.keepDecimalPlaces(bozhou, 3);
        return DataResult.success(bozhou);
    }

    @PostMapping("/airCondition")
    @ApiOperation(value = "空调")
    public DataResult<AirBozhouResp> airCondition(@RequestBody StationReq stationReq) {
        AirBozhouResp bozhou = new AirBozhouResp();
        Integer stationId = stationReq.getStationId();
        //先查这个站下的空调
        List<DeviceRespVO> airList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.AIR_CONDITION);
        if (!airList.isEmpty()) {
            DeviceRespVO deviceRespVO = airList.get(0);
            //在缓存里拿映射字段
            String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                Map<Object, Object> infos = redisService.hgetall(key);
                //分别拿8个字段
                //空调室内温度
                DeviceTransfer airconditionInnerTemperature = (DeviceTransfer) infos.get("airconditionInnerTemperature");
                BigDecimal airconditionInnerTemperatureBig = BigDecimal.ZERO;
                if (airconditionInnerTemperature != null) {
                    airconditionInnerTemperatureBig = airconditionInnerTemperature.getValue();
                    if (airconditionInnerTemperatureBig != null) {
                        String result = String.format("%.2f", airconditionInnerTemperatureBig);
                        airconditionInnerTemperatureBig = new BigDecimal(result);
                    }
                }
                bozhou.setAirconditionInnerTemperature(airconditionInnerTemperatureBig);
                //空调冷凝/环境温度
                DeviceTransfer airconditionEnvTemperature = (DeviceTransfer) infos.get("airconditionEnvTemperature");
                BigDecimal airconditionEnvTemperatureBig = BigDecimal.ZERO;
                if (airconditionEnvTemperature != null) {
                    airconditionEnvTemperatureBig = airconditionEnvTemperature.getValue();
                    if (airconditionEnvTemperatureBig != null) {
                        String result = String.format("%.2f", airconditionEnvTemperatureBig);
                        airconditionEnvTemperatureBig = new BigDecimal(result);
                    }
                }
                bozhou.setAirconditionEnvTemperature(airconditionEnvTemperatureBig);
                //空调冷凝风机输出/加湿器输出
                DeviceTransfer airconditionHumidifierOutput = (DeviceTransfer) infos.get("airconditionHumidifierOutput");
                BigDecimal airconditionHumidifierOutputBig = BigDecimal.ZERO;
                if (airconditionHumidifierOutput != null) {
                    airconditionHumidifierOutputBig = airconditionHumidifierOutput.getValue();
                }
                bozhou.setAirconditionHumidifierOutput(airconditionHumidifierOutputBig);
                //空调蒸发温度
                DeviceTransfer airconditionEvaporateTemperature = (DeviceTransfer) infos.get("airconditionEvaporateTemperature");
                BigDecimal airconditionEvaporateTemperatureBig = BigDecimal.ZERO;
                if (airconditionEvaporateTemperature != null) {
                    airconditionEvaporateTemperatureBig = airconditionEvaporateTemperature.getValue();
                    if (airconditionEvaporateTemperatureBig != null) {
                        String result = String.format("%.2f", airconditionEvaporateTemperatureBig);
                        airconditionEvaporateTemperatureBig = new BigDecimal(result);
                    }
                }
                bozhou.setAirconditionEvaporateTemperature(airconditionEvaporateTemperatureBig);
                //空调除湿温度
                DeviceTransfer airconditionDehumidificateTemperature = (DeviceTransfer) infos.get("airconditionDehumidificateTemperature");
                BigDecimal airconditionDehumidificateTemperatureBig = BigDecimal.ZERO;
                if (airconditionDehumidificateTemperature != null) {
                    airconditionDehumidificateTemperatureBig = airconditionDehumidificateTemperature.getValue();
                }
                bozhou.setAirconditionDehumidificateTemperature(airconditionDehumidificateTemperatureBig);
                //空调室内湿度
                DeviceTransfer airconditionInnerHumidity = (DeviceTransfer) infos.get("airconditionInnerHumidity");
                BigDecimal airconditionInnerHumidityBig = BigDecimal.ZERO;
                if (airconditionInnerHumidity != null) {
                    airconditionInnerHumidityBig = airconditionInnerHumidity.getValue();

                }
                bozhou.setAirconditionInnerHumidity(airconditionInnerHumidityBig);
                //空调湿度回差
                DeviceTransfer airconditionReturnHumidity = (DeviceTransfer) infos.get("airconditionReturnHumidity");
                BigDecimal airconditionReturnHumidityBig = BigDecimal.ZERO;
                if (airconditionReturnHumidity != null) {
                    airconditionReturnHumidityBig = airconditionReturnHumidity.getValue();
                }
                bozhou.setAirconditionReturnHumidity(airconditionReturnHumidityBig);
                //空调湿度设定
                DeviceTransfer airconditionSetHumidity = (DeviceTransfer) infos.get("airconditionSetHumidity");
                BigDecimal airconditionSetHumidityBig = BigDecimal.ZERO;
                if (airconditionSetHumidity != null) {
                    airconditionSetHumidityBig = airconditionSetHumidity.getValue();
                }
                bozhou.setAirconditionSetHumidity(airconditionSetHumidityBig);
                //空调温度设定
                DeviceTransfer airconditionSetTemperature = (DeviceTransfer) infos.get("airconditionSetTemperature");
                BigDecimal airconditionSetTemperatureBig = BigDecimal.ZERO;
                if (airconditionSetTemperature != null) {
                    airconditionSetTemperatureBig = airconditionSetTemperature.getValue();
                }
                bozhou.setAirconditionSetTemperature(airconditionSetTemperatureBig);
            }
        }
        //返回值的BigDecimal类型保留两位小数
       /* for (AppRealTimeCurveRespVo realTimeCurveRespVo : resList) {
            bigDecimalUtil.keepTwoDecimalPlaces(realTimeCurveRespVo);
            bigDecimalUtil.ifIsNUll(realTimeCurveRespVo);
        }*/
        return DataResult.success(bozhou);
    }


    //BMS值 SOC,SOH
    private WareHouse getBms(Integer stationId) {
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        List<DeviceRespVO> bmsList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.BMS);
        if (bmsList.isEmpty()) {
            bmsList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.BMS);
        }
        WareHouse wareHouse = new WareHouse();
        if (!bmsList.isEmpty()) {
            DeviceRespVO deviceRespVO = bmsList.get(0);
            String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                wareHouse.setBmsSrcId(deviceRespVO.getSrcId());
                DeviceTransfer soc = (DeviceTransfer) redisService.hget(key, "soc");
                DeviceTransfer soh = (DeviceTransfer) redisService.hget(key, "soh");
                if (soc != null) {
                    wareHouse.setSoc(soc.getValue());
                }
                if (soh != null) {
                    wareHouse.setSoh(soh.getValue());
                }
            }
        }
        return wareHouse;
    }

}
