import { Stencil } from '@antv/x6-plugin-stencil';
import { nextTick } from 'vue';
import { registerCustomNode } from './registerNode';
import { queryAllApplicationApi } from '@/api/system/application';
import { CommonStore } from '@/stores/common';
import { FileUtil } from '@/utils/file';
// import startImg from '@/assets/imgs/dragFlow/dragIcon/start.svg';
import stencilStartImg from '@/assets/imgs/dragFlow/dragIcon/stencil_start.svg';
import stencilEndImg from '@/assets/imgs/dragFlow/dragIcon/stencil_end.svg';
import { FLOW_CREATE_ID } from './initGraph';
import { FLOW_NODE_TYPE_ENUM } from '@/utils/enum/flow';

const commonStore = CommonStore();

export const stencilRegister = async (graph: any) => {

  registerCustomNode();

  const nodeListObj = await getNodeList();
  console.log('nodeList1', nodeListObj);
  nodeListObj[0] = {
    label: '起始节点',
    type: 'local',
    nodes: [
      {
        appImage: stencilStartImg,
        isLocal: true,
        appName: '起始节点',
        nodeType: FLOW_NODE_TYPE_ENUM.START,
      },
      {
        appImage: stencilEndImg,
        isLocal: true,
        appName: '结束节点',
        nodeType: FLOW_NODE_TYPE_ENUM.END,
      },
    ],
  };
  console.log('nodeList2', nodeListObj);
  const groups:any = [];
  for (const key in nodeListObj) {
    groups.push({ name: 'group' + key, title: nodeListObj[key].label });
  }

  const stencil:Stencil = new Stencil({
    title: 'Stencil',
    target: graph,
    // search(cell, keyword) {
    //   return cell.shape.indexOf(keyword) !== -1;
    // },
    placeholder: 'Search by shape name',
    notFoundText: 'Not Found',
    // collapsable: true,
    stencilGraphHeight: 0,
    layoutOptions: {
      columns: 3,
      columnWidth: 66,
      rowHeight: 70,
      // marginX: -8,
      // marginY: -15,
    },
    groups: groups,
  });
  const containerHtml = document.getElementById(FLOW_CREATE_ID) as HTMLElement;
  const stencilContainer = document.createElement('div');
  stencilContainer.id = 'stencil';
  containerHtml.appendChild(stencilContainer);
  console.log('containerHtml', containerHtml);

  nextTick( () => {
    const stencilHtml = document.getElementById('stencil') as HTMLElement;
    console.log('stencilHtml', stencilHtml);
    stencilHtml.appendChild(stencil.container);
    createNode(nodeListObj, graph, stencil);
    // const res = await queryAllApplicationApi();

    console.log('groups', groups);
  });

  console.log('stencil', stencil);
  stencil.dnd.options.getDropNode = (node: any) => {
    console.log('node', node);
    return graph.createNode({
      shape: node.data.isApp ? 'custom-app-vue-node' : 'custom-local-vue-node',
      // shape: 'custom-app-vue-node',
      data: { ...node.data },
    });
  };

};

export const createNode = (nodeListObj:any, graph:any, stencil?:any) => {
  for (const key in nodeListObj) {
    const imageNodes = nodeListObj[key].nodes.map((item:any) =>
      graph.createNode({
        shape: 'custom-stencil-node',
        label: item.appName,
        attrs: {
          image: {
            'xlink:href': item.isLocal ? item.appImage : FileUtil.getFilePreviewImgPathUrl(item.appImage),
          },
          // body: {
          //   fill: '#EBEBEB',
          // },
        },
        data: {
          label: item.appName,
          // 是否为应用中心的节点
          isApp: !item.isLocal,
          uuid: item.isLocal ? '' : item.uuid,
          type: item.isLocal ? nodeListObj[key].type : nodeListObj[key].label,
          nodeType: item.isLocal ? item.nodeType : nodeListObj[key].label,
          iconUrl: item.isLocal ? item.appImage : FileUtil.getFilePreviewImgPathUrl(item.appImage),
          preScripts: [],
          postScripts: [],
          pageConfigList: [],
          postExeCommand: '', // 执行命令
          preExeCommand: '', // 执行命令
          nodeCondition: 'and', // 节点条件
          exeMethod: 'serviceTask', // 执行方式
          inputFormat: '', // 输入文件格式
          outputFormat: '', // 输出文件格式
        },
      })
    );
    if (stencil) {
      stencil.load(imageNodes, 'group' + key);
    }
    console.log('imageNodes', imageNodes, 'group' + key);
  }
};

export const getNodeList = async () => {
  const typeList: any = (await commonStore.getDictData('APP_TYPE') as any).A;
  const typeKeyArray:any = {};
  typeList.forEach((item: any) => {
    typeKeyArray[item.value] = { label: item.label, type: item.value, nodes: [] };
  });
  const res:any = await queryAllApplicationApi();
  if (res.code === 200) {
    res.data.forEach((item: any) => {
      typeKeyArray[item.appType].nodes.push(item);
    });
  }
  return typeKeyArray;
};
