"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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) {
    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) : new P(function (resolve) { resolve(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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var antd_1 = require("antd");
var React = require("react");
var _ = require("lodash");
var utils_1 = require("../../utils");
/**
 * 说明：要想编辑动态树，提供的接口必须满足 VAP 接口规范，不满足规范的接口暂不支持。
 *
 */
var default_1 = /** @class */ (function (_super) {
    __extends(default_1, _super);
    function default_1() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.keyField = 'id';
        _this.nameField = 'name';
        _this.iconField = undefined;
        _this.parentField = 'parentId';
        _this.tree = null;
        _this.childSuffix = '';
        _this.state = {
            loading: true,
            treeData: [],
            selectedKeys: [],
        };
        _this.renderTreeNodes = function (data, parent) {
            if (parent === void 0) { parent = null; }
            return data.map(function (item) {
                if (item.children && item.children.length) {
                    return React.createElement(antd_1.Tree.TreeNode, { title: item[_this.nameField], key: item[_this.keyField], dataRef: item, parent: parent }, _this.renderTreeNodes(item.children, item));
                }
                var param = {};
                if (_this.props.checkChild) {
                    param = { isLeaf: !item[_this.props.checkChild] };
                }
                return React.createElement(antd_1.Tree.TreeNode, __assign({}, param, { title: item[_this.nameField], key: item[_this.keyField], dataRef: item, parent: parent }));
            });
        };
        return _this;
    }
    default_1.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            var selectedKeys, treeData, resp;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (_.has(this.props, 'keyField')) {
                            this.keyField = this.props.keyField;
                        }
                        if (_.has(this.props, 'nameField')) {
                            this.nameField = this.props.nameField;
                        }
                        if (_.has(this.props, 'iconField')) {
                            this.iconField = this.props.iconField;
                        }
                        if (_.has(this.props, 'parentField')) {
                            this.parentField = this.props.parentField;
                        }
                        if (_.has(this.props, 'childSuffix')) {
                            this.childSuffix = this.props.childSuffix;
                        }
                        selectedKeys = [];
                        treeData = [];
                        utils_1.Ajax.SESION(this.props.root);
                        return [4 /*yield*/, utils_1.Ajax.GET(this.props.root)];
                    case 1:
                        resp = _a.sent();
                        if (_.isArray(resp.data)) {
                            treeData = resp.data;
                            if (treeData.length == 1) {
                                selectedKeys = treeData[0][this.keyField];
                            }
                        }
                        else {
                            treeData = [resp.data];
                            selectedKeys = [resp.data[this.keyField]];
                        }
                        if (this.props.defaultSelectedKeys) {
                            selectedKeys = this.props.defaultSelectedKeys;
                        }
                        if (this.props.checkChild) {
                            treeData.map(function (item) { return item[_this.props.checkChild] = true; });
                        }
                        this.setState({ treeData: treeData, selectedKeys: selectedKeys, loading: false }, function () {
                            if (treeData.length > 0) {
                                _this.props.onSelect(treeData[0], null);
                            }
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    default_1.prototype.clearCache = function (node, self) {
        if (self === void 0) { self = false; }
        if (_.isEmpty(node[this.parentField])) {
            utils_1.Ajax.CLEAR(this.props.root);
        }
        else {
            if (self) {
                utils_1.Ajax.CLEAR(this.props.child + node[this.keyField] + this.childSuffix);
            }
            utils_1.Ajax.CLEAR(this.props.child + node[this.parentField] + this.childSuffix);
        }
    };
    // 寻找节点在树里面的位置
    default_1.prototype.findIndex = function (data, isParent) {
        if (isParent === void 0) { isParent = false; }
        var idx = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            idx[_i - 2] = arguments[_i];
        }
        var list = idx.length ? _.at(this.state.treeData, idx.map(function (i) { return "[" + i + "].children"; }).join(''))[0] : this.state.treeData;
        if (list == undefined) {
            return false;
        }
        for (var i in list) {
            if (isParent && _.isEmpty(data[this.parentField])) {
                return [];
            }
            if (list[i][this.keyField] == data[isParent ? this.parentField : this.keyField]) {
                return __spread(idx, [i]);
            }
            if (_.isArray(list[i].children) && list[i].children.length) {
                var result = this.findIndex.apply(this, __spread([data, isParent], idx, [i]));
                if (_.isArray(result) && result.length) {
                    return result;
                }
            }
        }
        return false;
    };
    /**
     * 添加一个节点
     *  */
    default_1.prototype.add = function (data, callback) {
        if (callback === void 0) { callback = null; }
        return __awaiter(this, void 0, void 0, function () {
            var resp, node, root, treeData, nodePath, rootPath, parentNode;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (_.isEmpty(this.props.api)) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, utils_1.Ajax.PUT(this.props.api, data)];
                    case 1:
                        resp = _a.sent();
                        if (resp.code != '0') {
                            antd_1.message.error(resp.message);
                            return [2 /*return*/];
                        }
                        node = resp.data;
                        antd_1.message.success(node[this.nameField] + ' : 添加成功');
                        if (_.isEmpty(node)) {
                            return [2 /*return*/];
                        }
                        root = this.findIndex(node, true);
                        treeData = _.concat([], this.state.treeData);
                        if (root.length == 0) {
                            treeData.unshift(node);
                        }
                        else {
                            nodePath = root.map(function (i) { return "[" + i + "].children"; }).join('');
                            rootPath = nodePath.substr(0, nodePath.length - 9);
                            parentNode = _.get(treeData, rootPath);
                            if (this.props.checkChild) {
                                parentNode[this.props.checkChild] = true;
                            }
                            if (parentNode.children) {
                                parentNode.children.unshift(node);
                            }
                            else {
                                parentNode.children = [node];
                            }
                            _.set(treeData, rootPath, parentNode);
                            this.clearCache(parentNode, true);
                        }
                        this.setState({ treeData: treeData });
                        if (callback) {
                            callback(node);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 更新一个节点
     */
    default_1.prototype.update = function (data, callback) {
        if (callback === void 0) { callback = null; }
        return __awaiter(this, void 0, void 0, function () {
            var resp, root, treeData, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (_.isEmpty(this.props.api)) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, utils_1.Ajax.PATCH(this.props.api, data)];
                    case 1:
                        resp = _a.sent();
                        if (resp.code != '0') {
                            antd_1.message.error(resp.message);
                            return [2 /*return*/];
                        }
                        antd_1.message.success(data[this.nameField] + '修改成功');
                        this.clearCache(data);
                        root = this.findIndex(data, false);
                        if (root === false) {
                            return [2 /*return*/];
                        }
                        treeData = _.concat([], this.state.treeData);
                        value = _.get(treeData, root.map(function (i) { return "[" + i + "]"; }).join('.children'));
                        _.assign(value, data);
                        _.set(treeData, root.map(function (i) { return "[" + i + "]"; }).join('.children'), value);
                        this.setState({ treeData: treeData, __now: _.now() });
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 删除一个节点
     */
    default_1.prototype.delete = function (data, callback) {
        if (callback === void 0) { callback = null; }
        return __awaiter(this, void 0, void 0, function () {
            var resp, findIds, treeData, index, root, childPath, rootPath, rootNode;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (_.isEmpty(this.props.api)) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, utils_1.Ajax.DELETE(this.props.api, { ids: data[this.keyField] })];
                    case 1:
                        resp = _a.sent();
                        if (resp.code != '0') {
                            antd_1.message.error(resp.message);
                            return [2 /*return*/];
                        }
                        antd_1.message.success(data[this.nameField] + '删除成功');
                        this.clearCache(data);
                        findIds = this.findIndex(data, false);
                        if (findIds === false) {
                            return [2 /*return*/];
                        }
                        treeData = _.concat([], this.state.treeData);
                        if (findIds.length == 1) {
                            if (treeData.length == 1) {
                                antd_1.message.error('至少需要有一个根节点');
                                return [2 /*return*/];
                            }
                            _.pullAt(treeData, findIds);
                            this.setState({ treeData: treeData, selectedKeys: [treeData[0][this.keyField]] }, function () { return _this.props.onSelect(_this.state.treeData[0]); });
                        }
                        else {
                            index = findIds[findIds.length - 1];
                            root = _.dropRight(findIds);
                            childPath = root.map(function (i) { return "[" + i + "].children"; }).join('');
                            rootPath = childPath.substr(0, childPath.length - 9);
                            rootNode = _.get(treeData, rootPath);
                            _.pullAt(rootNode.children, [parseInt(index)]);
                            if (rootNode.children.length == 0 && this.props.checkChild) {
                                rootNode[this.props.checkChild] = false;
                            }
                            _.set(treeData, rootPath, rootNode);
                            this.clearCache(rootNode);
                            this.setState({ treeData: treeData, selectedKeys: [treeData[0][this.keyField]] }, function () { return _this.props.onSelect(_this.state.treeData[0]); });
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    default_1.prototype.onLoadData = function (treeNode) {
        var _this = this;
        if (_.isArray(treeNode.props.children) && treeNode.props.children.length > 0) {
            return new Promise(function (resolve) { return resolve(); });
        }
        utils_1.Ajax.SESION("" + this.props.child + treeNode.props.eventKey + this.childSuffix);
        return utils_1.Ajax.GET("" + this.props.child + treeNode.props.eventKey + this.childSuffix).then(function (resp) {
            treeNode.props.dataRef.children = resp.data;
            _this.setState({
                treeData: __spread(_this.state.treeData),
            });
        });
    };
    default_1.prototype.onSelect = function (keys, nodes) {
        if (keys.length == 0) {
            if (this.props.mustSelect) {
                return;
            }
            else {
                this.setState({ selectedKeys: [] });
                this.props.onSelect(null, null);
                return;
            }
        }
        this.setState({ selectedKeys: keys });
        this.props.onSelect(nodes[0].props.dataRef, nodes[0].props.parent);
    };
    default_1.prototype.render = function () {
        var _this = this;
        if (this.state.loading) {
            return React.createElement(antd_1.Spin, { style: { margin: '24px auto', textAlign: 'center', width: '100%' } });
        }
        var param = {};
        if (this.state.treeData.length == 1) {
            param.defaultExpandedKeys = [this.state.treeData[0][this.keyField]];
            param.defaultSelectedKeys = [this.state.treeData[0][this.keyField]];
        }
        return React.createElement(antd_1.Tree, __assign({ showLine: true }, param, this.props, { selectedKeys: this.state.selectedKeys, onSelect: function (selectedKeys, evt) { return _this.onSelect(selectedKeys, evt.selectedNodes); }, loadData: function (treeNode) { return _this.onLoadData(treeNode); }, ref: function (tree) { return _this.tree = tree; } }), this.renderTreeNodes(this.state.treeData));
    };
    return default_1;
}(React.PureComponent));
exports.default = default_1;
