"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAnchorPoints = exports.closeLoading = exports.createLoading = exports.setEllipsis = exports.setParentChildren = exports.getChildrenData = exports.setLevelData = exports.getLevelData = exports.setTag = exports.setStyles = exports.cloneBesidesImg = exports.createMarker = exports.getStatusCfg = exports.getStatusBBox = exports.getSize = exports.getCommonConfig = exports.getStyle = exports.bindStateEvents = exports.getArrowCfg = exports.getCssPadding = exports.bindSourceMapCollapseEvents = exports.getMarkerPosition = exports.getGraphId = exports.processMinimap = exports.renderGraph = exports.bindDefaultEvents = exports.bindRadialExplore = exports.getCenterNode = exports.getGraphSize = exports.deepClone = exports.getType = exports.Log = exports.isType = void 0;
var g6_1 = __importDefault(require("@antv/g6"));
var util_1 = require("@antv/util");
var countBy_1 = require("./countBy");
var constants_1 = require("../constants");
var layout_1 = require("../layout");
var create_node_1 = require("./create-node");
// 类型检测
var isType = function (value, type) {
    var toString = {}.toString;
    return toString.call(value) === "[object ".concat(type, "]");
};
exports.isType = isType;
exports.Log = window.console;
var getType = function (n) {
    return Object.prototype.toString.call(n).slice(8, -1);
};
exports.getType = getType;
/**
 * 深克隆
 * @param source 要深克隆的目标对象
 */
