import { Outlet, useModel } from "@umijs/max";
import { useEffect, useState } from "react";
// @mui
import { styled } from "@mui/material/styles";
import { Scrollbars } from "react-custom-scrollbars";
import io from "socket.io-client";
import Header from "./header";
import Nav from "./nav";

const socket = io(SOCKET_IO_URL, { query: { id: localStorage.getItem("ID") } });

// ----------------------------------------------------------------------

const APP_BAR_MOBILE = 64;
const APP_BAR_DESKTOP = 64;

const StyledRoot = styled("div")({
  display: "flex",
  minHeight: "100%",
  overflow: "hidden",
});

const Main = styled("div")(({ theme }) => ({
  flexGrow: 1,
  overflow: "hidden",
  height: "100vh",
  paddingTop: APP_BAR_MOBILE + 24,
  paddingBottom: 0,
  [theme.breakpoints.up("lg")]: {
    paddingTop: APP_BAR_DESKTOP + 24,
    paddingLeft: 0,
    paddingRight: 0,
  },
}));

// ----------------------------------------------------------------------

export default function DashboardLayout() {
  const [open, setOpen] = useState(false);
  const {
    initialState: { menuNum },
    setInitialState,
  } = useModel("@@initialState");

  useEffect(() => {
    socket.connect();
    socket.on("message", (data) => {
      setInitialState((s) => ({
        ...s,
        menuNum: {
          ...s.menuNum,
          ...data?.param,
        },
      }));
    });

    return () => {
      // 关闭 WebSocket 连接
      socket.disconnect();
    };
  }, []);
  return (
    <StyledRoot>
      <Header onOpenNav={() => setOpen(true)} />

      <Nav openNav={open} onCloseNav={() => setOpen(false)} />

      <Main>
        <Scrollbars
          thumbMinSize={10}
          autoHide
          style={{
            width: "100%",
            height: "100%",
          }}
          hideTracksWhenNotNeeded
        >
          <Outlet />
        </Scrollbars>
      </Main>
    </StyledRoot>
  );
}
