import React, { useEffect, useState } from "react";
import baseRequest from "@/utils/baseRequest";
const WebSocketComponent = ({ getData }) => {
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    let socket = null;
    let interval = null;
    function fn() {
      const base = baseRequest();
      if (socket && socket.readyState === 1) return;
      // 创建WebSocket连接
      if (!socket)
        socket = new WebSocket(
          `${process.env.NEXT_PUBLIC_WEBSOCKET_URL}/ws?b_mid=${base.b_mid}&b_dt=1&b_token=${base.b_token}&b-ch=h5`
        );
      // 注意使用wss协议（如果服务器支持）
      // 连接打开时触发
      socket.onopen = () => {
        // console.log("WebSocket connected.", socket.readyState);
        // 可以在这里发送消息到服务器，例如：socket.send('Hello Server!');
        socket.send(JSON.stringify({ t: 1 }));
      };
      // 处理收到的消息
      socket.onmessage = (event) => {
        if (Object.prototype.toString.call(event.data) === "[object Blob]") {
          var reader = new FileReader();
          reader.readAsText(event.data, "utf-8");
          reader.onload = function (e) {
            try {
              const data = JSON.parse(reader.result);
              if (data.t === 2 && data.msg.ping_interval) {
                socket.send("ping");
                interval = setInterval(() => {
                  // 发送 ping 给服务器
                  socket.send("ping");
                  // 响应服务器的 ping
                  // socket.on("ping", () => {
                  //   socket.send("pong");
                  // });
                }, data.msg.ping_interval * 1000);
              }
              if (data.t === 3) {
                getData(data.msg);
                setMessages((prevMessages) => [...prevMessages, data]);
              }
            } catch (error) {}
          };
        }
      };

      // 连接关闭时触发
      socket.onclose = () => {
        clearInterval(interval);
        // console.log("WebSocket disconnected.");
      };

      // 连接错误时触发
      socket.onerror = (error) => {
        // console.error("WebSocket error:", error);
      };

      // 响应服务器的 ping
      // socket.on("ping", () => {
      //   socket.send("pong");
      // });
    }

    fn();
    // 组件卸载时关闭WebSocket连接
    return () => {
      // console.log("state", socket.readyState);
      socket.readyState === WebSocket.OPEN && socket?.close();
    };
  }, []); // 空依赖数组表示这个effect只在组件挂载时运行一次

  return (
    <div>
      {/* <Text style={{ fontSize: 24, fontWeight: 'bold' }}>WebSocket Messages</Text>
      <FlatList
        data={messages}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <Text>{item}</Text>}
      /> */}
    </div>
  );
};

export default WebSocketComponent;
