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.util.BytesUtil;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.netty.factory.YKCOperateFactory;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 充电阶段充电机中止Handler  0x21
 *
 * GBT-27930 充电桩与 BMS 充电阶段充电机中止报文
 * @author JS-ZZA
 * @date 2022/9/19 13:35
 */
@Slf4j
@Component
public class ChargerAbortedDuringChargingPhaseHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.THE_CHARGER_IS_ABORTED_DURING_THE_CHARGING_PHASE_CODE.getBytes());

    @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);

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

        // 保存时间
        saveLastTime(pileSn);

        // 枪号
        startIndex += length;
        length = 1;
        byte[] pileConnectorNumByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        /**
         * BMS 中止充电原因
         * 1-2 位——达到充电机设定 的条件中止
         * 3-4 位——人工中止
         * 5-6 位——异常中止
         * 7-8 位——BMS 主动中止
         */
        startIndex += length;
        byte[] BMSStopChargingReasonByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        /**
         * BMS 中止充电故障原因
         * 1-2 位——充电机过温故障
         * 3-4 位——充电连接器故障
         * 5-6 位——充电机内部过温故障
         * 7-8 位——所需电量不 能传送
         * 9-10 位——充电机急停故障
         * 11-12 位——其他故障
         * 13-16 位——预留位
         */
        startIndex += length;
        length = 2;
        byte[] BMSStopChargingFaultReasonByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        /**
         * BMS 中止充电错误原因
         * 1-2 位——电流不匹配
         * 3-4 位——电压异常
         * 5-8 位——预留位
         */
        startIndex += length;
        length = 1;
        byte[] BMSStopChargingErrorReasonByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);


        return null;
    }
}
