
const createNewPathTree = function (setting) {
    const treeSetting = JSON.parse(JSON.stringify(setting));
    const itemsPre = 'id_';
    const postData = function (url, data, successCallback) {
        $.ajax({
            type:"POST",
            url: url,
            data: {'data': JSON.stringify(data)},
            dataType: 'json',
            cache: false,
            timeout: 5000,
            beforeSend: function(xhr) {
                let csrfToken = Cookies.get('csrfToken');
                xhr.setRequestHeader('x-csrf-token', csrfToken);
            },
            success: function(result){
                if (result.err === 0) {
                    if (successCallback) {
                        successCallback(result.data);
                    }
                } else {
                    toast('error: ' + result.message, 'error', 'exclamation-circle');
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                toast('error ' + textStatus + " " + errorThrown, 'error', 'exclamation-circle');
            }
        });
    };

    const PathTree = function () {
        // 无索引
        this.datas = [];
        // 以key为索引
        this.items = {};
        // 以排序为索引
        this.nodes = [];
    };
    const proto = PathTree.prototype;
    /**
     * 树结构根据显示排序
     */
    proto.sortTreeNode = function () {
        const self = this;
        const addSortNodes = function (nodes) {
            for (let i = 0; i < nodes.length; i++) {
                self.nodes.push(nodes[i]);
                addSortNodes(self.getChildren(nodes[i]));
            }
        };
        self.nodes = [];
        addSortNodes(this.getChildren(null));
    };
    /**
     * 加载数据(初始化), 并给数据添加部分树结构必须数据
     * @param datas
     */
    proto.loadDatas = function (datas) {
        // 清空旧数据
        this.items = {};
        this.nodes = [];
        // 加载全部数据
        for (const data of datas) {
            const keyName = itemsPre + data[treeSetting.id];
            this.items[keyName] = JSON.parse(JSON.stringify(data));
            this.datas.push(this.items[keyName]);
        }
        this.sortTreeNode();
        for (const node of this.nodes) {
            const children = this.getChildren(node);
            node.expanded = children.length > 0;
            node.visible = true;
        }
    };
    /**
     * 加载数据(动态)，只加载不同部分
     * @param {Array} datas
     * @privateA
     */
    proto._loadData = function (datas) {
        for (const data of datas) {
            let node = this.getItems(data[treeSetting]);
            if (node) {
                for (const prop of node.propertyNameList) {
                    if (data[prop]) {
                        node[prop] = data[prop];
                    }
                }
            } else {
                const keyName = itemsPre + data[treeSetting.id];
                const node = JSON.parse(JSON.stringify(data));
                this.items[keyName] = node;
                this.datas.push(node);
                node.expanded = false;
                node.visible = true;
            }
        }
        this.sortTreeNode();
    }
    /**
     * 根据id获取树结构节点数据
     * @param {Number} id
     * @returns {Object}
     */
    proto.getItems = function (id) {
        return this.items[itemsPre + id];
    };
    /**
     * 查找node的parent
     * @param {Object} node
     * @returns {Object}
     */
    proto.getParent = function (node) {
        return this.getItems(node[treeSetting.pid]);
    };
    /**
     * 查询node的已下载子节点
     * @param {Object} node
     * @returns {Array}
     */
    proto.getChildren = function (node) {
        const pid = node ? node[treeSetting.id] : treeSetting.rootId;
        const children = this.datas.filter(function (x) {
            return x[treeSetting.pid] === pid;
        });
        children.sort(function (a, b) {
            return a.order - b.order;
        });
        return children;
    };
    /**
     * 查询node的已下载的全部后代
     * @param {Object} node
     * @returns {Array}
     */
    proto.getPosterity = function (node) {
        const reg = new RegExp('^' + node.full_path);
        return this.datas.filter(function (x) {
            return reg.test(x.full_path);
        })
    };
    /**
     * 查询node是否是父节点的最后一个子节点
     * @param {Object} node
     * @returns {boolean}
     */
    proto.isLastSibling = function (node) {
        const siblings = this.getChildren(this.getParent(node));
        return node.order === siblings.length;
    };
    /**
     * 刷新子节点是否可见
     * @param {Object} node
     * @private
     */
    proto._refreshChildrenVisible = function (node) {
        const children = this.getChildren(node);
        for (const child of children) {
            child.visible = node.expanded && node.visible;
            this._refreshChildrenVisible(child);
        }
    }
    /**
     * 设置节点是否展开, 并控制子节点可见
     * @param {Object} node
     * @param {Boolean} expanded
     */
    proto.setExpanded = function (node, expanded) {
        node.expanded = expanded;
        this._refreshChildrenVisible(node);
    };

    /**
     * 以下方法需等待响应
     */
    /**
     * 加载子节点, callback中应刷新界面
     * @param {Object} node
     * @param {function} callback
     */
    proto.loadChildren = function (node, callback) {
        const self = this;
        postData('get-children', {id: node[treeSetting.id]}, function (data) {
            self._loadData(data);
            callback();
        });
    }

    return new PathTree();
}