var deepClone = function (source) {
    if (!source || typeof source !== 'object') {
        return source;
    }
    var target;
    if (Array.isArray(source)) {
        target = source.map(function (item) { return (0, exports.deepClone)(item); });
    }
    else if (source instanceof HTMLElement) {
        target = source;
    }
    else {
        target = {};
        Object.keys(source).forEach(function (key) {
            return (target[key] = (0, exports.deepClone)(source[key]));
        });
    }
    return target;
};
exports.deepClone = deepClone;
var getGraphSize = function (width, height, container) {
    var CANVAS_WIDTH;
    var CANVAS_HEIGHT;
    if (container && container.current) {
        CANVAS_WIDTH = container.current.offsetWidth;
        CANVAS_HEIGHT = container.current.offsetHeight || 500;
    }
    if ((!width && !CANVAS_WIDTH) || (!height && !CANVAS_HEIGHT)) {
        exports.Log.warn('请为 Graph 指定 width 与 height！否则将使用默认值 500 * 500');
        return [500, 500];
    }
    return [width || CANVAS_WIDTH || 500, height || CANVAS_HEIGHT || 500];
};
exports.getGraphSize = getGraphSize;
var EventData = /** @class */ (function () {
    function EventData(data) {
        data && this.setData(data);
    }
    EventData.prototype.getData = function () {
        return this.data;
    };
    EventData.prototype.setData = function (data) {
        this.data = data;
    };
    return EventData;
}());
var getCenterNode = function (data) {
    var nodes = data.nodes, edges = data.edges;
    if (nodes.length === 1) {
        return nodes[0].id;
    }
    var linkCount = [];
    edges.forEach(function (item) {
        linkCount.push(item.source);
    });
    var timesObj = (0, countBy_1.countBy)(linkCount);
    var maxTimes = 0;
    var maxTimeKey = '';
    for (var k in timesObj) {
        if (timesObj.hasOwnProperty(k) && timesObj[k] > maxTimes) {
            maxTimes = timesObj[k];
            maxTimeKey = k;
        }
    }
    return maxTimeKey;
};
exports.getCenterNode = getCenterNode;
/** sector layout */
var bindRadialExplore = function (graph, asyncData, layoutCfg, fetchLoading) {
    var onDblClick = function (e) { return __awaiter(void 0, void 0, void 0, function () {
        var item, itemModel, newData, nodes, edges, x, y, centerNodeId, centerNode, _a, centerX, centerY, pureNodes, pureEdges, allNodeModels, allEdgeModels;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    item = e.item;
                    itemModel = item.getModel();
                    (0, exports.createLoading)(itemModel, fetchLoading);
                    return [4 /*yield*/, asyncData(item.getModel())];
                case 1:
                    newData = _b.sent();
                    (0, exports.closeLoading)();
                    nodes = graph.getNodes();
                    edges = graph.getEdges();
                    x = itemModel.x, y = itemModel.y;
                    centerNodeId = graph.get('centerNode');
                    centerNode = centerNodeId ? graph.findById(centerNodeId) : nodes[0];
                    _a = centerNode.getModel(), centerX = _a.x, centerY = _a.y;
                    pureNodes = newData.nodes.filter(function (item) { return (0, util_1.findIndex)(nodes, function (t) { return t.getModel().id === item.id; }) === -1; });
                    pureEdges = newData.edges.filter(function (item) {
                        return (0, util_1.findIndex)(edges, function (t) {
                            var _a = t.getModel(), source = _a.source, target = _a.target;
                            return source === item.source && target === item.target;
                        }) === -1;
                    });
                    allNodeModels = [];
                    allEdgeModels = [];
                    pureNodes.forEach(function (nodeModel) {
                        // set the initial positions of the new nodes to the focus(clicked) node
                        nodeModel.x = itemModel.x;
                        nodeModel.y = itemModel.y;
                        graph.addItem('node', nodeModel);
                    });
                    // add new edges to graph
                    pureEdges.forEach(function (em, i) {
                        graph.addItem('edge', em);
                    });
                    edges.forEach(function (e) {
                        allEdgeModels.push(e.getModel());
                    });
                    nodes.forEach(function (n) {
                        allNodeModels.push(n.getModel());
                    });
                    // 这里使用了引用类型
                    (0, layout_1.radialSectorLayout)({
                        center: [centerX, centerY],
                        eventNodePosition: [x, y],
                        nodes: nodes.map(function (n) { return n.getModel(); }),
                        layoutNodes: pureNodes,
                        options: layoutCfg,
                    });
                    graph.positionsAnimate();
                    graph.data({
                        nodes: allNodeModels,
                        edges: allEdgeModels,
                    });
                    return [2 /*return*/];
            }
        });
    }); };
    graph.on('node:dblclick', function (e) {
        onDblClick(e);
    });
};
exports.bindRadialExplore = bindRadialExplore;
// 展开&折叠事件
var bindDefaultEvents = function (graph, level, getChildren, fetchLoading) {
    var onClick = function (e) { return __awaiter(void 0, void 0, void 0, function () {
        var item, model, _a, collapsed, g_currentPath_1, _b, children, g_parentId_1, g_level_1, id_1, appendChildren, appendChildrenData;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    item = e.item;
                    model = item.getModel();
                    if (!(e.target.get('name') === 'collapse-icon')) return [3 /*break*/, 3];
                    _a = item.getModel(), collapsed = _a.collapsed, g_currentPath_1 = _a.g_currentPath, _b = _a.children, children = _b === void 0 ? [] : _b, g_parentId_1 = _a.g_parentId, g_level_1 = _a.g_level, id_1 = _a.id;
                    appendChildren = level &&
                        !children.length &&
                        (0, exports.getChildrenData)(graph.get('eventData').getData(), g_currentPath_1);
                    if (!(getChildren && !(children === null || children === void 0 ? void 0 : children.length) && !(appendChildren === null || appendChildren === void 0 ? void 0 : appendChildren.length))) return [3 /*break*/, 2];
                    (0, exports.createLoading)(model, fetchLoading);
                    return [4 /*yield*/, getChildren(item.getModel())];
                case 1:
                    appendChildrenData = _c.sent();
                    if (appendChildrenData) {
                        appendChildrenData = appendChildrenData.map(function (t, index) {
                            var _a;
                            return __assign((_a = {}, _a["".concat(constants_1.prefix, "_level")] = g_level_1 + 1, _a["".concat(constants_1.prefix, "_parentId")] = "".concat(g_parentId_1, "-").concat(id_1), _a["".concat(constants_1.prefix, "_currentPath")] = "".concat(g_currentPath_1, "-").concat(index), _a), t);
                        });
                        (0, exports.setLevelData)(graph, appendChildrenData, g_currentPath_1);
                    }
                    appendChildren = appendChildrenData;
                    (0, exports.closeLoading)();
                    _c.label = 2;
                case 2:
                    if ((appendChildren === null || appendChildren === void 0 ? void 0 : appendChildren.length) > 0) {
                        model.children = appendChildren;
                        graph.updateChild(model, model.id);
                        graph.updateItem(item, {
                            collapsed: false,
                        });
                        graph.refreshItem(item);
                    }
                    else {
                        graph.updateItem(item, {
                            collapsed: !collapsed,
                        });
                        graph.layout();
                    }
                    _c.label = 3;
                case 3: return [2 /*return*/];
            }
        });
    }); };
    graph.on('node:click', function (e) {
        onClick(e);
    });
    graph.on('node:touchstart', function (e) {
        onClick(e);
    });
};
exports.bindDefaultEvents = bindDefaultEvents;
var renderGraph = function (graph, data, level) {
    var originData = (0, exports.deepClone)(data);
    var tagData = originData;
    if (level) {
        tagData = (0, exports.setTag)(data);
        originData = (0, exports.getLevelData)(tagData, level);
    }
    graph.data(originData);
    graph.set('eventData', new EventData(tagData));
    graph.render();
    // 关闭局部刷新，各种 bug
    graph.get('canvas').set('localRefresh', false);
};
exports.renderGraph = renderGraph;
var grapgMinmapMaps = {};
var processMinimap = function (cfg, graph) {
    if (cfg === void 0) { cfg = {}; }
    var graphId = graph === null || graph === void 0 ? void 0 : graph.get('id');
    if (!graph || graph.destroyed) {
        grapgMinmapMaps[graphId] = null;
        return;
    }
    if ((!cfg || !cfg.show) && grapgMinmapMaps[graphId]) {
        var pluginMinimap = graph.get('plugins')[0];
        if (pluginMinimap) {
            graph.removePlugin(pluginMinimap);
        }
        grapgMinmapMaps[graphId] = null;
    }
    if (cfg.show && !grapgMinmapMaps[graphId]) {
        var curMminimapCfg = Object.assign(constants_1.defaultMinimapCfg, cfg);
        var minimap = new g6_1.default.Minimap(__assign(__assign({}, curMminimapCfg), { id: graphId }));
        graph.addPlugin(minimap);
        grapgMinmapMaps[graphId] = minimap;
        return minimap;
    }
    return null;
};
exports.processMinimap = processMinimap;
var getUuid = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0;
        var v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};
