package com.xhpc.pp.logic;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.common.api.PileOrderService;
import com.xhpc.common.data.redis.CacheBmsReqChargerOutputData;
import com.xhpc.common.data.up.BmsReqChargerOutputData;
import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.pp.mapper.XhpcDeviceMessageMapper;
import com.xhpc.pp.tx.ServiceParameter;
import com.xhpc.pp.tx.ServiceResult;
import com.xhpc.pp.tx.logic.ServiceLogic;
import com.xhpc.pp.utils.BMSCurrentParser;
import com.xhpc.pp.utils.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;

@Lazy
@Component("BmsReqChargerOutputDataLogic")
public class BmsReqChargerOutputDataLogic implements ServiceLogic {

    private static final Logger log = LoggerFactory.getLogger(BmsReqChargerOutputDataLogic.class);
    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

    @Resource
    PileOrderService pileOrderService;

    @Override
    public ServiceResult service(ServiceParameter sp) throws Exception {

        Map<String, Object> req = sp.getParameters();
        ObjectMapper objectMapper = new ObjectMapper();
        BmsReqChargerOutputData orderData = objectMapper.convertValue(req, BmsReqChargerOutputData.class);


        String hex = (String) req.get("hex");
        int idxStart = 60;
        int bmsVoltageRequest = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//BMS 电压需求

        idxStart = 4 + idxStart;
        double bmsCurrentRequest = BMSCurrentParser.parseBmsCurrent(hex.substring(idxStart, 4 + idxStart),400);
        //int bmsCurrentRequest = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//BMS 电流需求
        idxStart = 6 + idxStart;

        int bmsChargingVolt = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//BMS 充电电压测量值
        idxStart = 4 + idxStart;


        double bmsChargingCurrent = BMSCurrentParser.parseBmsCurrent(hex.substring(idxStart, 4 + idxStart),400);
        idxStart = 88;

        int pileVoltageOutput = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//电桩电压输出值
        idxStart = 4 + idxStart;
        double pileCurrentOutput = BMSCurrentParser.parseBmsCurrent(hex.substring(idxStart, 4 + idxStart),400);//电桩电流输出值

        String orderNo = (String) req.get("orderNo");
        String orderKey = "order:".concat(orderNo).concat(".bms");


        orderData.setBmsVoltageRequest(bmsVoltageRequest+"");
        orderData.setBmsCurrentRequest(bmsCurrentRequest+"");

        orderData.setBmsChargingVolt(bmsChargingVolt+"");
        orderData.setBmsChargingCurrent(bmsChargingCurrent+"");

        orderData.setPileVoltageOutput(pileVoltageOutput+"");
        orderData.setPileCurrentOutput(pileCurrentOutput+"");

        //CacheBmsReqChargerOutputData cacheBmsReqChargerOutputData = translate(orderData);

        CacheBmsReqChargerOutputData cacheBmsReqChargerOutputData = new CacheBmsReqChargerOutputData();

        cacheBmsReqChargerOutputData.setOrderNo(orderData.getOrderNo());
        cacheBmsReqChargerOutputData.setPileNo(orderData.getPileNo());
        cacheBmsReqChargerOutputData.setGunId(orderData.getGunId());
        cacheBmsReqChargerOutputData.setBmsVoltageRequest(new BigDecimal(bmsVoltageRequest).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());
//        try{
//            BigDecimal subtract1 = new BigDecimal(bmsCurrentRequest).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
//            if(subtract1.compareTo(new BigDecimal(0))<0){
//                subtract1 =subtract1.abs();
//            }
//            cacheBmsReqChargerOutputData.setBmsCurrentRequest(subtract1.doubleValue());
//        }catch (Exception e){
//
//        }
        cacheBmsReqChargerOutputData.setBmsCurrentRequest(new BigDecimal(orderData.getBmsCurrentRequest()).abs().setScale(2,RoundingMode.DOWN).doubleValue());
        cacheBmsReqChargerOutputData.setBmsChargingMod(HexUtils.reverseHexInt(orderData.getBmsChargingMod()));
        cacheBmsReqChargerOutputData.setBmsChargingVolt(new BigDecimal(bmsChargingVolt).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());

//        try{
//            BigDecimal subtract2 = new BigDecimal(bmsChargingCurrent).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
//            if(subtract2.compareTo(new BigDecimal(0))<0){
//                subtract2 =subtract2.abs();
//            }
//            cacheBmsReqChargerOutputData.setBmsChargingCurrent(subtract2.doubleValue());
//
//        }catch (Exception e){
//
//        }
        cacheBmsReqChargerOutputData.setBmsChargingCurrent(new BigDecimal(orderData.getBmsChargingCurrent()).abs().setScale(2,RoundingMode.DOWN).doubleValue());
        cacheBmsReqChargerOutputData.setMonoBatteryVolt(convertDouble(Integer.parseInt(orderData.getMonoBatteryVoltGroupId().substring(0, 3), 16) * 0.01));
        cacheBmsReqChargerOutputData.setSoc(HexUtils.reverseHexInt(orderData.getSoc()));
        cacheBmsReqChargerOutputData.setBmsEstRemainingTime(HexUtils.reverseHexInt(orderData.getBmsEstRemainingTime()));
        cacheBmsReqChargerOutputData.setPileVoltageOutput(new BigDecimal(pileVoltageOutput).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());
//        try{
//
//            BigDecimal subtract = new BigDecimal(pileCurrentOutput).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
//            if(subtract.compareTo(new BigDecimal(0))<0){
//                subtract =subtract.abs();
//            }
//            cacheBmsReqChargerOutputData.setPileCurrentOutput(subtract.doubleValue());
//        }catch (Exception e){
//
//        }
        cacheBmsReqChargerOutputData.setPileCurrentOutput(new BigDecimal(orderData.getPileCurrentOutput()).abs().setScale(2,RoundingMode.DOWN).doubleValue());
        cacheBmsReqChargerOutputData.setChargingTimeSummary(HexUtils.reverseHexInt(orderData.getChargingTimeSummary()));
        cacheBmsReqChargerOutputData.setMonoBatteryVoltGroupId(Integer.parseInt(orderData.getMonoBatteryVoltGroupId().substring(3), 16));
        cacheBmsReqChargerOutputData.setHex(orderData.getHex());
        cacheBmsReqChargerOutputData.setCreateTime(DateUtil.now());


        REDIS.setCacheObject(orderKey, cacheBmsReqChargerOutputData);
        pileOrderService.pileRimeOrderBms(orderNo);

        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(sp.getPileNo());
        deviceMessage.setRemark("充电桩与 BMS 充电过程 BMS 需求、充电机输出");
        deviceMessage.setStatus(0);
        deviceMessage.setContent((String) req.get("hex"));
        deviceMessage.setChargeOrderNo((String) req.get("orderNo"));
        deviceMessageMapper.insertByDomain(deviceMessage);

        return new ServiceResult(false);
    }


