package com.zksy.environment.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    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("客户端与服务端连接开始...");
        //获取到当前与服务器连接成功的channel
        NettyConfig.group.add(ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+" 上线，"+"在线数量："+NettyConfig.group.size());
        /**
         * 往客户端发送消息
         */
        /*String helo = "##0128QN=20231030111800029;ST=22;CN=2041;PW=123456;MN=010000A8900016F007;Flag=5;CP=&&BeginTime=20231029000000,EndTime=20231029000000&&";
        ByteBuf byteBuf = Unpooled.wrappedBuffer(helo.getBytes());
        ctx.channel().writeAndFlush(byteBuf);
        System.out.println("首次连接完成!"+byteBuf);*/
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端连接关闭...");
        //获取当前要断连接的channel
        NettyConfig.group.remove(ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+" 下线，"+"在线数量："+NettyConfig.group.size());
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @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();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
        try {
            // 处理data数组中的数据
            serverHandler.monitorDatasynch.pushMonitorData(msg);
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 服务端处理客户端websocket请求的核心方法，这里接收了客户端发来的信息
     */
    /*@Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        try {
            ByteBuf hexString = (ByteBuf) msg; // 接收16进制字符串
            //ByteBuf buf = DataCheckUtil.hexStringToByteBuf(hexString); // 将16进制字符串转换为 ByteBuf
            //System.err.println("strArr==="+strArr);
            //log.info("==========数据已接收,接收时间：==========" + LocalDateTime.now());
            String pushMonitorDataStr = serverHandler.monitorDatasynch.pushMonitorData(hexString);
        } catch (Exception e) {
            log.info("==========数据入库失败==========");
            e.printStackTrace();
        }
    }*/
}
