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;

/**
 * 余额更新应答
 *
 * @author JS-ZZA
 * @date 2022/9/19 14:47
 */
@Slf4j
@Component
public class RemoteAccountBalanceUpdateRequestHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.REMOTE_ACCOUNT_BALANCE_UPDATE_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 = 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);

        // 物理卡号  不足 8 位补零
        //如果不为零， 需要校验本次充电是 否为此卡充电
        //如果为零， 则不校验， 直接更新桩 当前充电用户余额
        startIndex += length;
        length = 8;
        byte[] cardNumByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 修改后账户金额  保留两位小数
        startIndex += length;
        length = 4;
        byte[] accountBalance = BytesUtil.copyBytes(msgBody, startIndex, length);

        // 应答
        // 帧类型
        byte[] remoteAccountBalanceUpdateAnswerCodeBytes = YKCFrameTypeCode.REMOTE_ACCOUNT_BALANCE_UPDATE_ANSWER_CODE.getBytes();

        // 修改结果  0x00-修改成功
        //0x01-设备编号错误
        //0x02-卡号错误



        return null;
    }
}