    private CacheBmsReqChargerOutputData translate(BmsReqChargerOutputData orderData) {
        CacheBmsReqChargerOutputData cacheBmsReqChargerOutputData = new CacheBmsReqChargerOutputData();
        cacheBmsReqChargerOutputData.setOrderNo(orderData.getOrderNo());
        cacheBmsReqChargerOutputData.setPileNo(orderData.getPileNo());
        cacheBmsReqChargerOutputData.setGunId(orderData.getGunId());
        cacheBmsReqChargerOutputData.setBmsVoltageRequest(new BigDecimal(orderData.getBmsVoltageRequest()).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());
        try{
            BigDecimal subtract1 = new BigDecimal(orderData.getBmsCurrentRequest()).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
            if(subtract1.compareTo(new BigDecimal(0))<0){
                subtract1 =subtract1.abs();
            }
            cacheBmsReqChargerOutputData.setBmsCurrentRequest(subtract1.doubleValue());
        }catch (Exception e){

        }
        cacheBmsReqChargerOutputData.setBmsChargingMod(HexUtils.reverseHexInt(orderData.getBmsChargingMod()));
        cacheBmsReqChargerOutputData.setBmsChargingVolt(new BigDecimal(orderData.getBmsChargingVolt()).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());

        try{
            BigDecimal subtract2 = new BigDecimal(orderData.getBmsChargingCurrent()).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
            if(subtract2.compareTo(new BigDecimal(0))<0){
                subtract2 =subtract2.abs();
            }
            cacheBmsReqChargerOutputData.setBmsChargingCurrent(subtract2.doubleValue());

        }catch (Exception e){

        }

        cacheBmsReqChargerOutputData.setMonoBatteryVolt(convertDouble(Integer.parseInt(orderData.getMonoBatteryVoltGroupId().substring(0, 3), 16) * 0.01));
        cacheBmsReqChargerOutputData.setSoc(HexUtils.reverseHexInt(orderData.getSoc()));
        cacheBmsReqChargerOutputData.setBmsEstRemainingTime(HexUtils.reverseHexInt(orderData.getBmsEstRemainingTime()));
        cacheBmsReqChargerOutputData.setPileVoltageOutput(new BigDecimal(orderData.getPileVoltageOutput()).divide(new BigDecimal(10),BigDecimal.ROUND_DOWN).doubleValue());
        try{

            BigDecimal subtract = new BigDecimal(orderData.getPileCurrentOutput()).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
            if(subtract.compareTo(new BigDecimal(0))<0){
                subtract =subtract.abs();
            }
            cacheBmsReqChargerOutputData.setPileCurrentOutput(subtract.doubleValue());
        }catch (Exception e){

        }
        cacheBmsReqChargerOutputData.setChargingTimeSummary(HexUtils.reverseHexInt(orderData.getChargingTimeSummary()));
        cacheBmsReqChargerOutputData.setMonoBatteryVoltGroupId(Integer.parseInt(orderData.getMonoBatteryVoltGroupId().substring(3), 16));
        cacheBmsReqChargerOutputData.setHex(orderData.getHex());
        cacheBmsReqChargerOutputData.setCreateTime(DateUtil.now());
        return cacheBmsReqChargerOutputData;
    }


