import React, { useEffect } from "react";
import { Input, Layout, Tabs, ConfigProvider, Spin } from "antd";
import type { TabsProps } from "antd/lib";
import Toolbar from "./components/Toolbar";
import TablePanel from "./components/TablePanel";
import RelationPanel from "./components/RelationPanel";
import ThemePanel from "./components/ThemePanel";
import RemarkPanel from "./components/RemarkPanel";
import Navigator from "./components/Navigator";
import Menu from "./components/Menu";
import { useModel, useRequest, useParams } from "umi";
import "./index.less";
import { useSessionStorageState } from "ahooks";
import {
  EnvironmentOutlined,
  FullscreenExitOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons";
import { GetDataModelDetail } from "@/api";

const { Header, Content, Sider } = Layout;

const App: React.FC = () => {
  const containerRef = React.useRef(null);
  const { initGraph, project, playModeEnable, exitPlayMode, setProject, graph } =
    useModel("erModel");
  const [tabActiveKey, setTabActiveKey] = useSessionStorageState(
    "tabs-active-key",
    {
      defaultValue: "1",
      listenStorageChange: true,
    }
  );
  // 更新画布key 用于刷新画布
  const [updateKey, setUpdateKey] = useSessionStorageState("update-key", {
    listenStorageChange: true,
    defaultValue: 0,
  });
  const [show, setShow] = useSessionStorageState("show-navigator");
  const params = useParams();

  const { run, loading, refresh } = useRequest(GetDataModelDetail, {
    manual: true,
    onSuccess: (res) => {
      console.log("模型详情:", res);
      const result = res?.result;
      if (result) {
        setProject(result, false, true);
        graph?.centerContent();
      }
    },
  });

  useEffect(() => {
    exitPlayMode();
    if (containerRef.current) {
      initGraph(containerRef.current);
    }
    if (!project.id && params?.id) {
      run({
        id: params.id,
      });
    }
  }, []);

  useEffect(() => {
    if (params?.id && updateKey) {
      run({
        id: params.id,
      });
    }
  }, [updateKey]);

  useEffect(() => {
    // 监听浏览器tab切换 刷新数据
    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        refresh();
      }
    };
    document.addEventListener("visibilitychange", handleVisibilityChange);
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  });

  const tabItems: TabsProps["items"] = [
    {
      key: "1",
      label: "表",
      children: <TablePanel />,
    },
    {
      key: "2",
      label: "关系",
      children: <RelationPanel />,
    },
    {
      key: "3",
      label: "主题区域",
      children: <ThemePanel />,
    },
    {
      key: "4",
      label: "注释",
      children: <RemarkPanel />,
    },
  ];

  useEffect(() => {
    document.addEventListener(
      "mousewheel",
      function (e: any) {
        // 判断是否按下ctrl
        if (e.ctrlKey) {
          // 阻止默认事件
          e.preventDefault();
        }
      },
      { capture: false, passive: false }
    );
    document.addEventListener(
      "keydown",
      function (event) {
        if (
          (event.ctrlKey === true || event.metaKey === true) &&
          event.key.toLowerCase() === "s"
        ) {
          event.preventDefault();
        }
      },
      false
    );
  }, []);

  return (
    <Spin spinning={loading}>
      <Layout className="h-100vh">
        {!playModeEnable && (
          <Header
            className="bg-white h-100px border-b-1px border-b-solid border-b-gray-200 p-x-0 flex flex-col"
            style={{
              height: project.setting.showMenu ? "100px" : "32px",
              transition: "all 0.3s ease-in-out",
            }}
          >
            <div
              className="grid"
              style={{
                gridTemplateRows: project.setting.showMenu ? "1fr" : "0fr",
                transition: "all 0.3s",
              }}
            >
              <div className="overflow-hidden">
                <Menu />
              </div>
            </div>
            <Toolbar />
          </Header>
        )}
        <Layout>
          {!playModeEnable && (
            <Sider
              width={project.setting.showSidebar ? 360 : 0}
              style={{ background: "#fff", borderRight: "1px solid #eee" }}
            >
              <ConfigProvider
                theme={{
                  components: {
                    Tabs: {
                      colorPrimary: "#000",
                    },
                  },
                }}
              >
                <Tabs
                  animated
                  activeKey={tabActiveKey}
                  onChange={setTabActiveKey}
                  items={tabItems}
                  centered
                />
              </ConfigProvider>
            </Sider>
          )}
          <Layout>
            <Content className="overflow-hidden">
              <div id="graph-container" ref={containerRef}></div>
              <Navigator key="editor" />
              {playModeEnable && (
                <div className="absolute top-32px right-32px z-2">
                  <div className="left bg-#fff shadow-md p-x-4px p-y-4px flex items-center gap-8px">
                    <div
                      className="
                    rounded-4px 
                    cus-btn 
                    w-32px 
                    h-32px
                    bg-#eee 
                    flex-none 
                    text-center 
                    leading-32px 
                    cursor-pointer 
                    hover:bg-#ddd"
                    >
                      <UnorderedListOutlined />
                    </div>
                    <div
                      className="
                    rounded-4px 
                    cus-btn 
                    w-32px 
                    h-32px
                    bg-#eee 
                    flex-none 
                    text-center 
                    leading-32px 
                    cursor-pointer 
                    hover:bg-#ddd"
                    >
                      <EnvironmentOutlined onClick={() => setShow(!show)} />
                    </div>
                    <div
                      className="
                    rounded-4px 
                    cus-btn 
                    w-32px 
                    h-32px
                    bg-#eee 
                    flex-none 
                    text-center 
                    leading-32px 
                    cursor-pointer 
                    hover:bg-#ddd"
                      onClick={() => exitPlayMode()}
                    >
                      <FullscreenExitOutlined />
                    </div>
                  </div>
                </div>
              )}
            </Content>
          </Layout>
        </Layout>
      </Layout>
    </Spin>
  );
};

export default App;
