import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  Button,
  Input,
  Dropdown,
  Tooltip,
  MenuProps,
  Divider,
  message,
} from "antd";
import {
  LeftOutlined,
  MenuOutlined,
  MinusCircleOutlined,
  PlusCircleOutlined,
  RightCircleOutlined,
} from "@ant-design/icons";
import logo from "@/assets/logo.png";
import { useModel, Icon } from "umi";
import { addTopic } from "../../render";
import { TopicType, GraphType } from "@/enum";
import {
  selectTopic,
  addBorder,
  addSummary,
  traverseNode,
} from "../../mindmapHander";
import { createNew } from "@/utils";
import FindReplaceModal from "@/components/FindReplaceModal";
import { useFindReplace } from "@/hooks/useFindReplace";
import { Copy, SaveAll } from "@/api/systemDesigner";
import { UploadFile } from "@/api";
import { base64ToFile, getClassRules } from "@repo/utils";
import { useMindMapStore } from "../../models/mindMapModel";
import { cloneDeep } from "lodash-es";

export default function index() {
  const {
    setMindProjectInfo,
    canRedo,
    canUndo,
    onRedo,
    onUndo,
    enableFormatBrush,
    toggleFormatBrush,
    graph,
    selectedCell,
    setCorrelationEdgeInfo,
  } = useModel("mindmap.mindMapModel");
  const mindProjectInfo = useMindMapStore((state) => state.mindProjectInfo);

  const { setShowHistory } = useModel("appModel");

  const { projectInfo } = useModel("projectModel");

  const {
    handleFind,
    handleReplace,
    // handleReplaceAll,
    handleClose,
    handleFindNext,
    handleFindPrev,
    findCount,
    currentIndex,
    setInstance,
  } = useFindReplace(graph);

  const currentNode = useMemo(() => {
    return selectedCell.filter((cell) => cell.isNode());
  }, [selectedCell]);

  const [title, setTitle] = useState<string>(mindProjectInfo?.name || "");

  useEffect(() => {
    setTitle(mindProjectInfo?.name || "");
  }, [mindProjectInfo?.name]);

  const handleChangeTitle = () => {
    mindProjectInfo &&
      setMindProjectInfo({
        info: {
          ...mindProjectInfo,
          name: title,
        }
      });
  };
  // 预览 todo
  const handlePreview = () => {};

  // 保存
  const handleSave = async () => {
    graph?.toPNG(
      async (dataUri) => {
        const file = base64ToFile(
          dataUri,
          mindProjectInfo?.name || "封面图",
          "image/png"
        );

        const formData = new FormData();
        formData.append("file", file);
        const res = await UploadFile(formData);

        const graphInfo: any = {
          ...(mindProjectInfo || {}),
          ...mindProjectInfo?.pageSetting,
          id: sessionStorage.getItem("projectId"),
          type: GraphType.mindmap,
        };
        delete graphInfo.pageSetting;
        delete graphInfo.topics;

        await SaveAll({
          graph: {
            ...graphInfo,
            coverImage: res?.result?.[0]?.id,
          },
          elements: mindProjectInfo?.topics,
        });

        message.success("保存成功");
      },
      {
        width: 300,
        height: 150,
        quality: 0.2,
        copyStyles: false,
        stylesheet: getClassRules(),
      }
    );
  };

  useEffect(() => {
    graph?.bindKey("ctrl+s", (e: KeyboardEvent) => {
      e.preventDefault();
      handleSave();
    });
  }, [graph]);

  // 克隆 todo
  const handleClone = async () => {
    const res = await Copy({
      fileType: "chart",
      fileId: projectInfo?.graph?.id,
      targetFolderId: projectInfo?.graph?.folderId || "root",
    });
    if (!res.result) return;
    const enterpriseCode = sessionStorage.getItem("enterpriseCode");
    const { pathname, origin } = window.location;
    window.open(
      `${origin}${pathname}#/mindmap/${res.result}?enterpriseCode=${enterpriseCode}`
    );
    message.success("克隆成功");
  };

  // 历史记录
  const handleHistory = () => {
    setShowHistory(true);
  };

  useEffect(() => {
    graph && setInstance(graph);
  }, [graph]);

  const findModalRef = useRef<any>();

  // 增加子主题
  const handleAddSubTopic = () => {
    if (!currentNode.length || !graph) return;

    const topic = addTopic(
      currentNode[0].data.type === TopicType.main
        ? TopicType.branch
        : TopicType.sub,
      setMindProjectInfo,
      graph,
      currentNode[0]
    );

    graph && selectTopic(graph, topic);
  };

  // 添加边框
  const handleAddBorder = () => {
    addBorder(currentNode.filter((item) => item.data.parentId));
  };

  // 添加概要
  const handleAddSummary = () => {
    graph &&
      addSummary(
        currentNode.filter((item) => item.data.parentId),
        graph
      );
  };

  // 添加关联线
  const handleAddCorrelation = () => {
    if (!currentNode.length) return;

    setCorrelationEdgeInfo(currentNode[0]);
  };

  // 导出图片
  const handleExportImage = () => {
    if (!graph) return;

    graph.exportPNG("", {
      quality: 1,
      copyStyles: false,
      stylesheet: getClassRules(),
    });
  };

  // 处理折叠节点
  const handleCollapse = (level: number | boolean) => {
    // 布尔值时展开或折叠全部
    if (typeof level === "boolean") {
      const topics = traverseNode(
        mindProjectInfo?.topics || [],
        (topic, index) => {
          if (topic.type !== TopicType.main) {
            topic.collapsed = level;
          }
        }
      );
      mindProjectInfo &&
        setMindProjectInfo({
          info: {
            ...mindProjectInfo,
            topics,
          },
        });
    } else {
      // 数字时折叠到指定层级
      const topics = traverseNode(
        mindProjectInfo?.topics || [],
        (topic, index, currentLevel = 0) => {
          if (topic.type !== TopicType.main) {
            topic.collapsed = currentLevel >= level;
          }
        }
      );
      mindProjectInfo &&
        setMindProjectInfo({
          info: {
            ...mindProjectInfo,
            topics,
          },
        });
    }
    graph?.centerContent();
  };

  /**
   * 全部替换
   */
  const handleReplaceAll = (searchText: string, replaceText: string) => {
    const info = cloneDeep(mindProjectInfo);
    if(searchText && replaceText) {
      traverseNode(info.topics, (topic) => {
        if (topic.label.includes(searchText)) {
          topic.label = topic.label.replaceAll(searchText, replaceText);
        }
      });
    }
    setMindProjectInfo({ info });
  }

  const menuData: MenuProps["items"] = [
    {
      key: "1",
      label: "新建",
      icon: <i className="w-20px iconfont icon-zengjiahuamian-1" />,
      children: [
        {
          key: "1-1-1",
          label: "流程图",
          icon: <Icon width="20" className="mt-5px" icon="local:flow" />,
          onClick: () => {
            createNew(GraphType.flowchart);
          },
        },
        {
          key: "1-1-2",
          label: "思维导图",
          icon: <Icon width="20" className="mt-5px" icon="local:mind" />,
          onClick: () => {
            createNew(GraphType.mindmap);
          },
        },
        {
          key: "1-1-3",
          label: "UML",
          icon: <Icon width="20" className="mt-5px" icon="local:uml" />,
          onClick: () => {
            createNew(GraphType.uml);
          },
        },
        {
          key: "1-1-4",
          label: "网络拓扑图",
          icon: <Icon width="20" className="mt-5px" icon="local:net" />,
          onClick: () => {
            createNew(GraphType.net);
          },
        },
        {
          key: "1-1-5",
          label: "组织结构图",
          icon: <Icon width="20" className="mt-5px" icon="local:flow" />,
          onClick: () => {
            createNew(GraphType.org);
          },
        },
        {
          key: "1-1-6",
          label: "BPMN",
          icon: <Icon width="20" className="mt-5px" icon="local:bpmn" />,
          onClick: () => {
            createNew(GraphType.bpmn);
          },
        },
      ],
    },
    // {
    //   key: "2",
    //   label: "预览",
    //   icon: <i className="w-20px iconfont icon-yulan" />,
    //   onClick: handlePreview,
    // },
    {
      key: "3",
      label: (
        <div className="flex justify-between">
          <span>保存</span>
          <span>Ctrl+S</span>
        </div>
      ),
      icon: <i className="w-20px iconfont icon-shangchuan" />,
      onClick: handleSave,
    },
    {
      key: "4",
      label: "克隆",
      icon: <i className="w-20px iconfont icon-niantie-1" />,
      onClick: handleClone,
    },
    {
      key: "5",
      label: "查找替换",
      icon: <i className="w-20px iconfont icon-chazhaotihuan" />,
      onClick: () => {
        findModalRef.current?.open();
      },
    },
    {
      key: "7",
      label: "导出图片",
      icon: <i className="w-20px iconfont icon-file-image" />,
      onClick: handleExportImage,
    },
    {
      key: "6",
      label: "历史记录",
      icon: <i className="w-20px iconfont icon-lishijilu" />,
      onClick: handleHistory,
    },
    // {
    //   key: "1-8",
    //   type: "divider",
    // },
  ];

  // 折叠菜单
  const topicCollapseMenu: MenuProps["items"] = [
    {
      key: "1",
      label: "关闭全部主题",
      icon: <MinusCircleOutlined />,
      onClick: () => handleCollapse(true),
    },
    {
      key: "2",
      label: "展开全部主题",
      icon: <PlusCircleOutlined />,
      onClick: () => handleCollapse(false),
    },
    {
      key: "3",
      label: "展开到",
      icon: <RightCircleOutlined />,
      children: [
        {
          key: "3-1",
          label: "一级主题",
          onClick: () => handleCollapse(1),
        },
        {
          key: "3-2",
          label: "二级主题",
          onClick: () => handleCollapse(2),
        },
        {
          key: "3-3",
          label: "三级主题",
          onClick: () => handleCollapse(3),
        },
        {
          key: "3-4",
          label: "四级主题",
          onClick: () => handleCollapse(4),
        },
        {
          key: "3-5",
          label: "五级主题",
          onClick: () => handleCollapse(5),
        },
        {
          key: "3-6",
          label: "六级主题",
          onClick: () => handleCollapse(6),
        },
      ],
    },
  ];

  const noParent = useMemo(() => {
    const nodes = selectedCell?.filter((cell) => cell.isNode());
    return !!(nodes.length && !nodes.find((node) => !node.data?.parentId));
  }, [selectedCell]);

  return (
    <div className="absolute absolute top-8px left-8px bg-white shadow-md flex items-center gap-4px rounded-4px px-8px">
      {/* <Button type="text" icon={<LeftOutlined />}></Button> */}

      <Dropdown
        trigger={["hover"]}
        menu={{ items: menuData, style: { width: 200 } }}
      >
        <div className="flex items-center gap-4px">
          <img className="w-22px" src={logo} />
          <MenuOutlined />
        </div>
      </Dropdown>

      <div className="flex flex-col leading-32px">
        {mindProjectInfo && (
          <Input
            className="text-16px max-w-100px"
            variant="borderless"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onBlur={handleChangeTitle}
            onPressEnter={handleChangeTitle}
          />
        )}
      </div>

      <Tooltip placement="bottom" title="撤销">
        <Button
          type="text"
          icon={<i className="iconfont icon-undo"></i>}
          disabled={!canUndo}
          onClick={onUndo}
        />
      </Tooltip>

      <Tooltip placement="bottom" title="恢复">
        <Button
          type="text"
          icon={<i className="iconfont icon-redo"></i>}
          disabled={!canRedo}
          onClick={onRedo}
        />
      </Tooltip>

      <Tooltip
        placement="bottom"
        title={`格式刷${enableFormatBrush ? "生效中按ESC取消" : "(Ctrl+Shift+C)"}`}
      >
        <Button
          type="text"
          icon={<i className="iconfont icon-geshishua"></i>}
          disabled={!currentNode?.length}
          className={enableFormatBrush && currentNode?.length ? "active" : ""}
          onClick={() => graph && toggleFormatBrush(graph)}
        />
      </Tooltip>

      <Divider type="vertical" />

      <Tooltip placement="bottom" title="子主题">
        <Button
          type="text"
          icon={<i className="iconfont icon-zizhuti"></i>}
          disabled={!currentNode.length}
          onClick={handleAddSubTopic}
        />
      </Tooltip>

      <Tooltip placement="bottom" title="关联线">
        <Button
          type="text"
          icon={<i className="iconfont icon-guanlianxian"></i>}
          disabled={!currentNode.length}
          onClick={handleAddCorrelation}
        />
      </Tooltip>

      <Tooltip placement="bottom" title="概要">
        <Button
          type="text"
          icon={<i className="iconfont icon-summary-outline"></i>}
          disabled={!noParent}
          onClick={handleAddSummary}
        />
      </Tooltip>

      <Tooltip placement="bottom" title="外框">
        <Button
          type="text"
          icon={<i className="iconfont icon-waikuang"></i>}
          disabled={!noParent}
          onClick={handleAddBorder}
        />
      </Tooltip>

      <Dropdown
        menu={{ items: topicCollapseMenu }}
        placement="bottomLeft"
        trigger={["click"]}
      >
        <Tooltip placement="bottom" title="主题折叠">
          <Button type="text" icon={<RightCircleOutlined />} />
        </Tooltip>
      </Dropdown>

      <FindReplaceModal
        ref={findModalRef}
        current={currentIndex}
        count={findCount}
        onClose={handleClose}
        onFind={handleFind}
        onFindNext={handleFindNext}
        onFindPrev={handleFindPrev}
        onReplace={handleReplace}
        onReplaceAll={handleReplaceAll}
        right={80}
        top={10}
      />
    </div>
  );
}
