/**
 * Created by Tony on 2017/4/27.
 */

var pageOprObj = {
    rationLibName : null,
    rationLibId : null,
    initPage : function() {
        var me = this, rationLibId = getQueryString("repository"),//获取定额库参数
            rationLibName = storageUtil.getSessionCache("RationGrp","repositoryID_" + rationLibId);
        if (rationLibName) {
            var html = $("#rationname")[0].outerHTML;
            html = html.replace("XXX定额库", rationLibName);
            $("#rationname")[0].outerHTML = html;
            me.rationLibName = rationLibName;
            me.rationLibId = rationLibId;
            zTreeOprObj.getRationTree(rationLibId);
        }
    }
}
var zTreeOprObj = {
    treeObj: null,
    getRationTree: function(rationLibId){
        var me = this;
        $.ajax({
            type:"POST",
            url:"api/getRationTree",
            data:{"rationLibId": rationLibId},
            dataType:"json",
            cache:false,
            timeout:20000,
            success:function(result,textStatus,status){
                if(status.status == 200) {
                    if (result.data.length > 0) {
                        storageUtil.setSessionCache("RationGrp","repositoryID",result.data[0].rationRepId);
                    }
                    zTreeHelper.createTree(result.data, setting, "rationChapterTree", me);
                }
            },
            error:function(err){
                alert(err.responseJSON.error);
            }
        })
    },
    addRootNode: function() {
        var me = zTreeOprObj, rawNode = {ParentID: -1, NextSiblingID: -1, name: "新增节点"}, lastNodeId = -1;
        if (me.treeObj) {
            var rootNodes = me.treeObj.getNodes();
            if (rootNodes.length > 0) {
                lastNodeId = rootNodes[rootNodes.length - 1].ID;
            }
        }
        me.addNewNode(rawNode, lastNodeId, function(err, rst){
            if (!(err)) {
                var newNodes = [], isSilent = false;
                newNodes.push({ rationRepId: rst.data.rationRepId, ID: rst.data.ID, ParentID:-1, NextSiblingID:-1, name:"新增节点",isParent:false, items:[]});
                if (me.treeObj) {
                    me.treeObj.addNodes(null, -1, newNodes, isSilent);
                } else {
                    me.treeObj = $.fn.zTree.init($("#rationChapterTree"), setting, newNodes);
                }
            }
        });
    },
    addNewNode : function(rawNode, lastNodeId, callback){
        $.ajax({
            type:"POST",
            url:"api/createNewNode",
            data:{"rationLibId":pageOprObj.rationLibId,"lastNodeId": lastNodeId, "rawNodeData": JSON.stringify(rawNode)},
            dataType:"json",
            cache:false,
            timeout:1000,
            success: function(result,textStatus,status){
                callback(false, result);
            },
            error:function(err){
                callback(err);
            }
        })
    },
    beforeRename: function(treeId, treeNode, newName, isCancel) {
        if (newName.length == 0) {
            return false;
        }
        return true;
    },
    onRename : function(e, treeId, treeNode, isCancel) {
        var nodes = [];
        nodes.push(treeNode);
        zTreeOprObj.updateNodes(nodes);
    },
    onBeforeRemove: function(treeId, treeNode){
        var nodeIds = [], preNode = treeNode.getPreNode(), preNodeId = -1;
        if (preNode) {
            preNodeId = preNode.ID;
        }
        private_fetchAllSubItems = function(pItem){
            nodeIds.push(pItem.ID);
            if (pItem.items && pItem.items.length > 0) {
                for (var i = 0; i < pItem.items.length; i++) {
                    private_fetchAllSubItems(pItem.items[i]);
                }
            }
        };
        nodeIds.push(treeNode.ID);
        for (var i = 0; i < treeNode.items.length; i++) {
            private_fetchAllSubItems(treeNode.items[i]);
        }
        $.ajax({
            type:"POST",
            url:"api/deleteNodes",
            data:{"nodes": JSON.stringify(nodeIds), "preNodeId": preNodeId, "preNodeNextId": treeNode.NextSiblingID},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result,textStatus,status){
                var pNode = treeNode.getParentNode();
                if (pNode && pNode.items && pNode.items.length == 1) {
                    pNode.isParent = false;
                }
            },
            error:function(){
            }
        });
        return true;
    },
    onRemove: function(e, treeId, treeNode){
        var me = zTreeOprObj, pNode = me.treeObj.getNodeByTId(treeNode.parentTId);
        if (pNode && pNode.items && pNode.items.length == 0) {
            pNode.isParent = false;
            me.treeObj.refresh();
            //me.treeObj.updateNode(pNode, false); //这方法有后遗症，多次操作后会造成节点新增子节点时，父节点icon显示不正确
        }
    },
    updateNodes: function(nodes){
        if (nodes && nodes.length > 0) {
            var reqData = []
            for (var i = 0; i < nodes.length; i++) {
                var node = {};
                node.rationRepId = nodes[i].rationRepId;
                node.ID = nodes[i].ID;
                node.ParentID = nodes[i].ParentID;
                node.NextSiblingID = nodes[i].NextSiblingID;
                node.name = nodes[i].name;
                if (nodes[i].__v != null) node.__v = nodes[i].__v + 1
                else node.__v = 0;
                reqData.push(node);
            }
            $.ajax({
                type:"POST",
                url:"api/updateNodes",
                data:{"nodes": JSON.stringify(reqData)},
                dataType:"json",
                cache:false,
                timeout:5000,
                success:function(result,textStatus,status){
                    console.log(status + ' : ' + result);
                },
                error:function(){
                }
            })
        }
    },
    addHoverDom: function(treeId, treeNode) {
        var me = zTreeOprObj, sObj = $("#" + treeNode.tId + "_span");
        //if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0||(treeNode.level==2)) return;
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增子节点' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(){
            var rawNode = {ParentID: treeNode.ID, NextSiblingID: -1, name: "新增子节点"}, lastNodeId = -1;
            if (treeNode.items.length > 0) {
                lastNodeId = treeNode.items[treeNode.items.length - 1].ID;
            }
            zTreeOprObj.addNewNode(rawNode, lastNodeId, function(err, rst){
                if (!(err)) {
                    var newNodes = [], isSilent = false;
                    newNodes.push({ rationRepId: rst.data.rationRepId, ID: rst.data.ID, ParentID: rst.data.ParentID, NextSiblingID:-1, name:"新增子节点",isParent:false, items:[]});
                    treeNode.isParent = true;
                    if (me.treeObj) {
                        me.treeObj.addNodes(treeNode, -1, newNodes, isSilent);
                    } else {
                        me.treeObj = $.fn.zTree.init($("#rationChapterTree"), setting, newNodes);
                    }
                }
            });
        });
    },
    removeHoverDom: function(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    },
    onClick: function(event,treeId,treeNode) {
        var sectionID = treeNode.ID;
        if (!(treeNode.items) || treeNode.items.length == 0) {
            rationOprObj.getRationItems(sectionID);
        } else {
            sheetCommonObj.cleanSheet(rationOprObj.workBook.getSheet(0), rationOprObj.setting, -1);
            sheetCommonObj.shieldAllCells(rationOprObj.workBook.getSheet(0));
        }
        sheetCommonObj.cleanSheet(rationGLJOprObj.workBook.getSheet(0), rationGLJOprObj.setting, -1);
        sheetCommonObj.shieldAllCells(rationGLJOprObj.workBook.getSheet(0));
    }

};
