/**
 * Created by jun on 2017/3/29.
 */

// create tree
var createTree = function (opts) {
    var tree = {
        treeId: opts.treeId,
        opts: opts,
        init: function (opts) {
            var self = this;
            $(opts.treeId).tree({
                url: opts.url,
                method: opts.method || 'get',
                checkbox: opts.checkbox || false,
                animate: opts.animate || false,
                dnd: opts.dnd || false,
                lines: opts.lines || false,
                onClick: opts.onClick,
                onDragEnter: opts.onDragEnter || undefined,
                onBeforeDrop: opts.onBeforeDrop || undefined,
                onBeforeExpand: opts.onBeforeExpand || undefined,
                onContextMenu: function(e, node){
                    e.preventDefault();
                    $(opts.treeId).tree('select', node.target);
                    $(opts.menu).menu('show', {
                        left: e.pageX,
                        top: e.pageY
                    });
                },
                formatter: function (node) {
                    if(opts.formatter){
                        return opts.formatter(node);
                    }else{
                        return node.text;
                    }
                },
                loadFilter: opts.loadFilter || function (data, parent) {
                    if(opts.loadCallBack){
                        opts.loadCallBack(data);
                    }
                    if (data.data){
                        return data.data;
                    }else{
                        return data
                    }
                },
                onLoadSuccess: opts.onLoadSuccess || function (node, data) {
                    return false;
                }
            });
            return self
        },
        getIdChecked: function () {
            var self = this;
            var idList = [];
            var nodes = $(self.opts.treeId).tree('getChecked');
            for (var i=0; i<nodes.length; i++) {
                if(nodes[i].is_pNode){
                    continue
                }
                var parent = $(self.opts.treeId).tree('getParent', nodes[i].target);
                if(parent && idList.indexOf(parent.id) == -1){
                    if(!parent.is_pNode){
                        idList.push(parent.id);
                    }
                }
                idList.push(nodes[i].id);
            }
            return idList;
        }
    }
    return tree.init(opts);
}
