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 "./mindMap";
import { TopicType } from "@/enum";

export default function MindMap() {
  const { rightToobarActive, initMindMap, setMindProjectInfo } =
    useModel("mindMapModel");
  const graphRef = useRef<HTMLDivElement>(null);

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

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

  const transData = (item: any): TopicItem => {
    return {
      ...item,
      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 ? { icons: JSON.parse(item.tags) } : {}),
      ...(item?.href ? { icons: JSON.parse(item.href) } : {}),
      ...(item?.links ? { icons: JSON.parse(item.links) } : {}),
      ...(item?.summary ? { icons: JSON.parse(item.summary) } : {}),
      ...(item?.summary ? { icons: JSON.parse(item.summary) } : {}),
    };
  };

  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({
      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,
    }, true);
  }, [data]);

  const params = useParams();

  useEffect(() => {
    if (params?.id) {
      run({ id: params.id });
      sessionStorage.setItem("projectId", 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>
            <HeaderToolbar />
            <RightToolbar />
            <Footer />
          </Layout.Content>
          <Layout.Sider
            className={styles.sider}
            width={rightToobarActive ? 280 : 0}
          >
            <Config />
          </Layout.Sider>
        </Layout>
      </Spin>
    </ConfigProvider>
  );
}
