/*
 * Author: 黎永顺
 * name: 薪资账套-薪资项目查看
 * Description:
 * Date: 2023/11/30
 */
import type { MutableRefObject } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { notification } from "antd";
import type { RelationGraphExpose, RGNode, RGNodeSlotProps, RGOptions } from "relation-graph/react";
import RelationGraph from "relation-graph/react";
import { exceptStr } from "@/utils/common";
import { extractTree } from "@/pages/salaryItemDiagram";
import cs from "classnames";
import styles from "../salaryItemFlowGraph/index.less";

const NodeSlot: React.FC<RGNodeSlotProps> = ({ node }) => {
  if (node.id === "0") {
    return <div className={styles.rootNode}> {node.text} </div>;
  }
  // @ts-ignore
  if (node.id !== "0" && !node.data.parentId) {
    return <div className={cs(styles.levelNode, styles.commonNode)}> {node.text} </div>;
  }
  return <div className={styles.commonNode}>
    <span title={node.text}>{node.text}</span>
  </div>;
};
const Index: React.FC = () => {
  const [itemsTree, setItemsTree] = useState<any[]>([]);
  const [i18n, setI18n] = useState<any>({});
  const graphRef = useRef() as MutableRefObject<RelationGraphExpose>;
  useEffect(() => {
    window.parent.postMessage({ type: "initDiagram" }, "*");
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);
  const receiveMessageFromIndex = (event: any) => {
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { itemsTree, i18n } = data;
      setI18n(i18n);
      setItemsTree(itemsTree);
    }
  };
  const dataSource: any = useMemo(() => {
    return {
      rootId: "0",
      // { id: "0", text: i18n["薪资项目"] },
      nodes: [..._.map(extractTree(itemsTree), o => ({
        id: o.salaryItemId,
        text: o.salaryItemName, data: { ...o }
      }))],
      lines: _.map(extractTree(itemsTree), o => ({
        from: o.parentId ? o.parentId : "0",
        to: o.salaryItemId
      })).filter(g => g.from !== "0")
    };
  }, [itemsTree, i18n]);
  useEffect(() => {
    if (!_.isEmpty(dataSource.nodes)) {
      const init = showGraph();
    }
  }, [dataSource]);
  const showGraph = async () => {
    await graphRef.current.setJsonData(dataSource, (graphInstance) => {
    });
  };
  const options: RGOptions = useMemo(() => {
    return {
      debug: false,
      layout: {
        label: "树",
        layoutName: "tree",
        layoutClassName: "seeks-layout-center",
        from: "left",
        // 通过这4个属性来调整 tree-层级距离&节点距离
        min_per_width: 500,
        max_per_width: 500,
        min_per_height: 60,
        max_per_height: undefined
        // levelDistance: "" // 如果此选项有值，则优先级高于上面那4个选项
      },
      defaultExpandHolderPosition: "right",
      defaultNodeWidth: 180,
      defaultNodeHeight: 50,
      defaultLineShape: 4,
      defaultNodeBorderWidth: 1,
      defaultLineColor: "#333",
      defaultExpandHolderColor: "rgba(0, 206, 209, 1)",
      defaultNodeColor: "transparent",
      defaultNodeBorderColor: "#333",
      allowShowMiniToolBar: false //工具栏展示与否
    };
  }, []);
  const onNodeClick = (node: RGNode) => {
    if (node.type === "node") {
      // @ts-ignore
      const { formula } = node?.data;
      notification.destroy();
      if (_.isEmpty(formula)) return;
      const { formula: description } = formula;
      notification.open({
        message: i18n["公式"],
        duration: 5,
        description,
        style: { maxWidth: 600 }
      });
    }
    return true;
  };
  return <div style={{ height: "100%", width: "100%" }}>
    <RelationGraph ref={graphRef} options={options} nodeSlot={NodeSlot}
      // @ts-ignore
                   onNodeClick={onNodeClick}
    />
  </div>;
};
export default Index;
