package com.jsowell.netty.handler;

import com.alibaba.fastjson2.JSONObject;
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.YKCPushCommandService;
import com.jsowell.pile.service.IPileBillingTemplateService;
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 IPileBillingTemplateService 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:{}", JSONObject.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);

        // 保存时间
        saveLastTime(pileSn);

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

        // 根据桩号查询计费模板
        // BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(pileSn);
        // String templateCode = null;
        // if (billingTemplateVO != null) {
        //     templateCode = billingTemplateVO.getTemplateCode();
        // }


        // log.info("桩传的计费模型编码：{}, 根据桩号:{} 查询到的计费模型编码：{}", billingTemplateCode, pileSn, templateCode);
        // log.info("桩传的计费模型编码：{}", billingTemplateCode);

        /**
         * 应答 0x00 桩计费模型与平台一致   0x01 桩计费模型与平台不一致
         */
        // byte[] flag;
        // if (StringUtils.equals(billingTemplateCode, "100")){
        //     flag = Constants.zeroByteArray;
        // }else {
        // }
        byte[] flag = Constants.oneByteArray;
        // 消息体
        byte[] messageBody = Bytes.concat(pileSnByte, billingTemplateCodeByte, flag);
        return getResult(ykcDataProtocol, messageBody);
    }
}
