package com.jsowell.netty.handler.yunkuaichong;

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.Cp56Time2a.Cp56Time2aUtil;
import com.jsowell.common.util.DateUtils;
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;

import java.util.Date;

/**
 * 对时设置应答
 *
 * @author JS-ZZA
 * @date 2022/9/27 11:09
 */
@Slf4j
@Component
public class TimeCheckSettingResponseHandler extends AbstractHandler{
    private final String type = YKCUtils.frameType2Str(YKCFrameTypeCode.TIME_CHECK_SETTING_ANSWER_CODE.getBytes());

    @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[] pileSnByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        String pileSn = BytesUtil.bcd2Str(pileSnByteArr);

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

        // 当前时间
        startIndex += length;
        length = 7;
        byte[] currentTimeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
        Date date = Cp56Time2aUtil.byte2Hdate(currentTimeByteArr);
        log.info("对时设置应答, pileSn:{}, channelId:{}, 充电桩当前时间:{}", pileSn, channel.id().asShortText(), DateUtils.formatDateTime(date));
        return null;
    }
}
