package com.jsowell.netty.handler;

import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import com.jsowell.common.core.domain.ykc.YKCFrameTypeCode;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.netty.factory.YKCOperateFactory;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.StationSettingRelation;
import com.jsowell.pile.domain.ThirdPartySettingInfo;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IStationSettingRelationService;
import com.jsowell.pile.service.IThirdPartySettingInfoService;
import com.jsowell.pile.vo.base.StationSettingRelationVO;
import com.jsowell.thirdparty.lianlian.service.LianLianService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 充电结束Handler
 *
 * GBT-27930 充电桩与 BMS 充电结束阶段报文
 * @author JS-ZZA
 * @date 2022/9/19 13:27
 */
@Slf4j
@Component
public class ChargeEndHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.CHARGE_END_CODE.getBytes());

    @Autowired
    private IOrderBasicInfoService orderBasicInfoService;

    @Autowired
    private IThirdPartySettingInfoService thirdPartySettingInfoService;

    @Autowired
    private LianLianService lianLianService;

    @Autowired
    private IStationSettingRelationService stationSettingRelationService;

    @Override
    public void afterPropertiesSet() throws Exception {
        YKCOperateFactory.register(type, this);
    }

    @Override
    public byte[] supplyProcess(YKCDataProtocol ykcDataProtocol, Channel channel) {
        log.info("[===执行充电结束逻辑===] param:{}, channel:{}", JSONObject.toJSONString(ykcDataProtocol), channel.toString());
        // 消息体
        byte[] msgBody = ykcDataProtocol.getMsgBody();

        int startIndex = 0;
        int length = 16;

        // 交易流水号
        byte[] serialNumByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String transactionCode = BytesUtil.bcd2Str(serialNumByteArr);

        // 桩编码
        startIndex += length;
        length = 7;
        byte[] pileSnByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String pileSn = BytesUtil.bcd2Str(pileSnByteArr);

        // 保存时间
        saveLastTime(pileSn);

        // 枪号
        startIndex += length;
        length = 1;
        byte[] connectorCodeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String connectorCode = BytesUtil.bcd2Str(connectorCodeByteArr);

        // BMS中止荷电状态 SOC   1%/位， 0%偏移量； 数据范围： 0~100%
        startIndex += length;
        byte[] BMSStopChargingSOC = BytesUtil.copyBytes(msgBody, startIndex, length);
        String stopSoc = BytesUtil.binary(BMSStopChargingSOC, 10);

        // BMS 动力蓄电池单体最低电压   0.01 V/位， 0 V 偏移量；数据范围： 0 ~24 V
        startIndex += length;
        length = 2;
        byte[] BMSBatteryMinVoltageByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // BMS 动力蓄电池单体最高电压   0.01 V/位， 0 V 偏移量；数据范围： 0 ~24 V
        startIndex += length;
        byte[] BMSBatteryMaxVoltageByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // BMS 动力蓄电池最低温度   1ºC/位， -50 ºC 偏移量；数据范围： -50 ºC ~+200 ºC
        startIndex += length;
        length = 1;
        byte[] BMSBatteryMinTemperatureByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // BMS 动力蓄电池最高温度   1ºC/位， -50 ºC 偏移量；数据范围： -50 ºC ~+200 ºC
        startIndex += length;
        byte[] BMSBatteryMaxTemperatureByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 电桩累计充电时间   1 min/位， 0 min 偏移量； 数据范围： 0~600 min
        startIndex += length;
        length = 2;
        byte[] pileSumChargingTimeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 电桩输出能量   0.1 kWh/位， 0 kWh 偏移量； 数据范围： 0~1000 kWh
        startIndex += length;
        byte[] pileOutputEnergyByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 电桩充电机编号   充电机编号，  1/位，  1偏移量 ，数据范围 ： 0 ～ 0xFFFFFFFF
        startIndex += length;
        length = 4;
        byte[] pileChargedCodeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 查询订单，改为待结算 将结束soc传入
        // OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(transactionCode);
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByTransactionCode(transactionCode);
        if (Objects.nonNull(orderInfo)) {
            if (StringUtils.equals(OrderStatusEnum.IN_THE_CHARGING.getValue(), orderInfo.getOrderStatus())) {
                orderInfo.setOrderStatus(OrderStatusEnum.STAY_SETTLEMENT.getValue());
            }
            orderInfo.setEndSOC(stopSoc);
            if (orderInfo.getChargeEndTime() == null) {
                orderInfo.setChargeEndTime(new Date()); // 结束充电时间
            }
            orderBasicInfoService.updateOrderBasicInfo(orderInfo);

            try {
                // 查询该站点是否已对接互联互通平台，如果对接则发送充电结束
                // 通过站点id查询相关配置信息
                StationSettingRelation relation = new StationSettingRelation();
                relation.setStationId(Long.parseLong(orderInfo.getStationId()));
                StationSettingRelationVO relationInfo = stationSettingRelationService.selectRelationInfo(relation);
                // ThirdPartySettingInfo info = thirdPartySettingInfoService.getInfoByStationId(Long.parseLong(orderInfo.getStationId()));
                if (Objects.nonNull(relationInfo)) {
                    // 推送停止充电结果
                    lianLianService.pushStopChargeResult(orderInfo.getOrderCode());
                }
            } catch (Exception e) {
                log.error("联联平台推送停止充电结果异常", e);
            }

        }

        return null;
    }
}
