package com.ho.business.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.Station;
import com.ho.business.service.CabinService;
import com.ho.business.service.DeviceService;
import com.ho.business.service.StationHomeService;
import com.ho.business.service.StationService;
import com.ho.business.vo.DeviceTransfer;
import com.ho.business.vo.req.MonitorQuery;
import com.ho.business.vo.req.device.DeviceTreeReq;
import com.ho.business.vo.req.point.PointReqVO;
import com.ho.business.vo.resp.AppRealTimeCurveRespVo;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.cabin.*;
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.vo.req.PointData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
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.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author fancl
 * @desc: 仓
 * @date 2023/5/5
 */
@RequestMapping(ContextConstant.BUSINESS + "station")
@RestController
@Api(tags = "舱堆簇包-舱")
@Slf4j
public class CabinController {

    @Autowired
    RedisService redisService;

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @Autowired
    StationHomeService stationHomeService;
    @Autowired
    DeviceService deviceService;

    @Autowired
    CabinService cabinService;

    @Autowired
    StationService stationService;

    @PostMapping("leftPanel")
    @ApiOperation(value = "左侧主面板")
    public DataResult<LeftPanel> leftPanel(@RequestBody @Valid PointReqVO reqVO) {
        LeftPanel leftPanel = new LeftPanel();
        Integer stationId = reqVO.getStationId();
        //查电站数据
        Station station = stationService.selectById(stationId);
        if (station == null) {
            return DataResult.success(leftPanel);
        }
        //舱装机容量和额定功率 是 总值/舱个数
        Integer cabinNum = station.getCabinNum();
        if (cabinNum != null && cabinNum != 0) {
            BigDecimal capacity = station.getCapacity();

            BigDecimal ratePower = station.getRatePower();
            BigDecimal cap = capacity.divide(new BigDecimal(cabinNum), 2, BigDecimal.ROUND_HALF_UP);
            //BigDecimal rate = ratePower.divide(new BigDecimal(cabinNum), 2, BigDecimal.ROUND_HALF_UP);
            leftPanel.setCapacity(cap);
            //leftPanel.setAcPower(rate);
        }
        //根据设备pid查询下面的温度
        List<DeviceRespVO> list = deviceService.getListByDeviceTypeAndPid(reqVO.getStationId(), reqVO.getSrcId(), DeviceTypeConstant.PCS);
        if (!list.isEmpty()) {
            DeviceRespVO deviceRespVO = list.get(0);
            String key = deviceRespVO.getDeviceType() + ":" + stationId + ":" + deviceRespVO.getSrcId();
            if (redisService.hasKey(key)) {
                DeviceTransfer deviceTransfer = (DeviceTransfer) redisService.hget(key, "outputPower");
                if (deviceTransfer != null) {
                    BigDecimal value = deviceTransfer.getValue();
                    leftPanel.setAcPower(value);
                }
            }
        }
        //日充日放等
        LeftPanel leftPanelCharge = cabinService.powerGeneration(stationId, reqVO.getSrcId());

        if( leftPanelCharge != null ){
            leftPanel.setDayCharge(leftPanelCharge.getDayCharge());
            leftPanel.setDayDischarge(leftPanelCharge.getDayDischarge());
            leftPanel.setMonthCharge(leftPanelCharge.getMonthCharge() == null ? BigDecimal.ZERO.add(leftPanelCharge.getDayCharge()) : leftPanelCharge.getMonthCharge().add(leftPanelCharge.getDayCharge()));
            leftPanel.setMonthDischarge(leftPanelCharge.getMonthDischarge() == null ? BigDecimal.ZERO.add(leftPanelCharge.getDayDischarge()) : leftPanelCharge.getMonthDischarge().add(leftPanelCharge.getDayDischarge()));
            leftPanel.setYearCharge(leftPanelCharge.getYearCharge());
            leftPanel.setYearDischarge(leftPanelCharge.getYearDischarge());
            leftPanel.setTotalCharge(leftPanelCharge.getTotalCharge());
            leftPanel.setTaotalDischarge(leftPanelCharge.getTaotalDischarge());
            leftPanel.setCumulatedCharge(leftPanelCharge.getTotalCharge());
            leftPanel.setCumulatedDischarge(leftPanelCharge.getTaotalDischarge());
        }
        return DataResult.success(leftPanel);
    }