// 同一页面存在多 graph 时需要指定 graphId
var getGraphId = function (graph) {
    if (graph.current) {
        return graph.current;
    }
    graph.current = "graph-".concat(getUuid());
    return graph.current;
};
exports.getGraphId = getGraphId;
var getMarkerPosition = function (direction, size) {
    if (direction === void 0) { direction = 'right'; }
    var width = size[0], height = size[1];
    var x = 0;
    var y = 0;
    switch (direction) {
        case 'top':
            x = width / 2;
            y = 0;
            break;
        case 'right':
            x = width;
            y = height / 2;
            break;
        case 'bottom':
            x = width / 2;
            y = height;
            break;
        case 'left':
            x = 0;
            y = height / 2;
            break;
    }
    return { x: x, y: y };
};
exports.getMarkerPosition = getMarkerPosition;
var bindSourceMapCollapseEvents = function (graph, asyncData, fetchLoading) {
    var onClick = function (e) { return __awaiter(void 0, void 0, void 0, function () {
        var controlData, item, collapsed, _a, fullEdges_1, nodeId_1, targetNodeIds_1, updateItems_1, updateIds_1, getLinkedId_1, showNode, _b, nodes, edges, eventData;
        var _c;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    controlData = graph.get('eventData').getData();
                    if (!(e.target.get('name') === 'collapse-icon')) return [3 /*break*/, 5];
                    item = e.item;
                    collapsed = item.getModel().collapsed;
                    if (!(0, exports.isType)(collapsed, 'Boolean')) {
                        // @ts-ignore
                        collapsed = (_c = item._cfg.group
                            .getChildren()
                            .find(function (item) { return item.get('name') === 'main-box'; })) === null || _c === void 0 ? void 0 : _c.attr('defaultCollapsed');
                    }
                    _a = (controlData !== null && controlData !== void 0 ? controlData : {}).edges, fullEdges_1 = _a === void 0 ? [] : _a;
                    nodeId_1 = item.getModel().id;
                    targetNodeIds_1 = [];
                    updateItems_1 = [];
                    updateIds_1 = [];
                    getLinkedId_1 = function (currentId) {
                        fullEdges_1.forEach(function (edge) {
                            var source = edge.source, target = edge.target;
                            if (source === currentId) {
                                targetNodeIds_1.push(target);
                                getLinkedId_1(target);
                            }
                        });
                    };
                    getLinkedId_1(nodeId_1);
                    if (!!collapsed) return [3 /*break*/, 1];
                    // collapse
                    graph.findAll('node', function (node) { return targetNodeIds_1.includes(node.get('id')); }).forEach(function (node) { return graph.hideItem(node); });
                    controlData.nodes.forEach(function (node) {
                        var _a = node.collapsedLevel, collapsedLevel = _a === void 0 ? 0 : _a, id = node.id;
                        if (targetNodeIds_1.includes(id)) {
                            node.collapsedLevel = collapsedLevel + 1;
                        }
                    });
                    return [3 /*break*/, 4];
                case 1:
                    showNode = graph.findAll('node', function (node) {
                        var collapsedLevel = controlData.nodes.find(function (item) { return item.id === node.get('id'); }).collapsedLevel;
                        return targetNodeIds_1.includes(node.get('id')) && (!collapsedLevel || collapsedLevel < 2);
                    });
                    if (!showNode.length) return [3 /*break*/, 2];
                    showNode.forEach(function (node) { return graph.showItem(node); });
                    controlData.nodes.forEach(function (node) {
                        var _a = node.collapsedLevel, collapsedLevel = _a === void 0 ? 0 : _a, id = node.id;
                        if (targetNodeIds_1.includes(id)) {
                            node.collapsedLevel = collapsedLevel - 1;
                        }
                    });
                    return [3 /*break*/, 4];
                case 2:
                    if (!asyncData) return [3 /*break*/, 4];
                    (0, exports.createLoading)(item.getModel(), fetchLoading);
                    return [4 /*yield*/, asyncData(item.getModel())];
                case 3:
                    _b = _d.sent(), nodes = _b.nodes, edges = _b.edges;
                    eventData = {
                        nodes: controlData.nodes.concat(nodes),
                        edges: controlData.edges.concat((edges === null || edges === void 0 ? void 0 : edges.length) ? edges : nodes.map(function (item) { return ({ source: nodeId_1, target: item.id }); })),
                    };
                    (0, exports.closeLoading)();
                    graph.set('eventData', new EventData(eventData));
                    graph.changeData(eventData);
                    if (graph.get('fitCenter')) {
                        graph.fitCenter();
                    }
                    return [2 /*return*/];
                case 4:
                    fullEdges_1.forEach(function (edge) {
                        var source = edge.source, target = edge.target;
                        if (targetNodeIds_1.includes(target)) {
                            updateIds_1.push(source);
                        }
                    });
                    updateIds_1 = Array.from(new Set(updateIds_1));
                    updateIds_1.forEach(function (id) {
                        updateItems_1.push(graph.find('node', function (node) { return node.get('id') === id; }));
                    });
                    updateItems_1.forEach(function (nodeItem) {
                        graph.updateItem(nodeItem, {
                            collapsed: !nodeItem.getModel().collapsed,
                        });
                        graph.refreshItem(nodeItem);
                    });
                    _d.label = 5;
                case 5: return [2 /*return*/];
            }
        });
    }); };
    graph.on('node:click', function (e) {
        onClick(e);
    });
    graph.on('node:touchstart', function (e) {
        onClick(e);
    });
};
exports.bindSourceMapCollapseEvents = bindSourceMapCollapseEvents;
/**
 * padding | margin 按 CSS 规则转换
 */
