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.IPileMsgRecordService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 远程重启应答
 *
 * @author JS-ZZA
 * @date 2022/9/27 13:27
 */
@Slf4j
@Component
public class RemoteRestartResponseHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.REMOTE_RESTART_ANSWER_CODE.getBytes());

    @Autowired
    private IPileMsgRecordService pileMsgRecordService;

    @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);

        // 保存报文
        String jsonMsg = JSONObject.toJSONString(ykcDataProtocol);
        pileMsgRecordService.save(pileSn, null, type, jsonMsg, ykcDataProtocol.getHEXString());

        // 设置结果
        startIndex += length;
        length = 1;
        byte[] settingResultByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);

        return null;
    }
}
