/**
 * Created by Tony on 2017/5/5.
 */

$("#drirect-dinge").click(function(){
    $(this).attr('href', "/rationRepository/ration" + "?repository=" + getQueryString("repository"))
});

$("#fuzhu").click(function(){
    $(this).attr('href', "/rationRepository/coeList" + "?repository=" + getQueryString("repository"))
});

var pageOprObj = {
    rationLibName : null,
    initPage : function(container) {
        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;
            repositoryGljObj.currentRepositoryId = parseInt(rationLibId);
            repositoryGljObj.getGljTree(rationLibId);
            repositoryGljObj.buildSheet(container);
            repositoryGljObj.getGljItems(rationLibId);
            sheetCommonObj.shieldAllCells(repositoryGljObj.workBook.getSheet(0), repositoryGljObj.setting);
        }
    }
}
repositoryGljObj = {
    treeObj : null,
    workBook: null,
    gljCurTypeId: -1,
    currentRepositoryId: -1,
    currentCache: null,
    parentNodeIds: {},
    gljList: [],
    setting: {
        header:[
            {headerName:"编码",headerWidth:120,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:260,dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"规格",headerWidth:260,dataCode:"specs", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"单位",headerWidth:120,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"基价单价",headerWidth:120,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"},
            {headerName:"类型",headerWidth:120,dataCode:"gljDistType", dataType: "String", hAlign: "center", vAlign: "center"}
        ],
        view:{
            comboBox:[
                {row:-1,col:3,rowCount:-1,colCount:1}
            ],
            lockedCells:[
            ]
        }
    },
    getGljTree: function(rationLibId) {
        var me = this;
        $.ajax({
            type:"POST",
            url:"api/getGljTree",
            data:{"rationLibId": rationLibId},
            dataType:"json",
            cache:false,
            timeout:20000,
            success:function(result,textStatus,status){
                if(status.status == 200) {
                    zTreeHelper.createTree(result.data, gljSetting, "repositoryTree", me);
                    if (result.data && result.data.length > 0) {
                        me.gljCurTypeId = result.data[0].ID;
                    } else {
                        gljTypeTreeOprObj.addRootNode();
                    }
                }
            },
            error:function(err){
                alert(err.responseJSON.error);
            }
        })
    },
    getGljItems: function(repId) {
        var me = this;
        $.ajax({
            type:"POST",
            url:"api/getGljItems",
            data:{"repositoryId": repId},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result){
                if(!result.error) {
                    me.gljList = result.data;
                    me.sortGlj();
                    me.showGljItems(result.data, me.gljCurTypeId);
                }
            },
            error:function(err){
                alert(err.responseJSON.error);
            }
        })
    },
    showGljItems: function(data, type) {
        var me = repositoryGljObj;
        if (me.workBook) {
            var cacheSection = [];
            var pArr = me.parentNodeIds["_pNodeId_" + type];
            for (var i = 0; i < data.length; i++) {
                if (pArr && pArr.indexOf(data[i].gljType) >= 0) {
                    cacheSection.push(data[i]);
                } else if (type == data[i].gljType) {
                    cacheSection.push(data[i]);
                }
            }
            sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
            sheetCommonObj.showData(me.workBook.getSheet(0), me.setting, cacheSection);
            cacheSection = null;
        }
    },
    buildSheet: function(container) {
        var me = repositoryGljObj;
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
        me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditStarting, me.onCellEditStart);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EditEnded, me.onCellEditEnd);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.RangeChanged, me.onRangeChanged);
    },
    onCellEditStart: function(sender, args) {
        var me = repositoryGljObj;
        var rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row);
        me.currentEditingGlj = rObj;
        var cacheSection = me.gljList;
        if (cacheSection) {
            for (var j = 0; j < cacheSection.length; j++) {
                if (cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
                    rObj["ID"] = cacheSection[j]["ID"];
                    break;
                }
            }
        }
    },
    onCellEditEnd: function(sender, args) {
        var me = repositoryGljObj, rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row),
            updateArr = [], addArr = [];
        if (me.currentEditingGlj["ID"]) {
            rObj["ID"] = me.currentEditingGlj["ID"];
            updateArr.push(rObj);
        } else {
            addArr.push(rObj);
        }
        rObj.gljType = me.gljCurTypeId;
        me.currentEditingGlj = null;
        me.mixUpdateRequest(updateArr, addArr, []);
    },
    onRangeChanged: function(sender, args) {
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            var me = repositoryGljObj, updateArr = [], removeArr = [];
            var cacheSection = me.currentCache;
            if (cacheSection) {
                for (var i = 0; i < args.rowCount; i++) {
                    var hasUpdate = false, rObj = sheetCommonObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row + i),
                        isEmpty = sheetCommonObj.chkIfEmpty(rObj, me.setting);
                    for (var j = 0; j < cacheSection.length; j++) {
                        if (cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
                            rObj["ID"] = cacheSection[j]["ID"];
                            hasUpdate = true;
                            break;
                        }
                    }
                    if (hasUpdate) {
                        if (isEmpty) {
                            removeArr.push(rObj["ID"]);
                        } else updateArr.push(rObj);
                    } else if (isEmpty) {
                        if (args.row + i < cacheSection.length) {
                            rObj["ID"] = cacheSection[args.row + i]["ID"];
                            removeArr.push(rObj["ID"]);
                        }
                    }
                }
                me.mixUpdateRequest(updateArr, [], removeArr);
            }
        }
    },
    onClipboardPasting: function(sender, args) {
        var me = repositoryGljObj;
        if (args.cellRange.colCount != me.setting.header.length || me.gljCurTypeId < 0 || me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]) {
            args.cancel = true;
        }
    },
    onClipboardPasted: function(e, info) {
        var me = repositoryGljObj;
        var updateArr = [], addArr = [];
        var items = sheetCommonObj.analyzePasteData(me.setting, info);
        var hasCacheItem = false;
        for (var i = 0; i < items.length; i++) {
            for (var j = 0; j < me.gljList.length; j++) {
                if (me.gljList[j][me.setting.header[0].dataCode] == items[i][me.setting.header[0].dataCode]) {
                    hasCacheItem = true;
                    items[i]["ID"] = me.gljList[j]["ID"];
                    break;
                }
            }
            if (!hasCacheItem) {
                items[i].gljType = me.gljCurTypeId;
                addArr.push(items[i]);
            } else {
                updateArr.push(items[i]);
            }
        }
        if (updateArr.length > 0 || addArr.length > 0) {
            me.mixUpdateRequest(updateArr, addArr, []);
        }
    },
    mixUpdateRequest: function(updateArr, addArr, removeIds) {
        var me = repositoryGljObj;
        $.ajax({
            type:"POST",
            url:"api/mixUpdateGljItems",
            data:{"repositoryId": me.currentRepositoryId, "updateItems": JSON.stringify(updateArr), "addItems": JSON.stringify(addArr), "removeIds": JSON.stringify(removeIds)},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result){
                if (result.error) {
                    alert(result.message);
                    me.getRationItems(me.currentRepositoryId);
                } else {
                    me.updateCache(addArr, updateArr, removeIds, result);
                    me.sortGlj();
                    me.currentCache = me.getCache();
                    me.showGljItems(me.gljList, me.gljCurTypeId);
                }
            },
            error:function(err){
                alert("保存失败");
            }
        })
    },
    getCache: function() {
        var me = this, rst = [];
        for (var i = 0; i < me.gljList.length; i++) {
            if (me.gljList[i].gljType == me.gljCurTypeId) {
                rst.push(me.gljList[i]);
            }
        }
        return rst;
    },
    updateCache: function(addArr, updateArr, removeIds, result) {
        var me = this, cacheSection = me.gljList;
        if (addArr.length > 0) {
            me.gljList = me.gljList.concat(addArr);
            cacheSection = me.gljList;
        }
        for (var i = removeIds.length - 1; i >= 0; i--) {
            for (var j = cacheSection.length - 1; j >= 0 ; j--) {
                if (cacheSection[j]["ID"] == removeIds[i]) {
                    cacheSection.splice(j,1);
                }
            }
        }
        if (result && result.data.ops && result.data.ops.length > 0) {
            for (var i = 0; i < result.data.ops.length; i++) {
                for (var j = 0; j < cacheSection.length; j++) {
                    if (cacheSection[j][me.setting.header[0].dataCode] == result.data.ops[i][me.setting.header[0].dataCode]) {
                        cacheSection[j]["ID"] = result.data.ops[i]["ID"];
                    }
                }
            }
        }
        for (var i = 0; i < updateArr.length; i++) {
            for (var j = 0; j < cacheSection.length; j++) {
                if (updateArr[i]["ID"] && cacheSection[j]["ID"]) {
                    if (cacheSection[j]["ID"] == updateArr[i]["ID"]) {
                        cacheSection[j] = updateArr[i];
                    }
                } else {
                    if (cacheSection[j][me.setting.header[0].dataCode] == updateArr[i][me.setting.header[0].dataCode]) {
                        cacheSection[j] = updateArr[i];
                    }
                }
            }
        }
    },
    sortGlj: function() {
        var me = this;
        me.gljList.sort(function(a, b){
            var rst = 0;
            if (a.code > b.code) rst = 1
            else if (a.code < b.code) rst = -1;
            return rst;
        });
    }
}

