function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
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);