package com.xueyi.nlt.netty.client.handler;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

import static com.xueyi.nlt.netty.client.NettyClient.APPID;

public class NettyClientHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    // 定义log
    private static final Logger log = LoggerFactory.getLogger(NettyClientHandler.class);

    private final WebSocketClientHandshaker webSocketClientHandshaker;

    public NettyClientHandler(WebSocketClientHandshaker webSocketClientHandshaker) {
        this.webSocketClientHandshaker = webSocketClientHandshaker;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        // 握手
        webSocketClientHandshaker.handshake(channel);

        String question = "你是能帮我指定一个五一出行的计划么？";
        log.info("Client,channelActive");
        JSONObject frame = new JSONObject();
        JSONObject header = new JSONObject();
        JSONObject chat = new JSONObject();
        JSONObject parameter = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject message = new JSONObject();
        JSONObject text = new JSONObject();
        JSONArray ja = new JSONArray();

        //填充header
        header.put("app_id",APPID);
        header.put("uid","123456789");
        //填充parameter
        chat.put("domain","general");
        chat.put("random_threshold",0);
        chat.put("max_tokens",1024);
        chat.put("auditing","default");
        parameter.put("chat",chat);
        //填充payload
        text.put("role","user");
        text.put("content",question);
        ja.add(text);
//            message.addProperty("text",ja.getAsString());
        message.put("text",ja);
        payload.put("message",message);
        frame.put("header",header);
        frame.put("parameter",parameter);
        frame.put("payload",payload);
        System.out.println("frame:\n" + frame.toString());
        ByteBuf byteBuf = Unpooled.copiedBuffer(frame.toString(), Charset.forName("utf-8"));
        ctx.writeAndFlush(frame.toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        log.info("Client,接收到服务端发来的消息:" + msg);
//        ByteBuf buf = (ByteBuf) msg;
//        byte[] buffer = new byte[buf.readableBytes()];
//        buf.readBytes(buffer);
//        String message = new String(buffer, "utf-8");
//        log.info("Client,接收到服务端发来的消息:" + message);

        Channel ch = ctx.channel();
        DefaultHttpResponse response = (DefaultHttpResponse) msg;
        log.info(response.toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        // 获取客户端传输来的文本消息
        String text = textWebSocketFrame.text();
        // 这个是自定义的日志工具类，可见其它文章
        log.info("收到的文本消息：[{}]", text);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("Client,exceptionCaught");
        cause.printStackTrace();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("Client,channelInactive");
    }

}