var getCssPadding = function (padding) {
    if (typeof padding === 'number') {
        return [padding, padding, padding, padding];
    }
    var result = [];
    switch (padding.length) {
        case 1:
            result = [padding[0], padding[0], padding[0], padding[0]];
            break;
        case 2:
            result = [padding[0], padding[1], padding[0], padding[1]];
            break;
        case 3:
            result = [padding[0], padding[1], padding[2], padding[1]];
            break;
        case 4:
            result = padding;
            break;
        default:
            break;
    }
    return result;
};
exports.getCssPadding = getCssPadding;
// 默认箭头样式
var getArrowCfg = function (arrowCfg, edge) {
    if (!arrowCfg) {
        return;
    }
    if (typeof arrowCfg === 'object' && (arrowCfg === null || arrowCfg === void 0 ? void 0 : arrowCfg.show) === false) {
        return;
    }
    var cfg = typeof arrowCfg === 'function' ? arrowCfg(edge) : arrowCfg;
    var _a = cfg.type, type = _a === void 0 ? 'vee' : _a, _b = cfg.d, d = _b === void 0 ? 0 : _b, _c = cfg.size, size = _c === void 0 ? 10 : _c;
    return __assign({ path: g6_1.default.Arrow[type](size, size, d), fill: '#ccc', d: d }, cfg);
};
exports.getArrowCfg = getArrowCfg;
// 交互
var bindStateEvents = function (graph, cfg) {
    var _a = cfg !== null && cfg !== void 0 ? cfg : {}, _b = _a.nodeCfg, nodeCfg = _b === void 0 ? {} : _b, _c = _a.edgeCfg, edgeCfg = _c === void 0 ? {} : _c;
    var nodeStateStyles = nodeCfg.nodeStateStyles;
    var edgeStateStyles = edgeCfg.edgeStateStyles;
    /**
     * 存储交互状态
     * id: [[endActive, endDefalut], [startActive, startDefalut]]
     */
    var statusCache = {};
    var updateArrowFill = function (item, endArrowFill, stratArrowFill) {
        graph.updateItem(item, {
            style: {
                endArrow: !!endArrowFill && {
                    fill: endArrowFill,
                },
                startArrow: !!stratArrowFill && {
                    fill: stratArrowFill,
                },
            },
        });
    };
    var setState = function (item, name, status) {
        var _a, _b, _c;
        status ? item.toFront() : item.toBack();
        var _d = (_a = item.getModel().style) !== null && _a !== void 0 ? _a : {}, endArrow = _d.endArrow, startArrow = _d.startArrow;
        if (endArrow || startArrow) {
            if (!statusCache[item.getID()]) {
                // @ts-ignore
                var endArrowFill = (endArrow !== null && endArrow !== void 0 ? endArrow : {}).fill;
                // @ts-ignore
                var startArrowFill = (startArrow !== null && startArrow !== void 0 ? startArrow : {}).fill;
                var hoverStatus = (_c = (_b = item.getModel().style) === null || _b === void 0 ? void 0 : _b[name]) === null || _c === void 0 ? void 0 : _c.stroke;
                statusCache[item.getID()] = [
                    [hoverStatus !== null && hoverStatus !== void 0 ? hoverStatus : endArrowFill, endArrowFill],
                    [hoverStatus !== null && hoverStatus !== void 0 ? hoverStatus : startArrowFill, startArrowFill],
                ];
            }
            var fill = statusCache[item.getID()];
            updateArrowFill(item, endArrow && fill[0][status ? 0 : 1], startArrow && fill[1][status ? 0 : 1]);
        }
        graph.setItemState(item, name, status);
    };
    var getRelationItems = function (currentItem, name, status, type) {
        var relationItems = type === 'node'
            ? graph.findAll('edge', function (edge) { return edge.getSource() === currentItem || edge.getTarget() === currentItem; })
            : graph.findAll('node', function (node) {
                return currentItem.getSource().get('id') === node.get('id') ||
                    currentItem.getTarget().get('id') === node.get('id');
            });
        var highlightItems = [currentItem].concat(relationItems);
        highlightItems.forEach(function (item) {
            setState(item, name, status);
        });
    };
    if (nodeStateStyles) {
        graph.on('node:mouseenter', function (evt) {
            var item = evt.item;
            getRelationItems(item, 'hover', true, 'node');
        });
        graph.on('node:mouseleave', function (evt) {
            var item = evt.item;
            getRelationItems(item, 'hover', false, 'node');
        });
    }
    if (edgeStateStyles) {
        graph.on('edge:mouseenter', function (evt) {
            var item = evt.item;
            getRelationItems(item, 'hover', true, 'edge');
        });
        graph.on('edge:mouseleave', function (evt) {
            var item = evt.item;
            getRelationItems(item, 'hover', false, 'edge');
        });
    }
};
exports.bindStateEvents = bindStateEvents;
// 统一处理 config，支持回调
var getStyle = function (source, cfg, item, current) {
    if (typeof source === 'function') {
        return source(cfg, item, current) || {};
    }
    return source || {};
};
exports.getStyle = getStyle;
// 统一处理 config，支持回调
var getCommonConfig = function (cfg, item, graph) {
    if (typeof cfg === 'function') {
        return cfg(item, graph);
    }
    return cfg;
};
exports.getCommonConfig = getCommonConfig;
var getSize = function (size) {
    if (Array.isArray(size)) {
        return size;
    }
    return size ? [size, size] : constants_1.defaultNodeSize;
};
exports.getSize = getSize;
// status bar 的默认宽度
var DefaultStatusBarWidth = 4;
/**
 * card status 对布局的影响，直接加到 padding 中
 */
