package com.jsowell.netty.handler;

import com.alibaba.fastjson2.JSONObject;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import com.jsowell.common.core.domain.ykc.YKCFrameTypeCode;
import com.jsowell.common.enums.ykc.ChargingFailedReasonEnum;
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.service.IOrderBasicInfoService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 远程启动充电命令回复 0x33, 0x34
 *
 * @author JS-ZZA
 * @date 2022/9/19 14:35
 */
@Slf4j
@Component
public class RemoteStartChargingRequestHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.REMOTE_START_CHARGING_ANSWER_CODE.getBytes());

    @Autowired
    private IOrderBasicInfoService orderBasicInfoService;

    @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[] orderCodeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String transactionCode = BytesUtil.bcd2Str(orderCodeByteArr);

        // 桩编码
        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);

        // 启动结果  0x00失败 0x01成功
        startIndex += length;
        byte[] startResultByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String startResult = BytesUtil.bcd2Str(startResultByteArr);

        /**
         * 失败原因
         *
         * 桩在收到启充命令后,检测到未插枪则发送 0x33 报文回复充电失败。
         * 若在 60 秒（以收到 0x34 时间开始计算）内检测到枪重新连接，则补送 0x33 成功报文;超时或者离线等其他异常，桩不启充、不补发 0x33 报文
         * 0x00 无
         * 0x01 设备编号不匹配
         * 0x02 枪已在充电
         * 0x03 设备故障
         * 0x04 设备离线
         * 0x05 未插枪
         */
        startIndex += length;
        byte[] failedReasonByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String failedReason = BytesUtil.bin2HexStr(failedReasonByteArr);
        String failedReasonMsg = ChargingFailedReasonEnum.getMsgByCode(Integer.parseInt(failedReason, 16));

        if (StringUtils.equals(startResult, Constants.DOUBLE_ZERO)) {
            // 启动失败 682204000001000000000041
            orderBasicInfoService.chargingPileFailedToStart(transactionCode, failedReasonMsg);
        } else {
            // 启动成功
            orderBasicInfoService.chargingPileStartedSuccessfully(transactionCode);
        }
        // orderBasicInfoService.updateOrderBasicInfo(orderInfo);
        log.info("交易流水号:{}, 桩编码:{}, 枪号:{}, 启动结果:{}, 失败原因:{}", transactionCode, pileSn, connectorCode, startResult, failedReasonMsg);
        return null;
    }
}
