package com.cisdi.data.RFID.gateway;

import com.cisdi.data.common.exception.BusinessException;
import com.cisdi.data.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.util.ArrayList;
import java.util.List;

public class RfidVoDecoder {

    public static List<RfidItemVo> Decode(ByteBuf in) {
        RfidItemVo vo = new RfidItemVo();
        List<RfidItemVo> result = new ArrayList<>();
        //消息体部分
        int length;
        if (in == null) {
            throw new BusinessException("ByteBuf 入参为null");
        } else if (in.readableBytes() == 10) {
            length = 8;
        }
        else {
            throw new BusinessException("报文长度不匹配 ,期望：10，实际：" + in.readableBytes());
        }
        //去掉报文头 和 结束符
        ByteBuf proceedIn = in.retainedSlice(1, length);
        result.add(split(proceedIn));
        ReferenceCountUtil.release(proceedIn);
        return result;
    }


    /**
     * @param in 去掉头尾的报文
     * @Description: 拆分报文
     * @author: Mo
     * @Date: 2021/6/2 10:51
     * @return: com.cisdi.data.RFID.gateway.RfidItemVo
     */
    public static RfidItemVo split(ByteBuf in) {
        RfidItemVo rfidItemVo = new RfidItemVo();
        ByteBuf buf = in.readBytes(8);
        // 编号
        String code = buf.toString(CharsetUtil.UTF_8);
        rfidItemVo.setCode(code);
        ReferenceCountUtil.release(buf);
        return rfidItemVo;
    }

    public static void main(String[] args) throws Exception {
        // 标签读取
//	    byte[] readBytes1 = HexUtil.hexStringToBytes("001c1952000b000e3000eabcdef01234567890003001000400000501");
//	    ByteBuf copiedBuffer = Unpooled.copiedBuffer(readBytes1);
//	    RfidItemVo decoderVo = RfidVoDecoder.Decode(copiedBuffer);
//	    logger.info("vo1={}", decoderVo);
//
//	    // 标签离开
//        readBytes1 = HexUtil.hexStringToBytes("00161942050c000e3000eabcdef01234567890003001");
//        copiedBuffer = Unpooled.copiedBuffer(readBytes1);
//        decoderVo = RfidVoDecoder.Decode(copiedBuffer);
//        logger.info("vo1={}", decoderVo);

        //标签读取
        
        
        
        byte[] readBytes1 = HexUtil.hexStringToBytes("02524630313030303103");
        ByteBuf copiedBuff = Unpooled.copiedBuffer(readBytes1);
        List<RfidItemVo> rfidItemVoList = RfidVoDecoder.Decode(copiedBuff);
        rfidItemVoList.forEach(System.out::println);


        readBytes1 = HexUtil.hexStringToBytes("0248656172744265617403");
        copiedBuff = Unpooled.copiedBuffer(readBytes1);
        rfidItemVoList = RfidVoDecoder.Decode(copiedBuff);
        rfidItemVoList.forEach(System.out::println);

        RfidFrameDecoder decoder = new RfidFrameDecoder(null);
        readBytes1 = HexUtil.hexStringToBytes("0248656172744265617403");
        copiedBuff = Unpooled.copiedBuffer(readBytes1);
        decoder.decode(null, copiedBuff, new ArrayList<Object>());
        
    }
}