var getStatusBBox = function (cfg) {
    if (!cfg) {
        return [0, 0, 0, 0];
    }
    var _a = cfg.size, size = _a === void 0 ? [] : _a, _b = cfg.position, position = _b === void 0 ? 'left' : _b;
    var _c = (0, exports.getSize)(size), width = _c[0], height = _c[1];
    var appendPadding = [];
    switch (position) {
        case 'top':
            appendPadding.push(height !== null && height !== void 0 ? height : DefaultStatusBarWidth, 0, 0, 0);
            break;
        case 'right':
            appendPadding.push(0, width !== null && width !== void 0 ? width : DefaultStatusBarWidth, 0, 0);
            break;
        case 'bottom':
            appendPadding.push(0, 0, height !== null && height !== void 0 ? height : DefaultStatusBarWidth, 0);
            break;
        case 'left':
            appendPadding.push(0, 0, 0, width !== null && width !== void 0 ? width : DefaultStatusBarWidth);
            break;
    }
    return appendPadding;
};
exports.getStatusBBox = getStatusBBox;
var getStatusCfg = function (cfg, cardSize) {
    var _a = cfg !== null && cfg !== void 0 ? cfg : {}, _b = _a.size, size = _b === void 0 ? [] : _b, _c = _a.position, position = _c === void 0 ? 'left' : _c;
    var _d = (0, exports.getSize)(size), width = _d[0], height = _d[1];
    var cardWidth = cardSize[0], cardHeight = cardSize[1];
    var x = 0;
    var y = 0;
    var w = 0;
    var h = 0;
    switch (position) {
        case 'top':
            x = 0;
            y = 0;
            w = width !== null && width !== void 0 ? width : cardWidth;
            h = height !== null && height !== void 0 ? height : DefaultStatusBarWidth;
            break;
        case 'left':
            x = 0;
            y = 0;
            w = width !== null && width !== void 0 ? width : DefaultStatusBarWidth;
            h = height !== null && height !== void 0 ? height : cardHeight;
            break;
        case 'right':
            x = cardWidth - ((0, util_1.isNumber)(width) ? width : DefaultStatusBarWidth);
            y = 0;
            w = width !== null && width !== void 0 ? width : DefaultStatusBarWidth;
            h = height !== null && height !== void 0 ? height : cardHeight;
            break;
        case 'bottom':
            x = 0;
            y = cardHeight - ((0, util_1.isNumber)(height) ? height : DefaultStatusBarWidth);
            w = width !== null && width !== void 0 ? width : cardWidth;
            h = height !== null && height !== void 0 ? height : DefaultStatusBarWidth;
            break;
    }
    return {
        x: x,
        y: y,
        width: w,
        height: h,
    };
};
exports.getStatusCfg = getStatusCfg;
var createMarker = function (cfg, group, size) {
    var show = cfg.show, position = cfg.position, collapsed = cfg.collapsed, style = cfg.style;
    if (show) {
        group.addShape('marker', {
            attrs: __assign(__assign(__assign({}, (0, exports.getMarkerPosition)(position, size)), { r: 6, cursor: 'pointer', symbol: collapsed ? g6_1.default.Marker.expand : g6_1.default.Marker.collapse, stroke: constants_1.defaultCardStyle.stroke, lineWidth: 1, fill: '#fff' }), style),
            defaultCollapsed: false,
            name: 'collapse-icon',
        });
    }
};
exports.createMarker = createMarker;
var cloneBesidesImg = function (obj) {
    var clonedObj = {};
    Object.keys(obj).forEach(function (key1) {
        var obj2 = obj[key1];
        if ((0, util_1.isObject)(obj2)) {
            var clonedObj2_1 = {};
            Object.keys(obj2).forEach(function (key2) {
                var v = obj2[key2];
                if (key2 === 'img' && !(0, util_1.isString)(v))
                    return;
                clonedObj2_1[key2] = (0, util_1.clone)(v);
            });
            clonedObj[key1] = clonedObj2_1;
        }
        else {
            clonedObj[key1] = (0, util_1.clone)(obj2);
        }
    });
    return clonedObj;
};
exports.cloneBesidesImg = cloneBesidesImg;
var setStyles = function (container, style) {
    if (style === void 0) { style = {}; }
    var keys = Object.keys(style);
    keys.forEach(function (key) {
        container.style[key] = style[key];
    });
};
exports.setStyles = setStyles;
/**
 * 对数据进行打标，加上 level 和  parentId
 */
