package com.jsowell.netty.handler.yunkuaichong;

import com.google.common.primitives.Bytes;
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.util.BytesUtil;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.netty.factory.YKCOperateFactory;
import com.jsowell.pile.service.PileBillingTemplateService;
import com.jsowell.pile.service.YKCPushCommandService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 计费模板验证请求Handler
 *
 * @author JS-ZZA
 * @date 2022/9/17 14:10
 */
@Slf4j
@Component
public class BillingTemplateValidateRequestHandler extends AbstractHandler{

    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.BILLING_TEMPLATE_VALIDATE_CODE.getBytes());

    @Autowired
    private PileBillingTemplateService pileBillingTemplateService;

    @Autowired
    private YKCPushCommandService ykcPushCommandService;

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

    @Override
    public byte[] supplyProcess(YKCDataProtocol ykcDataProtocol, Channel channel) {
        // log.info("[===执行计费模板验证请求逻辑===] param:{}, channel:{}", JSON.toJSONString(ykcDataProtocol), channel.toString());
        // 获取消息体
        byte[] msgBody = ykcDataProtocol.getMsgBody();

        int startIndex = 0;
        int length = 7;

        // 桩号
        byte[] pileSnByte = BytesUtil.copyBytes(msgBody, startIndex, length);
        String pileSn = BytesUtil.binary(pileSnByte, 16);

        // 保存时间
        saveLastTimeAndCheckChannel(pileSn, channel);

        // 计费模型编码
        startIndex += length;
        length = 2;
        byte[] billingTemplateCodeByte = BytesUtil.copyBytes(msgBody, startIndex, length);
        String billingTemplateCode = BytesUtil.binary(billingTemplateCodeByte, 16);

        byte[] flag = Constants.oneByteArray;
        // 消息体
        byte[] messageBody = Bytes.concat(pileSnByte, billingTemplateCodeByte, flag);
        return getResult(ykcDataProtocol, messageBody);
    }
}
