import { reactive, ref } from 'vue';
import { FLOW_CREATE_ID } from './initGraph';
import { ElMessage } from 'element-plus';

// 控制连接桩显示/隐藏
const showPorts = (ports: NodeListOf<SVGElement>, show: boolean) => {
  for (let i = 0, len = ports.length; i < len; i += 1) {
    ports[i].style.visibility = show ? 'visible' : 'hidden';
  }
};
/** 选中的节点 */
let selectNode: any = null;

export const initNodeEvents = (graph: any) => {
  graph.on('node:mouseenter', () => {
    const container = document.getElementById(FLOW_CREATE_ID)!;
    const ports = container.querySelectorAll('.x6-port-body') as NodeListOf<SVGElement>;
    showPorts(ports, true);
  });
  graph.on('node:mouseleave', () => {
    const container = document.getElementById(FLOW_CREATE_ID)!;
    const ports = container.querySelectorAll('.x6-port-body') as NodeListOf<SVGElement>;
    showPorts(ports, false);
  });
  graph.on('node:selected', () => {
    // const flowElement = document.getElementById('flow-create-content') as HTMLElement;
    // flowElement.tabIndex = -1;
    // flowElement.focus();
  });
  graph.on('node:unselected', ({ node }: any) => {
    node.removeTools();
    const container = document.getElementById(FLOW_CREATE_ID)!;
    const ports = container.querySelectorAll('.x6-port-body') as NodeListOf<SVGElement>;
    showPorts(ports, false);
    drawerVisible.value = false;
    selectNode = null;
  });

  graph.on('node:click', ({ node }: any) => {
    if (node.data.isApp) {
      drawerVisible.value = true;
      updateNodeAttribute(node.data);
      selectNode = node;
      // for (const key in node.data) {
      //   nodeAttribute[key] = node.data[key];
      // }
    }

    // graph.cleanSelection();
    node.addTools({
      name: 'boundary',
      args: {
        padding: 0,
        attrs: {
          // fill: '#7c68fc',
          stroke: '#0366FF ',
          'stroke-width': 2,
          'stroke-dasharray': '',
          rx: 4,
          ry: 4,
        },
      },
    });
  });
  graph.on('edge:click', ({ edge }: any) => {
    // graph.cleanSelection();
    edge.addTools({
      name: 'boundary',
      args: {
        padding: 5,
        attrs: {
          // fill: '#7c68fc',
          stroke: '#333',
          'stroke-width': 0.5,
          'fill-opacity': 0.2,
        },
      },
    });
  });
  graph.on('edge:unselected', ({ edge }: any) => {
    edge.removeTools();
  });
};

export const useNodeEvents = () => {
  return {
    undoFun,
    deleteFun,
    zoomInFun,
    zoomOutFun,
    yAlign,
    xAlign,
  };
};

const undoFun = (graph: any) => {
  graph.undo();
};

const deleteFun = (graph: any) => {
  const nodes = graph.getSelectedCells();
  graph.removeCells(nodes);
};

const zoomInFun = (graph: any) => {
  graph.zoom(-0.2);
};

const zoomOutFun = (graph: any) => {
  graph.zoom(0.2);
};

/**
 * 全部左对齐
 * @param graph
 */
// const xAlign = (graph: any) => {
//   const nodes = graph.getSelectedCells();
//   let x = 0;
//   for (let index = 0; index < nodes.length; index++) {
//     if (x === 0 || x > nodes[index].position().x) {
//       x = nodes[index].position().x;
//     }
//   }
//   for (let index = 0; index < nodes.length; index++) {
//     nodes[index].position(x, nodes[index].position().y);
//   }
// };

/**
 * 横向分布
 * @param graph
 */
const xAlign = (graph: any) => {
  const nodes = graph.getSelectedCells();
  if (nodes.length > 2) {
    nodes.sort((a: any, b: any) => {
      return a.position().x - b.position().x;
    });
    const xLength = nodes[1].position().x - nodes[0].position().x - nodes[0].size().width;
    for (let index = 2; index < nodes.length; index++) {
      nodes[index].position(
        nodes[index - 1].position().x + nodes[index - 1].size().width + xLength,
        nodes[index].position().y
      );
    }
  } else {
    ElMessage.warning('请框选超过 2 个节点！');
  }
  // for (let index = 0; index < nodes.length; index++) {
  //   nodes[index].position(x, nodes[index].position().y);
  // }
};

const yAlign = (graph: any) => {
  const nodes = graph.getSelectedCells();
  if (nodes.length > 1) {
    let y = 0;
    for (let index = 0; index < nodes.length; index++) {
      if (y === 0 || y > nodes[index].position().y) {
        y = nodes[index].position().y;
      }
    }
    for (let index = 0; index < nodes.length; index++) {
      nodes[index].position(nodes[index].position().x, y);
    }
  } else {
    ElMessage.warning('请框选超过 1 个节点！');
  }
};

const drawerVisible = ref(false);

export const useNodeAttribute = () => {
  return {
    drawerVisible,
    nodeAttribute,
  };
};

export const nodeAttribute = reactive<any>({
  label: '',
  uuid: '',
  type: '',
  iconUrl: '',
  appPath: '',
  preScripts: [],
  postScripts: [],
  postExeCommand: '', // 执行命令
  nodeExeCommand: '', // 节点执行命令
  preExeCommand: '', // 执行命令
  nodeCondition: 'and', // 节点条件
  exeMethod: 'serviceTask', // 执行方式
  inputFormat: '', // 输入文件格式
  outputFormat: '', // 输出文件格式
  beforeNodeId: '', // 输入节点，上一个节点
  pageConfigList: [],
});

export const updateNodeAttribute = (val: any) => {
  for (const key in val) {
    nodeAttribute[key] = val[key];
  }
  if (selectNode) {
    selectNode.setData(nodeAttribute);
  }
};