var setTag = function (data, level, parentId, path) {
    var _a;
    if (level === void 0) { level = 0; }
    if (parentId === void 0) { parentId = ''; }
    if (path === void 0) { path = ''; }
    var id = data.id, _b = data.children, children = _b === void 0 ? [] : _b;
    return __assign(__assign((_a = {}, _a["".concat(constants_1.prefix, "_level")] = level, _a["".concat(constants_1.prefix, "_parentId")] = parentId, _a["".concat(constants_1.prefix, "_currentPath")] = path, _a), data), { children: children === null || children === void 0 ? void 0 : children.map(function (item, index) {
            return (0, exports.setTag)(item, level + 1, parentId ? "".concat(parentId, "-").concat(id) : id, "".concat(path, "-").concat(index));
        }) });
};
exports.setTag = setTag;
/**
 * 根据 level 获取相关数据
 */
var getLevelData = function (data, level) {
    var _a = data.children, children = _a === void 0 ? [] : _a, _b = data.g_level, g_level = _b === void 0 ? 0 : _b;
    if (level <= 0) {
        return data;
    }
    return __assign(__assign({}, data), { children: g_level + 1 < level
            ? children === null || children === void 0 ? void 0 : children.map(function (item) {
                return (0, exports.getLevelData)(item, level);
            })
            : [] });
};
exports.getLevelData = getLevelData;
/**
 * 挂载异步数据到全局 data
 */
