import { Stencil } from '@antv/x6-plugin-stencil';
import { nextTick } from 'vue';
import { registerCustomNode } from './registerNode';
import { queryAllApplicationApi, queryApplicationConfigApi } 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';
import { v4 as uuidv4 } from 'uuid';

const commonStore = CommonStore();

export let appList: any[] = [];

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

  const nodeListObj = await getNodeList();

  graph.appListInfo = 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,
      },
    ],
  };
  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);

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

  stencil.dnd.options.getDropNode = (node: any) => {
    const currentId = 'uuid-node-' + node.data.label + '-' + uuidv4();
    return graph.createNode({
      id: currentId,
      shape: node.data.isApp ? 'custom-app-vue-node' : 'custom-local-vue-node',
      // shape: 'custom-app-vue-node',
      data: { ...node.data, currentId },
    });
  };
};

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,
          nodeTypeValue: nodeListObj[key].type,
          iconUrl: item.isLocal ? item.appImage : FileUtil.getFilePreviewImgPathUrl(item.appImage),
          appPath: item.appPath ? item.appPath : '',
          preScripts: [],
          postScripts: [],
          pageConfigList: [],
          postExeCommand: '', // 执行命令
          nodeExeCommand: '', // 节点执行命令
          preExeCommand: '', // 执行命令
          nodeCondition: 'and', // 节点条件
          exeMethod: 'serviceTask', // 执行方式
          inputFormat: '', // 输入主文件格式
          slaveFormat: '', // 输入附文件格式
          outputFormat: '', // 输出文件格式
          beforeNodeId: '', // 输入节点，上一个节点
          nodeParamConfigName: item.nodeParamConfigName || '', // 当前节点的默认配置(需要在应用中心配置界面进行配置)
          // currentId: item.id, // 当前节点id
        },
      })
    );
    if (stencil) {
      stencil.load(imageNodes, 'group' + key);
    }
  }
};

export const getNodeList = async (noload?: any) => {
  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 param = {
    appName: '',
    current: 1,
    size: 999,
  };
  const res: any = await queryAllApplicationApi(param);
  if (res.code === 200) {
    appList = [];

    const apps: any = res.data.data || [];

    for (let i = 0; i < apps.length; i++) {
      if (apps[i].appStatus === 1) {
        if (!noload) {
          apps[i].nodeParamConfigName = await getAppConfigListFun(apps[i].uuid);
        }
        typeKeyArray[apps[i].appType].nodes.push(apps[i]);
        appList.push(apps[i]);
      }
    }

    // res.data.data.forEach((item: any) => {
    //   // 启用的app才能在流程中使用
    //   if (item.appStatus === 1) {
    //     typeKeyArray[item.appType].nodes.push(item);
    //     appList.push(item);
    //   }
    // });
  }

  return typeKeyArray;
};

/**
 *
 * @param appId 获取app的配置信息
 */
export const getAppConfigListFun = async (appId: string) => {
  const res: any = await queryApplicationConfigApi({
    appId,
  });
  if (res && res.code == 200) {
    if (res.data?.length) {
      return res.data[0]?.configName;
    } else {
      return '';
    }
  } else {
    return '';
  }
};