    private Double convertDouble(Double oldVar) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        nf.setGroupingUsed(false);
        return Double.parseDouble(nf.format(oldVar));
    }


    public static void main(String[] args) {

        String hex = "6830EA070023808360001500010224080715153706848083600015000102D80EAC0D028E0D150E5001334B00A50D1A0E2D0081DD";
        int idxStart = 60;

        int bmsVoltageRequest = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//BMS 电压需求
        // System.out.println("===================bmsVoltageRequest========================="+bmsVoltageRequest);

        idxStart =idxStart+4;
        int bmsCurrentRequest = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//BMS 电流需求
//System.out.println("===================bmsCurrentRequest========================="+bmsCurrentRequest);
        idxStart = 88;

        int pileVoltageOutput = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//电桩电压输出值
        // System.out.println("===================pileVoltageOutput========================="+pileVoltageOutput);
        idxStart = 4 + idxStart;
        int pileCurrentOutput = HexUtils.reverseHexInt(hex.substring(idxStart, 4 + idxStart));//电桩电流输出值
        // System.out.println("===================pileCurrentOutput========================="+pileCurrentOutput);



        BigDecimal subtract1 = new BigDecimal(bmsCurrentRequest).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
        if(subtract1.compareTo(new BigDecimal(0))<0){
            subtract1 =subtract1.abs();
        }
        // System.out.println("===================subtract1========================="+subtract1);
        BigDecimal subtract = new BigDecimal(2905).divide(new BigDecimal(10), BigDecimal.ROUND_DOWN).subtract(new BigDecimal(400));
        if(subtract.compareTo(new BigDecimal(0))<0){
            subtract =subtract.abs();
        }
        // System.out.println("===================subtract========================="+subtract);


        String bmsData = "4A09"; // 从BMS获取的实际数据
        double current = BMSCurrentParser.parseBmsCurrent(bmsData,400);
        System.out.println("BMS电流需求: " + current + " A");


        int t1 = HexUtils.reverseHexInt("B014");//电桩电流输出值
        System.out.println("BMS电压: " + t1 + " v");


        String bmsData1 = "8409"; // 从BMS获取的实际数据
        double current1 = BMSCurrentParser.parseBmsCurrent(bmsData1,400);
        System.out.println("BMS电流需求: " + current1 + " A");
    }
}
