package com.zksy.environmentHJ212.config;

import com.zksy.environmentHJ212.utils.MonitorDatasynch;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

@Slf4j
@Component
public class ServerHandler extends ChannelInboundHandlerAdapter {
    private static ServerHandler serverHandler;

    @Autowired
    private MonitorDatasynch monitorDatasynch;
    @PostConstruct
    public void init() {
        log.info("init()方法");
        serverHandler = this;
        serverHandler.monitorDatasynch = this.monitorDatasynch;
    }

    /**
     * 客户端与服务端创建连接的时候调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端连接开始...");
        NettyConfig.group.add(ctx.channel());
        /**
         * 往客户端发送消息
         */
        /*String helo = "QN=20250530141057223;ST=32;CN=2031;PW=123456;MN=0152316A279055;Flag=5;CP=&&BeginTime=20250529000000;EndTime=20250530000000&&";
        ByteBuf byteBuf = Unpooled.wrappedBuffer(helo.getBytes());
        ctx.channel().writeAndFlush(byteBuf);
        System.out.println("首次连接完成!"+byteBuf);
        String helo2 = "QN=20250530141057223;ST=32;CN=2031;PW=123456;MN=1234567901234;Flag=5;CP=&&BeginTime=20250529000000;EndTime=20250530000000&&";
        ByteBuf byteBuf3 = Unpooled.wrappedBuffer(helo2.getBytes());
        ctx.channel().writeAndFlush(byteBuf3);*/
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端连接关闭...");
        NettyConfig.group.remove(ctx.channel());
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        log.info("信息接收完毕...");
    }

    /**
     * 工程出现异常的时候调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 服务端处理客户端websocket请求的核心方法，这里接收了客户端发来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception {
        try {
            ByteBuf buf = (ByteBuf) info;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String msg = new String(req);
            System.out.println(msg+"==============");
            log.info("==========数据已接收,接收时间：==========" + LocalDateTime.now());
            String pushMonitorDataStr = serverHandler.monitorDatasynch.pushMonitorData(channelHandlerContext,msg);
        } catch (Exception e) {
            log.info("==========数据错误==========");
            e.printStackTrace();
        } finally {
            channelHandlerContext.flush();
        }
    }
}
