import React from "react";
import TopP from "./TopP";
import Left from "./Left";
import Right from "./Right";
import Center from "./Center";
import {useEffect} from 'react';
import {useNavigate} from "react-router-dom";
import { useDispatch } from 'react-redux';
import { UpdateLine2After } from "../../store/LinePageSlice";
function LinePage() {
  const dispatch = useDispatch();
  const myUrl = "192.168.8.22"
  // const myUrl = window.location.host;
  useEffect(() => {
    let websocket2_2 = new WebSocket("ws://" + myUrl + "/websocket/message?userId=2-2-" + Date.now());
    // @ts-ignore
    websocket2_2.onmessage = function (event) {
      let msgData = event.data
      try {
        msgData = JSON.parse(event.data);
      } catch (error) {
        console.log("websocket: [unable to msgData] :  ", event.data);
      }
      if (!Object.prototype.toString.call(msgData).includes('Object')) return;
      dispatch(UpdateLine2After(msgData));
    }
    // 清理函数
    return () => {
      websocket2_2.close();
    };
  }, [dispatch]);

  const navigate = useNavigate();
  useEffect(() => {
    const handleKeyDown = (event:any) => {
      if (event.key === 'ArrowUp') {
        console.log('LDPage向上键被按下');
        navigate('/LD?lineId=2-2');
        // 执行向上键的逻辑
      } else if (event.key === 'ArrowDown') {
        console.log('LDPage向下键被按下');
        // 执行向下键的逻辑
        navigate('/LD?lineId=2-2');
      }
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  });
  return (
    <React.Fragment>
      <TopP />
      <div className="block_bottom flex-row">
        <Left />
        <Center />
        <Right />
      </div>
    </React.Fragment>
  );
}
export default LinePage;
