package com.yfd.platform.component.nettyserver;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class MyMessageDecoder extends ByteToMessageDecoder {
    private enum State {
        WAITING_FOR_START,
        READING_MESSAGE
    }

    private State state = State.WAITING_FOR_START;
    private final int expectedStartFlag = 0xEB90;
    private final int expectedEndFlag = 0xEB90;
    private int startFlag = 0;
    private long sendSessionID = 0;
    private long receiveSessionID = 0;
    private byte sessionSource = 0;
    private int xmlLength = 0;
    private ByteBuf cumulatedBuffer;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("进入解码方法" + in.toString());
        if (cumulatedBuffer == null) {
            cumulatedBuffer = in;
        } else {
            if (cumulatedBuffer.readableBytes() == 0) {
                cumulatedBuffer = in;
            } else {
                cumulatedBuffer.writeBytes(in);
            }
        }
        if (cumulatedBuffer.readableBytes() > 1024) {
            cumulatedBuffer.clear();
            xmlLength = 0;
            state = State.WAITING_FOR_START;
            return;
        }
        while (cumulatedBuffer.readableBytes() >= 2) {
            switch (state) {
                case WAITING_FOR_START:
                    startFlag = cumulatedBuffer.readUnsignedShort();
                    if (startFlag == expectedStartFlag) {
                        state = State.READING_MESSAGE;
                    } else {
                        // 未找到起始标志符，报文出现错误，重新等待起始标志符
                        state = State.WAITING_FOR_START;
                    }
                    break;

                case READING_MESSAGE:
                    if (cumulatedBuffer.readableBytes() >= 19) {
                        if(xmlLength==0){
                            // 读取发送会话序列号
                            sendSessionID = cumulatedBuffer.readLongLE();
                            // 读取接收会话序列号
                            receiveSessionID = cumulatedBuffer.readLongLE();
                            // 读取会话源标识
                            sessionSource = cumulatedBuffer.readByte();
                            // 读取XML的字节长度
                            xmlLength = cumulatedBuffer.readIntLE();
                        }

                        if (cumulatedBuffer.readableBytes() >= xmlLength + 2) {
                            ByteBuf xmlData = cumulatedBuffer.readSlice(xmlLength);
                            byte[] xmlContent1 = new byte[xmlLength];
                            xmlData.getBytes(0, xmlContent1);

                            int endFlag = cumulatedBuffer.readUnsignedShort();

                            if (endFlag == expectedEndFlag) {
                                // 报文解析完成
                                MyMessageProtocol msg = new MyMessageProtocol();
                                msg.setSenderSerialNo(sendSessionID);
                                msg.setReceiverSerialNo(receiveSessionID);
                                msg.setSessionflag(sessionSource);
                                msg.setXmllen(xmlLength);
                                byte[] xmlContent = new byte[xmlLength];
                                xmlData.getBytes(0, xmlContent);
                                msg.setXmlcontent(xmlContent);
                                out.add(msg);
                                cumulatedBuffer.clear();
                                xmlLength=0;
                                // 返回到等待状态
                                state = State.WAITING_FOR_START;
                            } else {
                                // 未找到结束标志符，报文出现错误，重新等待起始标志符
                                cumulatedBuffer.clear();
                                xmlLength=0;
                                state = State.WAITING_FOR_START;
                            }
                        } else {
                            // 不足以解析完整的XML数据，等待更多数据
                            return;
                        }
                    } else {
                        // 不足以解析完整的报文，等待更多数据
                        cumulatedBuffer.clear();
                        xmlLength = 0;
                        state = State.WAITING_FOR_START;
                        return;
                    }
                    break;
            }
        }

        // 如果有剩余数据，将其累积到下一个数据包中
        if (cumulatedBuffer.readableBytes() > 0) {
            in.clear().writeBytes(cumulatedBuffer);
        } else {
            in.clear();
        }
    }
}