    @PostMapping("chargeCurve")
    @ApiOperation(value = "充放电曲线,近一年,按天")
    public DataResult<List<ChargeDischarge>> elecPriceCurve(@RequestBody @Valid PointReqVO reqVO) {
        Integer stationId = reqVO.getStationId();
        log.info("stationId:{}, srcId:{}", stationId, reqVO.getSrcId());
        //从elec_meter_value取值
        //数据加工是按照BSM维度进行的,先查这个设备下的BMS
        //计算今天和一年前的日期
        Date date = new Date();
        String now = DateUtil.format(date, CommonConstant.DATE_YMD);
        DateTime oneYearBeforeDateTime = DateUtil.offsetDay(date, -365);
        //一年前作为开始日期,今天作为结束日期
        String begin = DateUtil.format(oneYearBeforeDateTime, CommonConstant.DATE_YMD);
        List<ChargeDischarge> chargeList = cabinService.getChargeList(stationId, reqVO.getSrcId(), begin, now);
        return DataResult.success(chargeList);
    }


    @PostMapping("socCurve")
    @ApiOperation(value = "SOC曲线,近24小时")
    public DataResult<List<PointData>> socCurve(@RequestBody @Valid PointReqVO reqVO) {
        List<PointData> list = new ArrayList<>();
        //当前时间往前取24小时
        List<String> houres24 = (List<String>) redisService.get(RedisKeyConstant.SIXTY_MINUTE_INTERVAL);
        return DataResult.success(list);
    }


    @PostMapping("/powerCurve")
    @ApiOperation(value = "功率曲线")
    public DataResult<List<AppRealTimeCurveRespVo>> powerCurve(@RequestBody MonitorQuery monitorQuery) {
        List<AppRealTimeCurveRespVo> resList = stationHomeService.getPowerCurve(monitorQuery);

        //返回值的BigDecimal类型保留两位小数
        for (AppRealTimeCurveRespVo realTimeCurveRespVo : resList) {
            bigDecimalUtil.keepTwoDecimalPlaces(realTimeCurveRespVo);
            bigDecimalUtil.ifIsNUll(realTimeCurveRespVo);
        }
        return DataResult.success(resList);
    }

    @ApiOperation(value = "温度电压正太分布")
    @PostMapping("temperatureVoltageData")
    public DataResult<TemperatureVoltageResp> temperatureVoltageData(@RequestBody DeviceTreeReq vo, HttpServletRequest request) {
        vo.setLang(request.getHeader(CommonConstant.LANG));
        TemperatureVoltageResp temperatureVoltageData = deviceService.getTemperatureVoltageData(vo);
        return DataResult.success(temperatureVoltageData);
    }

    //温湿度  （抽样）
    @PostMapping("/temperatureHumidityCurve")
    @ApiOperation(value = "温湿度曲线")
    @Cacheable(cacheManager = "towMinuteCacheManager", value = "temperatureHumidityCurve", key = "#monitorQuery.stationId+'_'+#monitorQuery.srcId+'_'+#monitorQuery.sampleTime", sync = true)
    public DataResult<List<TemperatureHumidityResp>> temperatureHumidityCurve(@RequestBody MonitorQuery monitorQuery) {
        List<TemperatureHumidityResp> resList = stationHomeService.getTemperatureHumidityCurve(monitorQuery);
        //返回值的BigDecimal类型保留两位小数
        for (TemperatureHumidityResp temperatureHumidityResp : resList) {
            List<TemperatureValue> list = temperatureHumidityResp.getList();
            //改为使用
            for (TemperatureValue temperatureValue : list) {
                BigDecimal temperature = temperatureValue.getTemperature();
                BigDecimal humidity = temperatureValue.getHumidity();
                if (temperature != null) {
                    String result = String.format("%.3f", temperature);
                    temperatureValue.setTemperature(new BigDecimal(result));;
                }
                if (humidity != null) {
                    String result = String.format("%.3f", humidity);
                    temperatureValue.setHumidity(new BigDecimal(result));;
                }
                //bigDecimalUtil.keepTwoDecimalPlaces(temperatureValue);
                //bigDecimalUtil.ifIsNUll(temperatureValue);
            }
        }
        return DataResult.success(resList);
    }

    @PostMapping("/auxPowerCurve")
    @ApiOperation(value = "辅助功率曲线")
    public DataResult<List<PointData>> auxPowerCurve(@RequestBody MonitorQuery monitorQuery) {
        List<PointData> auxPower = cabinService.getAuxPower(monitorQuery.getStationId(), monitorQuery.getSrcId());
        for (PointData pointData : auxPower) {
            bigDecimalUtil.keepTwoDecimalPlaces(pointData);
        }
        return DataResult.success(auxPower);
    }

}
