import G6 from "@antv/g6";

// 最多几个分支选项
const maxOptionsNums = 4;

// 根据不同节点的不同状态展示对应的下拉菜单
const createMenuListByNode = {
  // 根节点
  "root-node": (node, model) => {
    const data = model.data || {};
    // 判断是否已经填写
    const hasData = !!data.name;
    const children = model.children || [];

    return `<ul class="menu-list">
        ${
          children.length >= maxOptionsNums
            ? ``
            : `<li class="menu-item" data-type="create-plot">创建剧情模块</li> <li class="menu-item" data-type="create-jump">创建跳转模块</li>`
        }
        ${
          children.length < maxOptionsNums && hasData
            ? `<li class="menu-item-split"></li>`
            : ""
        }
        ${
          hasData ? `<li class="menu-item" data-type="clean">清空模块</li>` : ""
        }
      </ul>`;
  },
  // 剧情模块
  "plot-node": (node, model) => {
    const data = model.data || {};
    // 判断是否已经填写
    const hasData = !!data.name;
    const children = model.children || [];

    return `<ul class="menu-list">
        ${
          children.length >= maxOptionsNums
            ? ``
            : `<li class="menu-item" data-type="create-plot">创建剧情模块</li> <li class="menu-item" data-type="create-jump">创建跳转模块</li><li class="menu-item-split"></li>`
        }
        ${
          hasData ? `<li class="menu-item" data-type="clean">清空模块</li>` : ""
        }
        <li class="menu-item" data-type="delete">删除模块</li>
      </ul>`;
  },
  // 跳转模块
  "jump-node": () => {
    return `<ul class="menu-list">
        <li class="menu-item" data-type="delete">删除模块</li>
      </ul>`;
  },
};

// 剧情节点data的默认值
const plotNodeDefaultData = {
  name: "",
  image: "",
  url: "",
  materialId: "",
  question: "",
};

// 跳转节点data的默认值
const jumpNodeDefaultData = {
  jumpNodeName: "",
  jumpNodeId: "",
};

// 不同点击类型的功能处理
const menuClickFuncMap = {
  // 创建剧情模块
  "create-plot": (node, graph) => {
    const model = node.getModel();
    const children = model.children || [];
    // 当前选项的字母
    const newOptionType = String.fromCharCode(65 + children.length);
    // 新节点的 id
    const newNodeId = new Date().getTime() + "";
    graph.addChild(
      {
        id: newNodeId,
        type: "plot-node",
        preNodeId: model.id,
        data: {
          ...plotNodeDefaultData,
          optionType: newOptionType,
          optionName: "",
        },
      },
      model.id
    );
    graph.fitCenter();
  },
  // 创建跳转模块
  "create-jump": (node, graph) => {
    const model = node.getModel();
    const children = model.children || [];
    // 当前选项的字母
    const newOptionType = String.fromCharCode(65 + children.length);
    // 新节点的 id
    const newNodeId = new Date().getTime() + "";
    graph.addChild(
      {
        id: newNodeId,
        type: "jump-node",
        preNodeId: model.id,
        data: {
          ...jumpNodeDefaultData,
          optionType: newOptionType,
          optionName: "",
        },
      },
      model.id
    );
    graph.fitCenter();
  },
  // 清空模块数据
  clean: (node, graph) => {
    const defaultData =
      node.getModel().type === "plot-node"
        ? plotNodeDefaultData
        : jumpNodeDefaultData;
    graph.updateItem(node, {
      data: defaultData,
    });
    graph.layout(false);
  },
  // 删除模块
  delete: (node, graph) => {
    const model = node.getModel();
    // 获取父节点
    const pNode = node.get("parent");
    if (!pNode) return;
    const pModel = pNode.getModel();

    let _tempNum = 0;
    const _children = [];
    // 全量更新子节点数据
    pModel.children.forEach((item) => {
      // 不是被删除节点，需要添加进入新的数组
      if (item.id !== model.id) {
        _children.push({
          ...item,
          data: {
            ...item.data,
            optionType: String.fromCharCode(65 + _tempNum),
          },
        });
        _tempNum += 1;
      }
    });
    graph.updateChildren(_children, pModel.id);
  },
};

// 菜单配置
const menuConfig = {
  offsetX: 6,
  offsetY: 10,
  itemTypes: ["node"],
  // 获取菜单内容
  getContent(e) {
    // console.log('getContent', e, e.item.getModel())
    const node = e.item;
    const model = node.getModel();
    // const graph = e.currentTarget
    const outDiv = document.createElement("div");
    outDiv.style.width = "180px";
    outDiv.style.fontSize = "14px";
    outDiv.style.lineHeight = "20px";
    outDiv.innerHTML = createMenuListByNode[model.type]
      ? createMenuListByNode[model.type](node, model)
      : "";
    return outDiv;
  },
  // 控制菜单是否出现
  shouldBegin(e) {
    const actionType = e.target.get("action");
    // console.log('shouldBegin', e, e.target.get('action'))
    if (actionType === "tips") return false;
    return true;
  },
  handleMenuClick(target, item, graph) {
    const type = target.dataset.type;
    if (!type || !menuClickFuncMap[type]) return;
    menuClickFuncMap[type](item, graph);
  },
};

// 注册图表插件
const useGraphPlugins = () => {
  const toolbar = new G6.ToolBar();
  const grid = new G6.Grid();
  const menu = new G6.Menu(menuConfig);

  return {
    toolbar,
    grid,
    menu,
  };
};

export default useGraphPlugins;