var gljTypeTreeOprObj = {
    onClick: function(event,treeId,treeNode) {
        var me = repositoryGljObj,
            gljTypeId = treeNode.ID;
        me.gljCurTypeId = treeNode.ID;
        me.currentCache = me.getCache();
        me.showGljItems(me.gljList, gljTypeId);
        if (me.parentNodeIds["_pNodeId_" + treeNode.ID]) {
            sheetCommonObj.shieldAllCells(me.workBook.getSheet(0), me.setting);
        } else {
            sheetCommonObj.unShieldAllCells(me.workBook.getSheet(0));
        }
    },
    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);
        gljTypeTreeOprObj.updateNodes(nodes);
    },
    onBeforeRemove: function(treeId, treeNode){
        if (treeNode.ParentID == -1 && treeNode.isFirstNode) {
            alert("不允许删除全部！");
            return false;
        }
        if (!confirm("您确定要删除此节点及所有子节点的数据？删除后不可恢复！")) {
            return false;
        }
        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/deleteGljNodes",
            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 = repositoryGljObj, pNode = me.treeObj.getNodeByTId(treeNode.parentTId);
        if (pNode && pNode.items && pNode.items.length == 0) {
            pNode.isParent = false;
            me.treeObj.refresh();
        }
    },
    updateNodes: function(nodes){
        if (nodes && nodes.length > 0) {
            var reqData = []
            for (var i = 0; i < nodes.length; i++) {
                var node = {};
                node.repositoryId = nodes[i].repositoryId;
                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/updateGljNodes",
                data:{"nodes": JSON.stringify(reqData)},
                dataType:"json",
                cache:false,
                timeout:5000,
                success:function(result,textStatus,status){
                    console.log(status + ' : ' + result);
                },
                error:function(){
                }
            })
        }
    },
    addRootNode: function() {
        var me = repositoryGljObj, rawNode = {ParentID: -1, NextSiblingID: -1, Name: "所有"}, lastNodeId = -1;
        if (me.treeObj) {
            var rootNodes = me.treeObj.getNodes();
            if (rootNodes.length == 0) {
                gljTypeTreeOprObj.addNewNode(rawNode, lastNodeId, function(err, rst){
                    if (!(err)) {
                        var newNodes = [], isSilent = false;
                        newNodes.push({ repositoryId: rst.data.repositoryId, ID: rst.data.ID, ParentID: rst.data.ParentID, NextSiblingID:-1, Name:"所有",isParent:false, items:[]});
                        me.treeObj.addNodes(null, -1, newNodes, isSilent);
                    }
                });
            }
        }
    },
    addNewNode : function(rawNode, lastNodeId, callback){
        $.ajax({
            type:"POST",
            url:"api/createNewGljTypeNode",
            data:{"repositoryId": repositoryGljObj.currentRepositoryId,"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);
            }
        })
    },
    addHoverDom: function(treeId, treeNode) {
        var me = repositoryGljObj, sObj = $("#" + treeNode.tId + "_span");
        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;
            }
            gljTypeTreeOprObj.addNewNode(rawNode, lastNodeId, function(err, rst){
                if (!(err)) {
                    var newNodes = [], isSilent = false;
                    newNodes.push({ repositoryId: rst.data.repositoryId, 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"), gljSetting, newNodes);
                    }
                }
            });
        });
    },
    removeHoverDom: function(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    }

}
