package com.jiayue.ipp.idp.api;

import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.jiayue.ipp.common.data.entity.ForecastPowerShortTerm;
import com.jiayue.ipp.common.data.entity.PowerStationStatusData;
import com.jiayue.ipp.common.data.entity.SysParameter;
import com.jiayue.ipp.idp.dto.EnergyMeterData;
import com.jiayue.ipp.idp.dto.ResponsePowerData;
import com.jiayue.ipp.idp.service.*;
import com.jiayue.ipp.idp.util.JsonBeanUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 超短期数据
 *
 * @Author: tl
 * @Date: 2023/3/28 0028 13:16
 */
@Service
@Slf4j
@AllArgsConstructor
public class CallPowerStationStatusDataApi {

    ForecastPowerUltraShortTermService forecastPowerUltraShortTermService;

    ForecastPowerShortTermService forecastPowerShortTermService;

    PowerStationStatusDataService powerStationStatusDataService;

    ElectricFieldService electricFieldService;

    SysParameterService sysParameterService;

    public void packageData() throws Exception {

        List<PowerStationStatusData> powerStationStatusDataList = new ArrayList<>();
        electricFieldService.list().forEach(e -> {

            try {
                log.info("实际功率==》{}", e.getStationCode());
                PowerStationStatusData powerStationStatusData = new PowerStationStatusData();

                //设定容量
                powerStationStatusData.setCapacity(e.getCapacity());

                Long time = System.currentTimeMillis();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time - time % 60000), ZoneId.systemDefault());
                powerStationStatusData.setTime(localDateTime);
                powerStationStatusData.setStationCode(e.getStationCode());
                //设定开机容量为装机容量
                powerStationStatusData.setOpenCapacity(e.getCapacity());
                powerStationStatusData.setStationCode(e.getStationCode());

                getRealPowerVal(powerStationStatusData);


                //临时
//                List<ForecastPowerShortTerm> forecastPowerShortTerms = forecastPowerShortTermService.findByStationCodeAndStartTimeAndEndTime(e.getStationCode(),new Date(System.currentTimeMillis()-15*60000),new Date(System.currentTimeMillis()));
//
//                if(forecastPowerShortTerms.size()>0){
//                    powerStationStatusData.setRealValue(forecastPowerShortTerms.get(0).getFpValue().multiply(new BigDecimal(Math.random() * 0.7 + 0.8)));
//                    powerStationStatusData.setAbleValue(powerStationStatusData.getRealValue().add(new BigDecimal(0.1)));
//


                //设定 样板机参照功率
                if (powerStationStatusData.getOpenCapacity().compareTo(new BigDecimal(0)) != 0) {
                    //设置理论功率
                    powerStationStatusData.setTheoryValue(powerStationStatusData.getAbleValue().multiply(BigDecimal.ONE.add(getMagnificationK())).setScale(2, RoundingMode.HALF_DOWN));
                } else {
                    powerStationStatusData.setTheoryValue(new BigDecimal(0));
                }


                if (powerStationStatusData.getAbleValue().compareTo(BigDecimal.valueOf(-99)) == 0) {
                    powerStationStatusData.setAbleValue(powerStationStatusData.getRealValue());
                    powerStationStatusData.setTheoryValue(powerStationStatusData.getAbleValue());
                } else {
                    if (powerStationStatusData.getAbleValue().compareTo(powerStationStatusData.getRealValue()) < 0) {
                        powerStationStatusData.setAbleValue(powerStationStatusData.getRealValue().multiply(getMagnificationK().add(BigDecimal.ONE)).setScale(2, RoundingMode.HALF_DOWN));
                    }
                    if (powerStationStatusData.getTheoryValue().compareTo(powerStationStatusData.getAbleValue()) < 0) {
                        powerStationStatusData.setTheoryValue(powerStationStatusData.getAbleValue().multiply(getMagnificationK().add(BigDecimal.ONE)).setScale(2, RoundingMode.HALF_DOWN));
                    }
                }

                powerStationStatusDataList.add(powerStationStatusData);
//                }

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

        powerStationStatusDataService.saveBatch(powerStationStatusDataList);
    }


    /**
     * 获取0.015 - 0.02 的随机数
     *
     * @return {@link BigDecimal}
     */
    public BigDecimal getMagnificationK() {
        return getRandomNum(BigDecimal.valueOf(0.015), BigDecimal.valueOf(0.02));
    }

    /**
     * 得到随机num
     *
     * @param min 最小值
     * @param max 最大值
     * @return {@link BigDecimal}
     */
    public BigDecimal getRandomNum(BigDecimal min, BigDecimal max) {
        return BigDecimal.valueOf(random.nextDouble()).multiply(max.subtract(min)).add(min).setScale(2, RoundingMode.HALF_DOWN);
    }

    private static final Random random = new Random();


    public LocalDateTime timestamToDatetime(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }


    /**
     * 根据实际功率是否需要审核  返回实际功率
     *
     * @return 实际功率数值
     */
//    @SneakyThrows
    public void getRealPowerVal(PowerStationStatusData powerStationStatusData) {

        String url = sysParameterService.getSysParameterAndStationCode("get_power_url", "null", powerStationStatusData.getStationCode());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long now = System.currentTimeMillis();
        if (!url.equals("null")) {

            HttpResponse response = null;
            try {
                // 构造请求对象
                HttpRequest request = HttpRequest.get(url);

                request.setConnectionTimeout(5000);
                // 发送请求并获取响应对象
                response = request.execute();

                log.info("接口获取实际功率:接收到{}", response.body());
                ResponsePowerData responsePowerData = JsonBeanUtil.jsonToBeans("[" + response.body() + "]", ResponsePowerData.class).get(0);

                powerStationStatusData.setJsonText(response.body());

                long time = responsePowerData.getTimeStamp() * 1000;
                powerStationStatusData.setTime(timestamToDatetime(time - (time % 60000)));
//                List<EnergyMeterData> mainTransformerDatas = responsePowerData.getMainTransformerData();

//                List<EnergyMeterData> storedEnergyDatas = responsePowerData.getStoredEnergyData();

                List<EnergyMeterData> collectorSlipperDatas = responsePowerData.getCollectorSlipperData();


//                //求和
                double sum = 0;
                if (collectorSlipperDatas.size() > 0)
                    sum = collectorSlipperDatas.stream()
                            .mapToDouble(data -> Double.parseDouble(data.getPower()))
                            .sum();
//                if(mainTransformerDatas.size()>0)
//                    sum = mainTransformerDatas.stream()
//                            .mapToDouble(data -> Double.parseDouble(data.getPower()))
//                            .sum();

//                if(storedEnergyDatas.size()>0)
//                    sum = sum - storedEnergyDatas.stream()
//                            .mapToDouble(data -> Double.parseDouble(data.getPower()))
//                            .sum();

                log.info("接口获取实际功率:接口获取实际功率，实际功率：{}", sum);

//                if (now / 60000 != responsePowerData.getTimeStamp()*1000 / 60000) {
//
////                    String formatDate = simpleDateFormat.format(responsePowerData.getTimeStamp());
//                    String[] cmd = {"/bin/sh", "-c", "sudo date -s '" + formatDate + "'"};
//                    String str = RuntimeUtil.execForStr(cmd);
//
//                    log.info("接口获取实际功率:服务器对时成功,be：{}，af：{}", simpleDateFormat.format(now), str);
//
//                } else {
//                    log.info("接口获取实际功率：时间一致，无需对时");
//                }

                //设定实际功率
                powerStationStatusData.setRealValue(new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP));

            } catch (Exception e) {
                log.info("接口获取实际功率:实际功率接口过程发生异常", e);
                powerStationStatusData.setTime(LocalDateTime.now());
                //设定实际功率
                powerStationStatusData.setRealValue(BigDecimal.valueOf(-99D));
            } finally {
                response.close();
            }
        } else {
            powerStationStatusData.setTime(timestamToDatetime(now));
            //设定实际功率
            powerStationStatusData.setRealValue(BigDecimal.valueOf(-99D));
        }


    }

}
