package com.njcn.gather.detection.util.socket.service;

import com.alibaba.fastjson.JSONObject;
import com.njcn.gather.detection.pojo.enums.SourceOperateCodeEnum;
import com.njcn.gather.detection.pojo.vo.SocketDataMsg;
import com.njcn.gather.detection.util.socket.MsgUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Objects;

/**
 * @Description: 客户端业务处理
 * @Author: wr
 * @Date: 2024/12/10 14:18
 */

public class DevNettyServerHandler extends SimpleChannelInboundHandler<String> {

    private final String DEV = "_Dev";
    private final String source = "_Source";

    private final String stepTag = "&&";
    private final String stepBegin = "_Start";
    private final String stepEnd = "_End";


    public static final DevNettyServerHandler INSTANCE = new DevNettyServerHandler();

    /**
     * @Description: 当通道进行连接时推送消息
     * @Author: wr
     * @Date: 2024/12/10 14:19
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端监听到" + ctx.channel().id() + "连接");
        super.channelActive(ctx);
    }

    /**
     * 处理消息信息
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) {
        System.out.println(ctx.channel().id() + "NettyServer服务端接收到客户端消息：" + msg);
        Channel channel = ctx.channel();
        SocketDataMsg socketDataMsg = MsgUtil.socketDataMsg(msg);
        String[] tem = socketDataMsg.getRequestId().split(stepTag);
        SourceOperateCodeEnum sourceOperateCodeEnum = SourceOperateCodeEnum.getDictDataEnumByCode(tem[0]);

        switch (Objects.requireNonNull(sourceOperateCodeEnum)) {
            //设备通讯校验
            case YJC_SBTXJY:
                String aa = "{\"requestId\":\"yjc_sbtxjy\",\"operateCode\":\"INIT_GATHER$01\",\"data\":null,\"code\":10201}";
                String bb = "{\"requestId\":\"yjc_sbtxjy\",\"operateCode\":\"INIT_GATHER$01\",\"data\":null,\"code\":10201}";
                String cc = "{\"requestId\":\"yjc_sbtxjy\",\"operateCode\":\"INIT_GATHER$01\",\"data\":\"192.168.1.237_1\",\"code\":10200}";
                channel.writeAndFlush(aa+"\n");
                channel.writeAndFlush(bb+"\n");
                channel.writeAndFlush(cc+"\n");
                break;
            //协议校验
            case YJC_XYJY:
               String dd="{\"requestId\":\"yjc_xyjy\",\"operateCode\":\"INIT_GATHER$02\",\"data\":null,\"code\":10201}";
               String ee = "{\"requestId\":\"yjc_xyjy\",\"operateCode\":\"INIT_GATHER$02\",\"data\":\"192.168.1.237_1\",\"code\":10200}";
                channel.writeAndFlush(dd+"\n");
                channel.writeAndFlush(ee+"\n");

                String ff = "{\"requestId\":\"yjc_xyjy\",\"operateCode\":\"INIT_GATHER$03\",\"data\":null,\"code\":10201}";
                String gg ="{\"requestId\":\"yjc_xyjy\",\"operateCode\":\"INIT_GATHER$03\",\"data\":\"192.168.1.237_1\",\"code\":10200}";
                channel.writeAndFlush(ff+"\n");
                channel.writeAndFlush(gg+"\n");
                break;
            //相序校验
            case YJC_XUJY:
                String hh = "{\"requestId\":\"YJC_xujy\",\"operateCode\":\"DATA_REQUEST$02\",\"data\":null,\"code\":10201}";
                String ii = "{\"requestId\":\"YJC_xujy\",\"operateCode\":\"DATA_REQUEST$02\",\"data\":\"{\\\"Time\\\":\\\"2025-02-14T15:09:06.004\\\",\\\"ID\\\":\\\"192.168.1.237_1\\\",\\\"result\\\":false,\\\"SqlData\\\":[{\\\"type\\\":\\\"real\\\",\\\"desc\\\":\\\"VRMS\\\",\\\"list\\\":{\\\"A\\\":\\\"59.969920\\\",\\\"B\\\":\\\"49.963360\\\",\\\"C\\\":\\\"39.971470\\\",\\\"T\\\":null}},{\\\"type\\\":\\\"real\\\",\\\"desc\\\":\\\"VA\\\",\\\"list\\\":{\\\"A\\\":\\\"0.000000\\\",\\\"B\\\":\\\"-119.864000\\\",\\\"C\\\":\\\"120.052000\\\",\\\"T\\\":null}},{\\\"type\\\":\\\"real\\\",\\\"desc\\\":\\\"IRMS\\\",\\\"list\\\":{\\\"A\\\":\\\"1.000979\\\",\\\"B\\\":\\\"1.998939\\\",\\\"C\\\":\\\"3.000807\\\",\\\"T\\\":null}},{\\\"type\\\":\\\"real\\\",\\\"desc\\\":\\\"IA\\\",\\\"list\\\":{\\\"A\\\":\\\"-0.038000\\\",\\\"B\\\":\\\"-120.052000\\\",\\\"C\\\":\\\"119.941000\\\",\\\"T\\\":null}}],\\\"SqlDataHarm\\\":[]}\",\"code\":10200}\n";
                channel.writeAndFlush(hh+"\n");
                channel.writeAndFlush(ii+"\n");
                break;
            //正式检测
            case FORMAL_REAL:

                break;
            //系数校验
            case Coefficient_Check:
                String a = "{\"requestId\":\"Coefficient_Check\",\"operateCode\":\"DATA_CHNFACTOR$01\",\"data\":null,\"code\":10201}";
                String b = "{\"requestId\":\"Coefficient_Check\",\"operateCode\":\"DATA_CHNFACTOR$01\",\"data\":\"[{\\\"uMonitorPoint\\\":0,\\\"f\\\":{\\\"Ua_gain\\\":9999,\\\"Ub_gain\\\":10008,\\\"Uc_gain\\\":10000,\\\"U0_gain\\\":10000,\\\"Ia_gain\\\":9997,\\\"Ib_gain\\\":9997,\\\"Ic_gain\\\":10001,\\\"I0_gain\\\":10000,\\\"Uab_gain\\\":9999,\\\"Ubc_gain\\\":10008,\\\"Uca_gain\\\":10000}}]\",\"code\":10200}";
                channel.writeAndFlush(a+"\n");
                channel.writeAndFlush(b+"\n");

                switch (Objects.requireNonNull(sourceOperateCodeEnum)) {
                    case DATA_CHNFACTOR$01:
                        break;
                }


                break;
            //退出关闭
            case QUITE:
              //  quitDeal(socketDataMsg, param, msg);
                break;
            case YXT:
                break;
        }


    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("有新连接加入了++++......" + ctx.channel());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // Client disconnected, close the server-side channel too
        System.out.println("NettyServer服务端监听到" + ctx.channel().id() + "关闭连接");
        ctx.close();  // This will trigger the close event on the server side
        super.channelInactive(ctx);
    }

    /**
     * 用户事件的回调方法（自定义事件用于心跳机制）
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //空闲状态的事件
//        if (evt instanceof IdleStateEvent) {
//            IdleStateEvent event = (IdleStateEvent) evt;
//            System.out.println(event.state() + ">>>" + ctx.channel().id());
//            //已经10秒钟没有读时间了
//            if (event.state().equals(IdleState.READER_IDLE)){
//                // 心跳包丢失，10秒没有收到客户端心跳 (断开连接)
//                ctx.channel().close().sync();
//                System.out.println("已与 "+ctx.channel().remoteAddress()+" 断开连接");
//            }
//        }
    }

}