var setLevelData = function (graph, data, currentPath) {
    var currentData = graph.get('eventData').getData();
    // 打标时已经做了编码，这直接取值即可
    var path = currentPath.split('-');
    path.shift(); // 根节点没有 path
    var current = currentData;
    path.forEach(function (childrenIndex) {
        current = current.children[Number(childrenIndex)];
    });
    current.children = data;
};
exports.setLevelData = setLevelData;
/**
 * get children
 * 获取相关路径下的一级节点
 */
var getChildrenData = function (data, currentPath) {
    // 打标时已经做了编码，这直接取值即可
    var path = currentPath.split('-');
    path.shift(); // 根节点没有 path
    var current = data;
    path.forEach(function (childrenIndex) {
        current = current.children[Number(childrenIndex)];
    });
    if (!(current === null || current === void 0 ? void 0 : current.children)) {
        return [];
    }
    return current.children.map(function (item) { return (__assign(__assign({}, item), { children: [] })); });
};
exports.getChildrenData = getChildrenData;
/**
 * 将查询到的节点挂载到当前图数据上
 */
var setParentChildren = function (parendData, currentPath, children) {
    var path = currentPath.split('-');
    path.shift();
    var current = parendData;
    path.forEach(function (childrenIndex) {
        current = current.children[Number(childrenIndex)];
    });
    current.children = children;
    return parendData;
};
exports.setParentChildren = setParentChildren;
/** 超出省略 */
var setEllipsis = function (text, fontSize, contentWidth) {
    if (fontSize === void 0) { fontSize = 12; }
    if (contentWidth === void 0) { contentWidth = 120; }
    var size = (0, util_1.isNumber)(fontSize) ? fontSize : Number(fontSize.replace('px', ''));
    var maxWords = Math.floor(contentWidth / size);
    if (text.length <= maxWords) {
        return text;
    }
    return text.slice(0, maxWords - 1) + '...';
};
exports.setEllipsis = setEllipsis;
/** 开启加载动画， 不支持同时存在多个 */
var createLoading = function (node, fetchLoading) {
    var loadingClassName = "".concat(constants_1.prefix, "-antd-loading");
    if (fetchLoading) {
        var loadingTemplate = (0, util_1.isFunction)(fetchLoading) ? fetchLoading(node) : fetchLoading;
        document.body.appendChild((0, create_node_1.createNode)(loadingTemplate, loadingClassName));
    }
    else {
        var container = document.createElement('div');
        container.className = loadingClassName;
        var styles = {
            position: 'fixed',
            left: '0',
            top: '0',
            width: '100vw',
            height: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'rgba(0,0,0, 0.25)',
            color: '#fff',
            fontSize: '16px',
            zIndex: 999,
        };
        (0, exports.setStyles)(container, styles);
        var span = document.createElement('span');
        span.innerText = 'loading...';
        container.appendChild(span);
        document.body.appendChild(container);
    }
};
exports.createLoading = createLoading;
/** 关闭加载动画 */
var closeLoading = function () {
    var hideContainer = document.getElementsByClassName("".concat(constants_1.prefix, "-antd-loading"));
    Array.from(hideContainer).forEach(function (el) {
        document.body.removeChild(el);
    });
};
exports.closeLoading = closeLoading;
/** 支持自定义 anchor */
var getAnchorPoints = function (anchorPoints, node) {
    if (typeof anchorPoints === 'function' && node) {
        return anchorPoints(node) || {};
    }
    if (Array.isArray(anchorPoints)) {
        return anchorPoints;
    }
    return constants_1.defaultFlowGraphAnchorPoints;
};
exports.getAnchorPoints = getAnchorPoints;
