"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _drawer = _interopRequireDefault(require("@alifd/next/lib/drawer"));
var _input = _interopRequireDefault(require("@alifd/next/lib/input"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = _interopRequireWildcard(require("react"));
var _g = _interopRequireDefault(require("@antv/g6"));
var _locale = require("../../../../src/locale");
var _defaultLayout = require("./default-layout");
var _lodash = require("lodash");
var _contextMenu = _interopRequireDefault(require("./components/context-menu"));
var _node = require("./node");
var _lines = require("./lines");
var _type = require("./type");
var _service = require("./service");
var _setterPanel = _interopRequireDefault(require("./setter-panel"));
var _boxSlotComponent = _interopRequireDefault(require("../../_components/boxSlotComponent"));
var _context = require("../context");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
var SetterPanelMap = _setterPanel["default"];

// 注入支持的节点
(0, _node.registerNodes)();
// 注入支持的线
(0, _lines.registerLines)();
var FlowPage = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _curModel$current2, _curModel$current3;
  var FlowCtx = (0, _react.useContext)(_context.FlowContext);
  var flowData = props.flowData;
  var refContainer = (0, _react.useRef)();
  var graphRef = (0, _react.useRef)();
  var curModel = (0, _react.useRef)();

  // const flowEventService = new FlowEventService();

  // TODO:使用 useRef 来保持对同一个 FlowEventService 实例的引用
  var flowEventServiceRef = (0, _react.useRef)();
  if (!flowEventServiceRef.current) {
    flowEventServiceRef.current = new _service.FlowEventService();
  }
  var flowEventService = flowEventServiceRef.current;
  var _useState = (0, _react.useState)(),
    position = _useState[0],
    setPosition = _useState[1];
  var _useState2 = (0, _react.useState)(false),
    menuOpen = _useState2[0],
    setMenuOpen = _useState2[1];
  var _useState3 = (0, _react.useState)([]),
    menuList = _useState3[0],
    setMenuList = _useState3[1];
  var _useState4 = (0, _react.useState)(false),
    settingOpen = _useState4[0],
    setSettingOpen = _useState4[1];
  var _useState5 = (0, _react.useState)(""),
    label = _useState5[0],
    setLabel = _useState5[1];
  (0, _react.useEffect)(function () {
    if (!settingOpen) {
      curModel.current = null;
      setMenuOpen(false);
    }
  }, [settingOpen]);
  (0, _react.useEffect)(function () {
    var _refContainer$current;
    var _ref = (refContainer === null || refContainer === void 0 ? void 0 : (_refContainer$current = refContainer.current) === null || _refContainer$current === void 0 ? void 0 : _refContainer$current.getBoundingClientRect()) || {},
      width = _ref.width,
      height = _ref.height;
    var graph = new _g["default"].TreeGraph({
      container: refContainer.current,
      width: width,
      height: height,
      layout: _defaultLayout.defaultLayout,
      minZoom: 1,
      maxZoom: 1,
      linkCenter: true,
      defaultNode: {
        type: "start"
      },
      animate: false,
      modes: {
        "default": ["drag-canvas"] // 允许按住移动画布和节点
      }
    });

    // graph.on("afteradditem", () => {
    //   // updateItemData(graph, width)
    // });
    // graph.on("afterremoveitem", () => {
    //   // updateItemData(graph, width)
    // });

    graph.edge(function (config) {
      // 获取线的源节点和目标节点
      // const sourceNode: any = graph.findById(config.source);
      // const targetNode: any = graph.findById(config.target);

      // 获取源节点和目标节点的配置
      // const sourceModel = sourceNode?.getModel();
      // const targetModel = targetNode?.getModel();

      // let label = "";

      // // 如果是条件节点，则取条件名称
      // if (sourceModel?.type === "condition") {
      //   const { name } =
      //     sourceModel?.config?.find(
      //       (o: any) => o.id === targetModel?.conditionId
      //     ) || {};
      //   label = name;
      // }

      return {
        type: "flow-line",
        style: {
          stroke: "#91d5ff"
        }
      };
    });
    updateGraphData(graph, flowData, true);
    graphRef.current = graph;
    graph.on("node:click", function (evt) {
      var _curModel$current;
      var item = evt.item,
        target = evt.target;
      var targetType = target.get("type");
      var name = target.get("name");
      var model = item.getModel();
      if ([_type.FlowEvent.action, _type.FlowEvent.condition, _type.FlowEvent.rule, _type.FlowEvent.eventFlowNode].includes(model.type) && targetType !== "marker") {
        curModel.current = item.getModel();
        setLabel(curModel.current.label);
        setSettingOpen(true);
        setMenuOpen(false);
        return;
      }
      if (model.id === ((_curModel$current = curModel.current) === null || _curModel$current === void 0 ? void 0 : _curModel$current.id)) {
        return;
      }
      setMenuOpen(false);
      if (targetType === "marker" && (name === _type.FlowEvent.addItem || name === _type.FlowEvent.removeItem)) {
        curModel.current = item.getModel();
        var _flowEventService$get = flowEventService.getMenusPosition(item, target, graph, refContainer),
          left = _flowEventService$get.left,
          top = _flowEventService$get.top;
        var newMenus = name === _type.FlowEvent.addItem ? flowEventService.getMenusByNode(model, FlowCtx) : flowEventService.getDeleteMenus(model, graph);
        changeMenus(newMenus, top, left);
      }
    });
    graph.on("canvas:click", function () {
      setMenuOpen(false);
      curModel.current = null;
    });
    return function () {
      graph.destroy();
    };
  }, []);
  var changeMenus = function changeMenus(newMenus, tops, lefts) {
    setTimeout(function () {
      setPosition({
        top: tops,
        left: lefts
      });
      setMenuList(newMenus);
      setMenuOpen(true);
    }, 10);
  };
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      save: function save() {
        var _graphRef$current;
        return (_graphRef$current = graphRef.current) === null || _graphRef$current === void 0 ? void 0 : _graphRef$current.save();
      }
    };
  }, []);

  // const updateItemData = (graph: any, width: number) => {
  //   const newData = graph.save();
  //   const depth = getTreeDepth(newData);
  //   graph.changeSize(width, depth * 40 + 56 * (depth - 1) + 200);
  // }

  var updateGraphData = function updateGraphData(graph, data, isFirst) {
    if (isFirst === void 0) {
      isFirst = false;
    }
    var newFlowData = (0, _lodash.cloneDeep)(flowEventService.updatedParentConfigs(data));
    if (isFirst) {
      graph.data(newFlowData);
      graph.render();
      graph.fitCenter();
    } else {
      var viewPoint = graph.getViewPortCenterPoint();
      graph.changeData(newFlowData);
      graph.refresh();
      var newViewPoint = graph.getViewPortCenterPoint();
      //更新画布位置
      graph.translate(newViewPoint.x - viewPoint.x, newViewPoint.y - viewPoint.y);
    }
  };
  var onSelect = function onSelect(key) {
    if (!curModel.current) return;
    var curData = (0, _lodash.cloneDeep)(graphRef.current.save()); //当前数据 
    var newData; //更新数据
    if (key === _type.FlowEvent.deleteContent || key === _type.FlowEvent.deleteAfter) {
      if (key === _type.FlowEvent.deleteContent && curModel.current.children.length) {
        var _graphRef$current$fin;
        var parentId = curModel.current.parentConfig.parentId;
        var parentModel = (_graphRef$current$fin = graphRef.current.findById(parentId)) === null || _graphRef$current$fin === void 0 ? void 0 : _graphRef$current$fin.getModel();
        if (parentModel) {
          newData = flowEventService.getNewTreeGraphData(curData, key, curModel.current.id, null);
        }
      } else {
        newData = flowEventService.getNewTreeGraphData(curData, key, curModel.current.id, null);
      }
    } else {
      // 新增逻辑
      var newNode = flowEventService.createFlowNode(curModel, key);
      var isInsertNode = flowEventService.isInsertNode(key, curModel.current);
      newData = flowEventService.getNewTreeGraphData(curData, _type.FlowEvent.insert, curModel.current.id, newNode, isInsertNode);
    }
    //根据新数据进行更新数据源并重新渲染
    updateGraphData(graphRef.current, newData);
    setMenuOpen(false);
    curModel.current = null;
  };
  var onSetterPanelChange = function onSetterPanelChange(value) {
    graphRef.current.updateItem(curModel.current.id, value);
  };
  var DrawCloseFn = function DrawCloseFn() {
    setSettingOpen(false);
  };
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "flowPageMain"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      height: "calc(100vh - 65px)",
      width: "calc(100vw - 40px)",
      overflowY: "auto",
      overflowX: "hidden",
      backgroundColor: "#F2F7FA"
    },
    ref: refContainer
  }, menuList.length > 0 && /*#__PURE__*/_react["default"].createElement(_contextMenu["default"], {
    position: position,
    items: menuList,
    onSelect: onSelect,
    open: menuOpen
  }), /*#__PURE__*/_react["default"].createElement(_drawer["default"], {
    className: "flowEventDrawer",
    title: (0, _locale.t)("setter.setKey"),
    width: "500px",
    placement: "right",
    visible: settingOpen,
    onClose: DrawCloseFn
  }, curModel.current && /*#__PURE__*/_react["default"].createElement(_boxSlotComponent["default"], {
    title: (0, _locale.t)("setter.nodeDec")
  }, /*#__PURE__*/_react["default"].createElement(_input["default"], {
    hasClear: true,
    value: label,
    style: {
      width: 100 + "%",
      minWidth: 0
    },
    onChange: function onChange(e) {
      setLabel(e);
      onSetterPanelChange((0, _extends2["default"])({}, curModel.current, {
        label: e
      }));
    }
  })), SetterPanelMap && SetterPanelMap[(_curModel$current2 = curModel.current) === null || _curModel$current2 === void 0 ? void 0 : _curModel$current2.type] && /*#__PURE__*/_react["default"].createElement(SetterPanelMap[(_curModel$current3 = curModel.current) === null || _curModel$current3 === void 0 ? void 0 : _curModel$current3.type], {
    current: curModel.current,
    onChange: onSetterPanelChange
  }))));
});
var _default = exports["default"] = FlowPage;