import React, { useEffect, useRef } from "react";
import { Layout, ConfigProvider, Spin } from "antd";
import styles from "./index.less";
import "./index.less";
import RightToolbar from "./components/RightToolbar";
import HeaderToolbar from "./components/HeaderToolbar";
import { useModel, useRequest, useParams } from "umi";
import Footer from "./components/Footer";
import Config from "./components/Config";
import SvgComponent from "./components/SvgComponent";
import { FlowchartMindMapInfo } from "@/api/systemDesigner";
import { defaultProject, topicData } from "@/config/data";
import { TopicItem } from "@/types";
import { buildTopic } from "./render";
import { TopicType } from "@/enum";
import HistoryPanel from "@/components/HistoryPanel";

export default function MindMap() {
  const { rightToobarActive, initMindMap, setMindProjectInfo } =
    useModel("mindmap.mindMapModel");
  const graphRef = useRef<HTMLDivElement>(null);
  const { showHistory, mindmapRightPanelWidth } = useModel("appModel");
  const { setProjectInfo } = useModel("projectModel");

  useEffect(() => {
    graphRef.current && initMindMap(graphRef.current);
  }, []);

  // 获取项目详情
  const { loading, run, data } = useRequest(FlowchartMindMapInfo, {
    manual: true,
  });

  const transData = (item: any): TopicItem => {
    return {
      ...item,
      parentId: null,
      edge: JSON.parse(item.edge),
      fill: JSON.parse(item.fill),
      links: JSON.parse(item.links),
      text: JSON.parse(item.text),
      stroke: JSON.parse(item.stroke),
      children: JSON.parse(item.children),
      ...(item?.extraModules
        ? { extraModules: JSON.parse(item.extraModules) }
        : {}),
      ...(item?.icons ? { icons: JSON.parse(item.icons) } : {}),
      ...(item?.tags ? { tags: JSON.parse(item.tags) } : {}),
      ...(item?.href ? { href: JSON.parse(item.href) } : {}),
      ...(item?.links ? { links: JSON.parse(item.links) } : {}),
      ...(item?.summary ? { summary: JSON.parse(item.summary) } : {}),
      ...(item?.border ? { border: JSON.parse(item.border) } : {}),
    };
  };

  useEffect(() => {
    if (!data) return;
    const graphInfo = data?.result?.graph || {};
    const topics = (data?.result?.elements || []).map((item: any) =>
      transData(item)
    );

    if (!topics.length) {
      const mainTopic = buildTopic(TopicType.main, {
        label: "中心主题",
        fill: {
          ...topicData.fill,
          color1: "#30304D",
        },
        text: {
          ...topicData.text,
          fontSize: 30,
          color: "#fff",
        },
      });
      if (mainTopic) {
        topics.push(mainTopic);
      }
    }
    setMindProjectInfo({
      info: {
        name: graphInfo.name,
        desc: graphInfo?.desc || "",
        version: graphInfo.version,
        author: graphInfo?.author || "",
        theme: graphInfo?.theme || defaultProject.theme,
        structure: graphInfo?.structure || defaultProject.structure,
        pageSetting: {
          backgroundType:
            graphInfo?.backgroundType ||
            defaultProject.pageSetting.backgroundType,
          backgroundColor:
            graphInfo?.backgroundColor ||
            defaultProject.pageSetting.backgroundColor,
          backgroundImage:
            graphInfo?.backgroundImage ||
            defaultProject.pageSetting.backgroundImage,
          branchY: graphInfo?.branchY || defaultProject.pageSetting.branchY,
          branchX: graphInfo?.branchX || defaultProject.pageSetting.branchX,
          subTopicY:
            graphInfo?.subTopicY || defaultProject.pageSetting.subTopicY,
          subTopicX:
            graphInfo?.subTopicX || defaultProject.pageSetting.subTopicX,
          alignSameTopic:
            graphInfo?.alignSameTopic ||
            defaultProject.pageSetting.alignSameTopic,
          showWatermark:
            graphInfo?.showWatermark ||
            defaultProject.pageSetting.showWatermark,
          watermarkText:
            graphInfo?.watermarkText ||
            defaultProject.pageSetting.watermarkText,
        },
        topics,
      },
      init: true
    });

    setProjectInfo(data.result);
  }, [data]);

  const params = useParams();

  useEffect(() => {
    if (params?.id) {
      run({ id: params.id });
      sessionStorage.setItem("projectId", params.id);
    }
  }, []);

  const handleRevert = () => {
    if (params?.id) {
      run({ id: params.id });
    }
  };

  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.keyCode === 61 ||
            event.keyCode === 107 ||
            event.keyCode === 173 ||
            event.keyCode === 109 ||
            event.keyCode === 187 ||
            event.keyCode === 189 ||
            event.keyCode === 80)
        ) {
          event.preventDefault();
        }
      },
      false
    );
  }, []);

  return (
    <ConfigProvider
      // componentSize="small"
      prefixCls="shalu"
      theme={{
        token: {
          colorPrimary: "#1890ff",
        },
      }}
    >
      <SvgComponent />
      <Spin spinning={loading}>
        <Layout className="w-100vw h-100vh">
          <Layout.Content className={styles.container + " relative"}>
            <div ref={graphRef} className="w-full h-full"></div>
            {showHistory ? (
              <div className="absolute bottom-0 left-0 h-95vh w-200px shadow-md">
                <HistoryPanel
                  graphId={params.id ? params.id : ""}
                  onRevert={handleRevert}
                />
              </div>
            ) : null}
            <HeaderToolbar />
            <RightToolbar />
            <Footer />
          </Layout.Content>
          <Layout.Sider
            className={styles.sider}
            width={rightToobarActive ? mindmapRightPanelWidth : 0}
          >
            <Config />
          </Layout.Sider>
        </Layout>
      </Spin>
    </ConfigProvider>
  );
}
