function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useImperativeHandle, useState } from 'react';
import _ from 'lodash';
import { Graph } from '@antv/x6';
import './customNode';
import './styles/index.less';
import FlowToolbar from './toolbar';
import graphConfig from './graphConfig';
import CdpFlowTypes from '../../types/flow';
import FlowEdge from './customNode/edge';
import request from '../../utils/ajax';
import apis from '../../constants/api';
import { FlowIterator } from './util';
export function getData(graph_) {
  if (!graph_) return null;
  var lineList = [];
  var nodeList = [];
  graph_.toJSON().cells.forEach(function (cell) {
    var id = cell.id,
      shape = cell.shape,
      position = cell.position,
      size = cell.size,
      data = cell.data,
      source = cell.source,
      target = cell.target,
      ports = cell.ports;
    if (data) delete data.runCode;
    var res = {
      id: id,
      shape: shape,
      position: position,
      size: size,
      data: data,
      source: source,
      target: target,
      ports: ports === null || ports === void 0 ? void 0 : ports.items
    };
    for (var key in res) {
      if (res[key] === undefined) delete res[key];
    }
    if (shape === CdpFlowTypes.Shape.line) {
      lineList.push(res);
    } else {
      nodeList.push(res);
    }
  });
  return {
    lineList: lineList,
    nodeList: nodeList
  };
}
var VisualFlow = function VisualFlow(props, ref) {
  var className = props.className,
    defaultValue = props.defaultValue,
    readonly = props.readonly;
  var id = "flow-".concat(_.random(true));
  var _useState = useState(),
    _useState2 = _slicedToArray(_useState, 2),
    graph = _useState2[0],
    setGraph = _useState2[1];
  useEffect(function () {
    initGraph();
    return function () {
      /**
       * 销毁画布
       */
      graph === null || graph === void 0 ? void 0 : graph.dispose();
    };
  }, []);
  useImperativeHandle(ref, function () {
    var res = {
      graph: graph
    };
    return res;
  });
  function initGraph() {
    var container = document.getElementById(id);
    var graph_ = new Graph(_objectSpread(_objectSpread({
      container: container
    }, graphConfig), {}, {
      interacting: function interacting() {
        return {
          nodeMovable: readonly ? false : true
        };
      }
    }));
    initFlow(graph_);
    setGraph(graph_);
    graph_.on('node:mouseenter', function () {
      showPorts(graph_.container.getAttribute('id'), true);
    });
    graph_.on('node:mouseleave', function () {
      showPorts(graph_.container.getAttribute('id'), false);
    });
    graph_.on('edge:mouseenter', function (_ref) {
      var edge = _ref.edge;
      if (readonly) return;
      edge.addTools({
        name: 'button-remove'
      });
    });
    graph_.on('edge:mouseleave', function (_ref2) {
      var edge = _ref2.edge;
      edge.removeTool('button-remove');
    });
    graph_.on('node:click', function (_ref3) {
      var node = _ref3.node;
      if (props.onClickNode) props.onClickNode(node);
    });
    graph_.on('node:added', function (_ref4) {
      var node = _ref4.node;
      graph_.unselect(graph_.getSelectedCells());
      graph_.select(node);
      request(apis.getCode, {
        method: 'get',
        params: {
          num: 1
        }
      }).then(function (res) {
        if (!res) return;
        node.updateData({
          code: res.data[0]
        });
      }).catch(function (err) {
        console.error('获取节点code失败', err);
      });
      if (props.onClickNode) props.onClickNode(node);
    });
    graph_.on('blank:click', function () {
      if (props.onClickNode) props.onClickNode();
    });
    graph_.on('edge:connected', function () {
      onChange(graph_);
    });
    graph_.on('node:changed', function () {
      onChange(graph_);
    });
    graph_.on('node:change:data', function (_ref5) {
      var node = _ref5.node;
      var data = node.getData();
      // 如果节点发生异常，则将该节点后的所有节点置为异常状态
      if (data.status === 'failed') {
        FlowIterator(node, 'down', function (item) {
          item.updateData({
            status: 'failed'
          });
        });
      }
      // TODO 如果节点数据发生变化，需要对后续节点进行校验及数据矫正
    });

    graph_.on('edge:removed', function (_ref6) {
      var edge = _ref6.edge;
      // 后续节点全部置为异常状态
      var targetNode = graph_.getCellById(edge.target.cell);
      // 如果是链接节点，则删除所有连接条件及字段勾选
      if ((targetNode === null || targetNode === void 0 ? void 0 : targetNode.shape) === CdpFlowTypes.Shape.join) {
        targetNode.updateData({
          joinOn: [],
          resultTable: {
            table1: [],
            table2: []
          }
        });
      }
      if (edge.target && targetNode) {
        FlowIterator(targetNode, 'down', function (node) {
          node.updateData({
            status: 'failed'
          });
        });
      }
      graph_.cleanSelection();
      if (props.onClickNode) props.onClickNode();
    });
    if (props.onReady) props.onReady(graph_);
  }
  function onChange(graph_) {
    if (props.onChange) props.onChange(getData(graph_));
  }
  function onSetting() {
    if (props.onClickNode) props.onClickNode();
  }
  /**
   * 初始化画布数据
   */
  function initFlow(graph_) {
    if (!defaultValue) return;
    graph_.fromJSON({
      cells: defaultValue.nodeList
    }, {
      silent: false
    });
    defaultValue.lineList.forEach(function (cell) {
      graph_.addEdge(new FlowEdge({
        source: cell.source,
        target: cell.target
      }));
    });
  }
  function showPorts(containerId, show) {
    var _document$getElementB;
    if (readonly) return;
    (_document$getElementB = document.getElementById(containerId)) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.querySelectorAll('.x6-port-body').forEach(function (port) {
      port.setAttribute('visibility', show ? 'visible' : 'hidden');
    });
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "flow-container ".concat(className)
  }, graph && /*#__PURE__*/React.createElement(FlowToolbar, {
    graph: graph,
    readonly: readonly,
    onRemoveNode: function onRemoveNode(node) {
      onChange(graph);
      if (props.onRemoveNode) props.onRemoveNode;
    },
    onBack: props.onBack,
    onSetting: onSetting
  }), /*#__PURE__*/React.createElement("div", {
    id: id
  }));
};
export default /*#__PURE__*/React.forwardRef(VisualFlow);