/*
 * Author: 黎永顺
 * name: 中江-薪资账套薪资项目流向图
 * Description:
 * Date: 2023/11/14
 */
import React, { FunctionComponent, useEffect, useMemo, useState } from "react";
import { Menu } from "antd";
import { FundFlowGraph } from "@ant-design/graphs";
import { exceptStr } from "@/utils/common";
import { extractTree } from "@/pages/salaryItemDiagram";
import styles from "./index.less";

interface OwnProps {
}

type Props = OwnProps;

const index: FunctionComponent<Props> = (props) => {
  const [nodes, setNodes] = useState<any[]>([]);
  const [edges, setEdges] = useState<any[]>([]);
  const [i18n, setI18n] = useState<any>({});
  useEffect(() => {
    window.parent.postMessage({ type: "init" }, "*");
    window.addEventListener("message", receiveMessageFromIndex, false);
    return () => {
      window.removeEventListener("message", receiveMessageFromIndex, false);
    };
  }, []);
  const openNotification = (data: any) => {
    const { formulaId } = data;
    window.parent.postMessage({ type: "turn", payload: { id: "VIEW", params: { formulaId } } }, "*");
  };
  const receiveMessageFromIndex = (event: any) => {
    const data: any = exceptStr(event.data);
    if (!_.isEmpty(data)) {
      const { itemsTree, i18n } = data;
      setI18n(i18n);
      setNodes([{
        id: "0",
        salaryItemName: i18n["薪资项目"],
        value: { text: i18n["薪资项目"] }
      }, ..._.map(extractTree(itemsTree), o => ({
        ...o,
        id: o.salaryItemId.toString(),
        value: { text: o.salaryItemName.length >= 8 ? o.salaryItemName.slice(0, 8) + "..." : o.salaryItemName }
      }))]);
      const edges: any = _.map(extractTree(itemsTree), o => ({
        source: o.parentId ? o.parentId.toString() : "0",
        target: o.salaryItemId.toString()
      }));
      setEdges(edges);
    }
  };
  const config: any = useMemo(() => {
    const data = { nodes, edges };
    return {
      data,
      menuCfg: {
        className: styles.salaryItemOptWrapper,
        shouldBegin: (evt: any) => {
          const { item: { _cfg: { model } } } = evt;
          return model.canAddItem || (!_.isNil(model.formulaId) && model.formulaId !== 0);
        },
        handleMenuClick: (__: any, evt: any) => {
          const { _cfg: { model } } = evt;
          const id = __.innerText.indexOf(i18n["添加薪资项目"]) !== -1 ? "ADD" : "EDIT";
          window.parent.postMessage({
            type: "turn",
            payload: {
              id, params: {
                visible: true, id: model?.groupId, dataType: model?.dateType,
                formulaId: model?.formulaId, valueType: model?.valueType,
                salaryItemId: model?.salaryItemId
              }
            }
          }, "*");
        },
        customContent: (evt: any) => {
          const { item: { _cfg: { model } } } = evt;
          let items: any = [
            { label: i18n["添加薪资项目"], key: "add" },
            { label: i18n["编辑公式"], key: "edit" }
          ];
          (_.isNil(model.formulaId) || model.formulaId === 0) && (items = _.filter(items, o => o.key !== "edit"));
          (!model.canAddItem) && (items = _.filter(items, o => o.key !== "add"));
          return (
            <Menu items={items}/>
          );
        }
      },
      edgeCfg: {
        endArrow: { fill: "#333" },
        style: { stroke: "#333" },
        edgeStateStyles: {
          hover: {
            stroke: "#1890ff",
            lineWidth: 2,
            endArrow: {
              fill: "#1890ff"
            }
          }
        }
      },
      nodeCfg: {
        style: (item: any, group: any) => {
          const { id, parentId } = item;
          let styleObj = {};
          switch (id) {
            case "0":
              styleObj = { ...styleObj, fill: "rgb(0,154,73)", stroke: "rgb(0,154,73)" };
              break;
            default:
              styleObj = { ...styleObj, fill: "#FFF", stroke: "#666", radius: [2, 2, 2, 2] };
              if (_.isNil(parentId)) styleObj = {
                ...styleObj, fill: "rgb(170,212,179)",
                stroke: "#000", radius: [2, 2, 2, 2]
              };
              break;
          }

          return styleObj;
        },
        label: {
          style: (item: any) => {
            const { id } = item;
            return { fontWeight: "bold", fill: id === "0" ? "#FFF" : "#333", fontSize: id === "0" ? 18 : 12 };
          }
        }
      },
      markerCfg: (cfg: any) => {
        const { edges } = data;
        return {
          position: "right",
          show: edges.find((item) => item.source === cfg.id)
        };
      },
      layout: {
        rankdir: "LR",
        // nodesep: 5,
        // ranksep: 20
      },
      tooltipCfg: {
        show: true,
        shouldBegin: (evt: any) => {
          const { item: { _cfg: { model } } } = evt;
          return model.salaryItemName.length >= 8;
        },
        customContent: (item: any) => (<h3>{item.salaryItemName}</h3>)
      },
      onReady: (graph: any) => {
        graph.on("node:click", (evt: any) => {
          if (_.isEmpty(evt.target.attrs) || JSON.stringify(evt.target.attrs).indexOf("cursor") !== -1) return;
          openNotification(evt.item._cfg.model);
        });
        graph.on("node:contextmenu", (evt: any) => {
        });
      },
      behaviors: ["drag-canvas", "zoom-canvas", 'drag-node'],
      // autoFit: false,
      // fitCenter: true
    };
  }, [nodes, edges]);
  return ((!_.isEmpty(nodes) && !_.isEmpty(edges)) ? <FundFlowGraph {...config} /> : null);
};

export default index;
