import WebSocketService from "@/Hoc/WebSocket";
import { AnyRecord } from "dns";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";

function useWebsocketListener(url: string, openJson: string): { latestMessage: string | null, readyState: any, sendMessage: (json: string) => void, close: () => void, socket: WebSocket } {
  const [latestMessage, setMessage] = useState<string | null>(null);
  const websocket:any = useRef(WebSocketService.getInstance(url, openJson).getWebsocket())
  const [readyState, setStatus] = useState<any>(websocket.current?.CONNECTING);
  sessionStorage.setItem("isOutPage","0")
  useEffect(() => {
    setStatus(websocket.current.readyState)
    const handleOpen = () => {
      console.log("websocketopen")
      setStatus(websocket.current.OPEN)
    };
    const handleClose = () => {
      console.log("websocketclose")
      setStatus(websocket.current.CLOSED)
    };
    const handleError = () => {
      console.log("websocketerror")
      setStatus(websocket.current.CLOSED);
    }
    const handleMessage = (event: MessageEvent) => {
      setMessage(event.data);
    };
    websocket.current?.addEventListener('open', handleOpen);
    websocket.current?.addEventListener('close', handleClose);
    websocket.current?.addEventListener('error', handleError);
    websocket.current?.addEventListener('message', handleMessage);
    return () => {
      websocket.current?.removeEventListener('open', handleOpen);
      websocket.current?.removeEventListener('close', handleClose);
      websocket.current?.removeEventListener('error', handleError);
      websocket.current?.removeEventListener('message', handleMessage);
    };
  }, [websocket.current]);
  // 断线重连
  useEffect(() => {
    if (readyState === 3 && !websocket.current) {
      console.log("断线重连====>")
      websocket.current = WebSocketService.getInstance(url, openJson).getWebsocket()
    }
  }, [readyState])
  // 发送消息
  const sendMessage = useCallback((json: string) => {
    websocket.current?.send(json)
  }, [websocket])
  return { latestMessage, readyState, sendMessage, close: websocket.current?.close, socket: websocket.current };
}

export default useWebsocketListener
// import { useEffect, useRef, useState } from 'react';

// type WebSocketHook = {
//   sendMessage: (message: string) => void;
//   readyState: number | null;
//   latestMessage: string | null;
//   close: () => void,
//   socket: WebSocket | null
// };

// const useWebSocket = (url: string, openJson: string): WebSocketHook => {
//   const [socket, setSocket] = useState<WebSocket | null>(null);
//   const [readyState, setReadyState] = useState<number | null>(null);
//   const [latestMessage, setMessages] = useState<string | null>(null);
//   const [heart, setHeart] = useState<any>(null)
//   const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
//   useEffect(() => {
//     const connect = (): WebSocket => {

//       const newSocket = new WebSocket(url);
//       newSocket.onopen = () => {
//         if (reconnectTimeoutRef.current) {
//           clearTimeout(reconnectTimeoutRef.current);
//         }
//         sessionStorage.setItem("isOutPage","0")
//         if (heart) {
//           clearInterval(heart)
//           setHeart(null)
//         }
//         console.log('WebSocket connected');
//         setReadyState(newSocket.readyState);
//         startHeartbeat(newSocket);
//         newSocket.send(openJson)
//       };

//       newSocket.onmessage = (event) => {
//         setMessages(event.data);
//       };

//       newSocket.onerror = () => {
//         console.error('WebSocket error occurred');
//         setReadyState(newSocket.readyState);
//       };

//       newSocket.onclose = () => {
//         console.log('WebSocket connection closed');
//         setReadyState(newSocket.readyState);
//         if(sessionStorage.getItem("isOutPage")  && sessionStorage.getItem("isOutPage") == "0"){
//           console.log("isOutPage===>",sessionStorage.getItem("isOutPage") )
//           scheduleReconnect()
//         }
//       };
//       return newSocket;
//     };

//     const scheduleReconnect = () => {
//       console.log("scheduleReconnect")
//       reconnectTimeoutRef.current = setTimeout(() => {
//         setSocket(connect());
//       }, 10000);
//     };

//     const startHeartbeat = (socket: WebSocket) => {
//       let t = setInterval(() => {
//         if (socket.readyState === websocket.current.OPEN) {
//           socket.send('heartbeat');
//         }
//       }, 10000);
//       setHeart(t)
//     };
//     if (!socket) {
//       console.log("socket不存在创建新的")
//       setSocket(connect());
//     }else{
//       console.log("已存在socket")
//     }
//   }, [url,openJson, socket]);

//   const sendMessage = (message: string) => {
//     console.log("msg===>", socket?.readyState)
//     if (socket && socket.readyState === websocket.current.OPEN) {
//       socket.send(message);
//     }
//   };
//   const close = () => {
//     console.log("执行关闭操作！")
//     socket?.close();
//     setSocket(null)
//     setReadyState(3)
//     if (heart) {
//       clearInterval(heart)
//       setHeart(null)
//     }
//     console.log("关闭结束！")
//   }
//   useEffect(() => {
//     return () => {
//       if(socket){
//         console.log("被卸载了websocket")
//         close()
//         sessionStorage.setItem("isOutPage","1")
//       }
//     }
//   }, [socket])
//   return { sendMessage, readyState, latestMessage, close, socket };
// };

// export default useWebSocket;
