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 com.jsowell.pile.service.YKCPushCommandService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.vo.web.BillingTemplateVO;
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 15:59
 */
@Slf4j
@Component
public class BillingTemplateRequestHandler extends AbstractHandler{

    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.BILLING_TEMPLATE_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[] pileSnByte = ykcDataProtocol.getMsgBody();
        String pileSn = BytesUtil.binary(pileSnByte, 16);
        // log.info("桩号：{}", pileSn);

        // 保存时间
        saveLastTime(pileSn);

        // 根据桩号查询计费模板
        BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(pileSn);
        if (billingTemplateVO == null) {
            log.warn("根据桩号：{}，查询计费模板为null", pileSn);
            return null;
        }

        // log.info("下面进行下发二维码 pileSn:{}, thread:{}", pileSn, Thread.currentThread().getName());
        // CompletableFuture.runAsync(() -> {
        //     try {
        //         Thread.sleep(200);
        //     } catch (InterruptedException e) {
        //         e.printStackTrace();
        //     }
        //     // 下发二维码
        //     IssueQRCodeCommand issueQRCodeCommand = IssueQRCodeCommand.builder().pileSn(pileSn).build();
        //     ykcPushCommandService.pushIssueQRCodeCommand(issueQRCodeCommand);
        // });

        byte[] messageBody = pileBillingTemplateService.generateBillingTemplateMsgBody(pileSn, billingTemplateVO);

        return getResult(ykcDataProtocol, messageBody);
    }

}
