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

import cn.hutool.core.util.ObjectUtil;
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;

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

public class SourceNettyServerHandler 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 SourceNettyServerHandler INSTANCE = new SourceNettyServerHandler();

    /**
     * @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 enumByCode = SourceOperateCodeEnum.getDictDataEnumByCode(tem[0]);
        JSONObject jsonObject1 = new JSONObject();
        if (ObjectUtil.isNotNull(enumByCode)) {
            switch (enumByCode) {
                //源初始化
                case YJC_YTXJY:
              String aa = "{\"requestId\":\"yjc_ytxjy\",\"operateCode\":\"INIT_GATHER\",\"data\":null,\"code\":10201}";
              String bb = "{\"requestId\":\"yjc_ytxjy\",\"operateCode\":\"INIT_GATHER\",\"data\":null,\"code\":10200}";
                    channel.writeAndFlush(aa+"/n");
                    channel.writeAndFlush(bb+"/n");
                    break;
                //相序检测
                case YJC_XUJY:
                    String hh = "{\"requestId\":\"YJC_xujy\",\"operateCode\":\"OPER_GATHER\",\"data\":null,\"code\":10201}";
                    String ii = "{\"requestId\":\"YJC_xujy\",\"operateCode\":\"OPER_GATHER\",\"data\":null,\"code\":10200}";
                    channel.writeAndFlush(hh+"\n");
                    channel.writeAndFlush(ii+"\n");
                    break;
                //正式检测
                case FORMAL_REAL:

                    break;
                //系数校验
                case Coefficient_Check:
                    String a = "{\"requestId\":\"Coefficient_Check\",\"operateCode\":\"OPER_GATHER\",\"data\":null,\"code\":10201}";
                    String b= "{\"requestId\":\"Coefficient_Check\",\"operateCode\":\"OPER_GATHER\",\"data\":null,\"code\":10200}";

                    break;
                case QUITE_SOURCE:

                    break;
                case YXT:
                    jsonObject1.put("requestId", "yjc_ytxjy");
                    jsonObject1.put("operateCode", "INIT_GATHER");
                    jsonObject1.put("code", "10201");
                    channel.writeAndFlush(jsonObject1.toJSONString() + '\n');

                    break;
            }
        } else {
            System.out.println("未知异常" + enumByCode);
        }


    }

    @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()+" 断开连接");
//            }
//        }
    }

}
