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

var pageOprObj = {
    rationLibName : null,
    rationLibId: null,
    initPage : function(container) {
        var me = this;//获取定额库参数
        repositoryGljObj.buildSheet(container);
        repositoryGljObj.getGljDistType(function () {
            //引用的工料机库
            if(gljLibId && typeof gljLibId !== 'undefined'){
                repositoryGljObj.getGljTree(gljLibId, function () {
                    repositoryGljObj.getGljItems(gljLibId);
                });
            }
            sheetCommonObj.shieldAllCells(repositoryGljObj.workBook.getSheet(0), repositoryGljObj.setting);
        });

    }
}
repositoryGljObj = {
    treeObj : null,
    workBook: null,
    gljCurTypeId: -1,
    currentRepositoryId: -1,
    currentCache: null,
    parentNodeIds: {},
    gljList: [],
    distTypeTree: null,//add
    setting: {
        header:[
            {headerName:"编码",headerWidth:90,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:200,dataCode:"name", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"规格型号",headerWidth:110,dataCode:"specs", dataType: "String", hAlign: "left", vAlign: "center"},
            {headerName:"单位",headerWidth:60,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"定额价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"},
            {headerName:"类型",headerWidth:90,dataCode:"gljType", dataType: "String", hAlign: "center", vAlign: "center"}
        ],
        view:{
            comboBox:[
                {row:-1,col:3,rowCount:-1,colCount:1}
            ],
            lockedCells:[
            ]
        }
    },
    getComboData: function (gljDistType) {
        let me = this;
        let distType;
        let distTypeTree = {
            prefix : 'gljType',
            distTypes: {},
            comboDatas: [],
            distTypesArr: []
        };
        gljDistType.forEach(function (typeData) {
            let typeObj = {
                data: typeData,
                children: [],
                parent: null
            }
            distTypeTree.distTypes[distTypeTree.prefix + typeData.ID] = typeObj;
            distTypeTree.distTypesArr.push(typeObj);
        });
        gljDistType.forEach(function (typeData) {
            distType = distTypeTree.distTypes[distTypeTree.prefix + typeData.ID];
            let parent = distTypeTree.distTypes[distTypeTree.prefix + typeData.ParentID];
            if(parent){
                distType.parent = parent;
                parent.children.push(distType);
            }
        });
        distTypeTree.distTypesArr.forEach(function (distTypeObj) {
            if(distTypeObj.data.fullName !== '材料'){
                distTypeTree.comboDatas.push({text: distTypeObj.data.fullName, value: distTypeObj.data.ID});
            }
        });
        return distTypeTree;
    },
    getGljDistType: function (callback) {
        let me = this;
        CommonAjax.post('/complementaryRation/api/getGljDistType', {}, function (rstData) {
            me.distTypeTree = me.getComboData(rstData);
            me.workBook.getSheet(0).getCell(-1, 5, GC.Spread.Sheets.SheetArea.viewport).value(me.distTypeTree.comboDatas[0].text);
            if(callback){
                callback();
            }
        });
    },
    getGljTree: function(gljLibId, callback) {
        var me = this;
        CommonAjax.post('/complementaryRation/api/getGljTree', {gljLibId: gljLibId}, function (rstData) {
            zTreeHelper.createTree(rstData, gljSetting, "repositoryTree", me);
            if (rstData && rstData.length > 0) {
                me.gljCurTypeId = rstData[0].ID;
            } else {
                gljTypeTreeOprObj.addRootNode();
            }
            callback();
        });
    },
    getGljItems: function(gljLibId) {
        var me = this;
        CommonAjax.post('/complementaryRation/api/getGljItems', {stdGljLibId: gljLibId}, function (rstData) {
            me.gljList = rstData.stdGljs.concat(rstData.complementaryGljs);
            me.workBook.getSheet(0).setRowCount(rstData.length);
            me.sortGlj();
            let rootNode = me.treeObj.getNodes()[0];
            if(rootNode && rootNode.isParent && rootNode.isFirstNode){
                me.treeObj.selectNode(rootNode);
                gljTypeTreeOprObj.onClick(null, 'repositoryTree', rootNode);
            }
        });

    },
    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].gljClass) >= 0) {
                    cacheSection.push(data[i]);
                } else if (type == data[i].gljClass) {
                    //data[i].gljDistType = me.distTypeTree.distTypes[me.distTypeTree.prefix + data[i].gljDistType].data.fullName;
                    cacheSection.push(data[i]);
                }
            }
            sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
            sheetsOprObj.showData(me.workBook.getSheet(0), me.setting, cacheSection, me.distTypeTree);

            cacheSection = null;
        }
    },
    buildSheet: function(container) {
        var me = repositoryGljObj;
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30, me);
        sheetCommonObj.spreadDefaultStyle(me.workBook);
        me.workBook.getSheet(0).options.isProtected = true;
        /* me.repositoryGljDelOpr();
         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);
         me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.EnterCell, me.onEnterCell);*/
    },
    onEnterCell: function (sender, args) {
        let me = repositoryGljObj;
        me.cellRowIdx = args.row;
        let isHasData = false;
        if(me.addGljObj){
            for(let i=0; i<me.setting.header.length; i++){
                if(me.addGljObj[me.setting.header[i].dataCode]){
                    isHasData = true;
                    break;
                }
            }
        }
        if(isHasData){
            if(me.editingRowIdx !== me.cellRowIdx) {
                let isComple = true;
                let focusToCol;
                function getFocusToCol (me){
                    if(!me.addGljObj[me.setting.header[0].dataCode]){
                        $('#alertGljTxt').text('编号不能为空，是否取消增加人材机?');
                        return 0;
                    }
                    else if(!me.addGljObj[me.setting.header[1].dataCode]){
                        $('#alertGljTxt').text('名称不能为空，是否取消增加人材机?');
                        return 1;
                    }
                    else if(!me.addGljObj[me.setting.header[5].dataCode]){
                        $('#alertGljTxt').text('类型不能为空，是否取消增加人材机?');
                        return 5;
                    }
                    else {
                        return -1;
                    }
                }
                focusToCol = getFocusToCol(me);
                if(focusToCol === -1){

                }
                else {
                    $('#gljAlertBtn').click();
                    //me.workBook.getSheet(0).options.isProtected = true;
                    sheetCommonObj.lockAllCells(args.sheet);
                    $('#aleCanceBtn').click(function () {
                        // me.workBook.getSheet(0).options.isProtected = false;
                        sheetCommonObj.unLockAllCells(args.sheet);
                        sheetsOprObj.reLockSomeCodes(args.sheet, 0, repositoryGljObj.currentCache.length);
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, focusToCol);
                    });
                    $('#gljAleClose').click(function () {
                        // me.workBook.getSheet(0).options.isProtected = false;
                        sheetCommonObj.unLockAllCells(args.sheet);
                        sheetsOprObj.reLockSomeCodes(args.sheet, 0, repositoryGljObj.currentCache.length);
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, focusToCol);
                    });
                    $('#aleConfBtn').click(function () {
                        // me.workBook.getSheet(0).options.isProtected = false;
                        sheetCommonObj.unLockAllCells(args.sheet);
                        sheetsOprObj.reLockSomeCodes(args.sheet, 0, repositoryGljObj.currentCache.length);
                        me.addGljObj = null;
                        for(let col=0; col<me.setting.header.length; col++){
                            let field = me.setting.header[col].dataCode;
                            if(field === 'gljType'){
                                me.workBook.getSheet(0).getCell(me.editingRowIdx, col).value(
                                    me.distTypeTree.distTypes[me.distTypeTree.prefix + me.currentEditingGlj[field]].data.fullName);
                            }
                            else{
                                me.workBook.getSheet(0).getCell(me.editingRowIdx, col).value(me.currentEditingGlj[me.setting.header[col].dataCode]);
                            }
                        }
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, 0);
                    });
                }
            }
        }
    },
    onCellEditStart: function(sender, args) {
        var me = repositoryGljObj;
        var rObj = sheetsOprObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row);
        me.currentEditingGlj = rObj;
        me.orgCode = me.workBook.getSheet(0).getValue(args.row, 0);
        var cacheSection = me.gljList;
        if (cacheSection) {
            for (var j = 0; j < cacheSection.length; j++) {
                if (cacheSection[j][me.setting.header[0].dataCode] && cacheSection[j][me.setting.header[0].dataCode] == rObj[me.setting.header[0].dataCode]) {
                    rObj["ID"] = cacheSection[j]["ID"];
                    rObj.gljClass = cacheSection[j].gljClass;
                    break;
                }
            }
        }
    },
    onCellEditEnd: function(sender, args) {
        var me = repositoryGljObj, rObj = sheetsOprObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row, me),
            updateArr = [], addArr = [], updateBasePrcArr = [];
        me.editingRowIdx = args.row;
        rObj.basePrice = rObj.basePrice ? rObj.basePrice : 0;
        if (me.currentEditingGlj["ID"]) {
            rObj["ID"] = me.currentEditingGlj["ID"];
            rObj.gljClass = me.currentEditingGlj.gljClass;
            for(let col =0; col< me.setting.header.length; col++){
                if(me.currentEditingGlj[me.setting.header[col].dataCode] !== rObj[me.setting.header[col].dataCode]){
                    me.addGljObj = rObj;
                    if(rObj[me.setting.header[0].dataCode] && rObj[me.setting.header[1].dataCode] && rObj[me.setting.header[5].dataCode]){
                        updateArr.push(rObj);
                        break;
                    }
                }
            }
            if(me.currentEditingGlj.basePrice !== rObj.basePrice){
                //update basePrice of ration when editting basePrice of glj
                let gljType = -1;
                let gljTypeParent = me.distTypeTree.distTypes[me.distTypeTree.prefix + me.currentEditingGlj.gljType].parent;
                if(gljTypeParent && gljTypeParent.data.ID <=3){
                    gljType = gljTypeParent.data.ID;
                }
                if(!gljTypeParent && me.currentEditingGlj.gljType <= 3){
                    gljType = me.currentEditingGlj.gljType;
                }
                let gljBasePrcObj = {gljId: me.currentEditingGlj.ID, gljType: gljType, basePrice: rObj.basePrice};
                if(gljBasePrcObj.gljType !== -1){
                    updateBasePrcArr.push(gljBasePrcObj);
                    me.updateRationBasePrcRq(updateBasePrcArr);
                }
            }
            //update basePrice of ration when editting gljType of glj
            if(me.currentEditingGlj.gljType !== rObj.gljType){
                let gljTypeObj = {gljId: me.currentEditingGlj.ID, gljType: rObj.gljType, basePrice: rObj.basePrice};
                updateBasePrcArr.push(gljTypeObj);
                me.updateRationBasePrcRq(updateBasePrcArr);
            }
        } else {
            me.addGljObj = rObj;
            let isCanSav = true;
            if(!rObj[me.setting.header[0].dataCode] || !rObj[me.setting.header[1].dataCode] || !rObj[me.setting.header[5].dataCode]){
                isCanSav = false;
            }
            if(isCanSav){
                me.addGljObj = null;
                addArr.push(rObj);
            }
        }
        if(me.gljCurTypeId !== 1){
            rObj.gljClass = me.gljCurTypeId;
        }
        if(updateArr.length >0 || addArr.length >0){
            me.currentEditingGlj = null;
            //me.workBook.getSheet(0).setValue(11, 5, "人工");
            me.mixUpdateRequest(updateArr, addArr, []);
        }
    },
    repositoryGljDelOpr: function () {
        let me = repositoryGljObj;
        me.workBook.commandManager().register('repositoryGljDel', function () {
            let sheet = me.workBook.getSheet(0),
                updateArr = [], removeArr = [],
                tempRemoveArr= [],
                refGljCodes = [], //已被引用的工料机
                updateBasePrcArr = [],//删除基价单位后重新计算
                sels = sheet.getSelections(),
                cacheSection = me.currentCache;
            if(sels.length > 0 && cacheSection.length > 0){
                for(let i = 0; i < sels.length; i++){
                    if(sels[i].colCount === me.setting.header.length){
                        for(let j = 0; j < sels[i].rowCount; j++){
                            if(sels[i].row + j < cacheSection.length){
                                tempRemoveArr.push({ID: cacheSection[sels[i].row + j].ID, code: cacheSection[sels[i].row + j].code});
                            }
                        }
                    }
                    else{
                        let maxCol = sels[i].col + sels[i].colCount - 1;
                        if(sels[i].col >= 2 && maxCol <= 4){
                            for(let j = 0; j < sels[i].rowCount; j++){
                                if(sels[i].row + j < cacheSection.length){
                                    let updateObj = cacheSection[sels[i].row + j];
                                    for(let col = sels[i].col; col <= maxCol; col++){
                                        if(me.setting.header[col].dataCode === 'basePrice'){
                                            updateObj[me.setting.header[col].dataCode] = 0;
                                            updateBasePrcArr.push({gljId: updateObj.ID, gljType: updateObj.gljType, basePrice: 0});
                                        }
                                        else{
                                            updateObj[me.setting.header[col].dataCode] = '';
                                        }
                                    }
                                    updateArr.push(updateObj);
                                }
                            }
                        }
                        //编号、名称、类型不可为空
                        else{
                            if(sels[i].row < cacheSection.length){
                                let text = '', cantNullStr =['编码', '名称', '类型'];
                                for(let col = sels[i].col; col <= sels[i].col + sels[i].colCount -1; col++){
                                    if(cantNullStr.indexOf(me.setting.header[col].headerName) !== -1){
                                        text += me.setting.header[col].headerName + " ";
                                    }
                                }
                                $('#alertText').text(text + "不可为空！");
                                $('#codeAlertBtn').click();
                                sheet.options.isProtected = true;
                                $('#codAleConfBtn').click(function () {
                                    sheetsOprObj.lockSomeCodes(sheet, 0, cacheSection.length);
                                });
                                $('#codAleClose').click(function () {
                                    sheetsOprObj.lockSomeCodes(sheet, 0, cacheSection.length);
                                });
                            }
                        }
                    }
                }
                //提取已被引用工料机
                if(tempRemoveArr.length > 0){
                    for(let i = 0; i < tempRemoveArr.length; i++){
                        if(me.rationGljIds.indexOf(tempRemoveArr[i].ID) !== -1){
                            refGljCodes.push(tempRemoveArr[i].code);
                            tempRemoveArr.splice(i--, 1);
                        }
                        else{
                            removeArr.push(tempRemoveArr[i].ID);
                        }
                    }
                }
                //提示
                if(refGljCodes.length > 0){
                    let alertText;
                    if(refGljCodes.length > 3){
                        alertText = "编号: " + refGljCodes[0]+" 、" + refGljCodes[1] + " 、" + refGljCodes[2] + "...等人材机已有定额引用，删除失败！";
                    }
                    else {
                        let alertCode = " ";
                        for(let i=0; i< refGljCodes.length; i++){
                            alertCode += refGljCodes[i] + " 、";
                        }
                        alertText = "编号：" + alertCode + "工料机已有定额引用，删除失败！"
                    }
                    $('#alertText').text(alertText);
                    $('#codeAlertBtn').click();
                    sheet.options.isProtected = true;
                    $('#codAleConfBtn').click(function () {
                        sheetsOprObj.lockSomeCodes(sheet, 0, cacheSection.length);
                        if(removeArr.length > 0){
                            me.mixUpdateRequest(updateArr, [], removeArr);
                        }
                    });
                    $('#codAleClose').click(function () {
                        sheetsOprObj.lockSomeCodes(sheet, 0, cacheSection.length);
                        me.mixUpdateRequest(updateArr, [], removeArr);
                    });
                }
                else if(removeArr.length > 0 || updateArr.length > 0){
                    me.mixUpdateRequest(updateArr, [], removeArr);
                    if(updateBasePrcArr.length > 0){
                        me.updateRationBasePrcRq(updateBasePrcArr);
                    }
                }
            }

        });

        me.workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
        me.workBook.commandManager().setShortcutKey('repositoryGljDel', GC.Spread.Commands.Key.del, false, false, false, false);
    },
    validUpdateObj: function (pasteObj, rowIdx) {
        let rst = {}, backUpObj = {},
            me = repositoryGljObj,
            tempObj = me.currentCache[rowIdx],
            reCalBasePrc = false, isValid = true;
        //备份原始数据
        for(let atr in tempObj){
            backUpObj[atr] = tempObj[atr];
        }
        if(typeof pasteObj.code !== 'undefined'){
            if(pasteObj.code.trim().length !== 0){
                let isExist = false;
                for(let i = 0; i < me.gljList.length; i++){
                    if(me.gljList[i].code === pasteObj.code){
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    tempObj.code = pasteObj.code;
                }
                else isValid = false;
            }
            else isValid = false;
        }
        if(typeof pasteObj.name !== 'undefined'){
            if(pasteObj.name.trim().length === 0) isValid = false;
            else tempObj.name = pasteObj.name;
        }
        if(typeof pasteObj.specs !== 'undefined'){
            tempObj.specs = pasteObj.specs;
        }
        if(typeof pasteObj.unit !== 'undefined'){
            tempObj.unit = pasteObj.unit;
        }
        if(typeof pasteObj.gljType !== 'undefined'){
            let isExsit = false;
            for(let i = 0; i < me.distTypeTree.comboDatas.length; i++){
                if(pasteObj.gljType === me.distTypeTree.comboDatas[i].text){
                    isExsit = true;
                    reCalBasePrc = true;
                    tempObj.gljType = me.distTypeTree.comboDatas[i].value;
                    tempObj.shortName = me.distTypeTree.distTypes[me.distTypeTree.prefix + tempObj.gljType].data.shortName;

                }
            }
            if(!isExsit) isValid = false;
        }
        //
        pasteObj.basePrice = !isNaN(parseFloat(pasteObj.basePrice)) && (pasteObj.basePrice && typeof pasteObj.basePrice !== 'undefined') ? parseFloat(pasteObj.basePrice) :
            me.currentCache[rowIdx].basePrice;
        if(pasteObj.basePrice !== me.currentCache[rowIdx].basePrice){
            reCalBasePrc = true;
            tempObj.basePrice = pasteObj.basePrice;
        }
        if(isValid){
            rst.updateGlj = tempObj;
            if(reCalBasePrc){
                //重新计算定额基价对象
                rst.updateBasePrc = {gljId: tempObj.ID, gljType: tempObj.gljType, basePrice: tempObj.basePrice};
            }
        }
        else {
            for(let attr in backUpObj){
                tempObj[attr] = backUpObj[attr];
            }
        }
        return rst;
    },
    //粘贴的数据是否是可添加的数据,只有含有编号，名称，类型才可添加
    isValidObj: function(pasteObj) {
        let me = repositoryGljObj;
        if(!(pasteObj.code && typeof pasteObj.code !== 'undefined') || !(pasteObj.name && typeof pasteObj.name !== 'undefined') ||
            !(pasteObj.gljType && typeof pasteObj.gljType !== 'undefined')){
            return false;
        }
        if(pasteObj.gljType && typeof pasteObj.gljType !== 'undefined'){
            let isExist = false;
            for(let i = 0; i < me.distTypeTree.comboDatas.length; i++){
                if(me.distTypeTree.comboDatas[i].text === pasteObj.gljType){
                    isExist = true;
                    pasteObj.gljType = me.distTypeTree.comboDatas[i].value;
                    pasteObj.shortName = me.distTypeTree.distTypes[me.distTypeTree.prefix + pasteObj.gljType].data.shortName;
                    break;
                }
            }
            if(!isExist){
                return false;
            }
        }
        if(pasteObj.code && typeof pasteObj.code !== 'undefined'){
            for(let i = 0; i < me.gljList.length; i++){
                if(me.gljList[i].code === pasteObj.code){
                    return false;
                }
            }
        }
        pasteObj.basePrice = !isNaN(parseFloat(pasteObj.basePrice)) && (pasteObj.basePrice && typeof pasteObj.basePrice !== 'undefined') ? parseFloat(pasteObj.basePrice) : 0;
        pasteObj.gljClass = me.gljCurTypeId;
        return true;
    },
    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;
         }*/
        if (me.gljCurTypeId < 0 ) {
            args.cancel = true;
        }
    },
    onClipboardPasted: function(e, info) {
        var me = repositoryGljObj;
        var updateArr = [], addArr = [];
        var items = sheetCommonObj.analyzePasteData(me.setting, info);
        let beginRow = info.cellRange.row, endRow = info.cellRange.row + info.cellRange.rowCount - 1,
            maxRow = me.currentCache.length - 1, updateItems = [], addItems = [], updateBasePrcArr = [] , updateCount, resumeArr = [];
        if(endRow <= maxRow){
            //updateItems = items;
            for(let i = 0; i < items.length; i++){
                let updateObj = me.validUpdateObj(items[i], info.cellRange.row + i);
                if(updateObj && typeof updateObj.updateGlj !== 'undefined'){
                    updateArr.push(updateObj.updateGlj);
                    if(typeof updateObj.updateBasePrc !== 'undefined'){
                        updateBasePrcArr.push(updateObj.updateBasePrc);
                    }
                }
                else{
                    resumeArr.push(info.cellRange.row + i);
                }
            }
        }
        else if(beginRow <= maxRow && endRow > maxRow){
            updateCount = maxRow - beginRow + 1;
            for(let i = 0; i < updateCount; i++){
                let updateObj = me.validUpdateObj(items[i], info.cellRange.row + i);
                if(updateObj && typeof updateObj.updateGlj !== 'undefined'){
                    updateArr.push(updateObj.updateGlj);
                    if(typeof updateObj.updateBasePrc !== 'undefined'){
                        updateBasePrcArr.push(updateObj.updateBasePrc);
                    }
                }
                else{
                    resumeArr.push(info.cellRange.row + i);
                }
            }
            if(info.cellRange.colCount === me.setting.header.length){
                for(let i = updateCount ; i < items.length; i++){
                    if(me.isValidObj(items[i])){
                        addItems.push(items[i]);
                        addArr.push(items[i]);
                    }
                    else{
                        resumeArr.push(info.cellRange.row + i);
                    }
                }
            }
            else{
                for(let i = updateCount ; i < items.length; i++){
                    resumeArr.push(info.cellRange.row + i);
                }
            }
        }
        else{
            if(info.cellRange.colCount === me.setting.header.length){
                for(let i = 0; i < items.length; i++){
                    if(me.isValidObj(items[i])){
                        addArr.push(items[i]);
                    }
                    else{
                        resumeArr.push(info.cellRange.row + i);
                    }
                }
            }
            else{
                for(let i = 0; i < items.length; i++){
                    resumeArr.push(info.cellRange.row + i);
                }
            }
        }
        //repaint
        if(resumeArr.length > 0){
            info.sheet.suspendPaint();
            for(let i = 0; i < resumeArr.length ; i++){
                if(resumeArr[i] < me.currentCache.length){
                    for(let col = 0; col < me.setting.header.length; col++){
                        if(me.setting.header[col].dataCode === 'gljType'){
                            let gljType = me.currentCache[resumeArr[i]][me.setting.header[col].dataCode];
                            info.sheet.setValue(resumeArr[i], col, me.distTypeTree.distTypes["gljType" + gljType].data.fullName);
                        }
                        else{
                            info.sheet.setValue(resumeArr[i], col, me.currentCache[resumeArr[i]][me.setting.header[col].dataCode]);
                        }
                    }
                }
                else{
                    for(let col = 0; col < me.setting.header.length; col++){
                        info.sheet.setValue(resumeArr[i], col, '');
                    }
                }
            }
            info.sheet.resumePaint();
        }
        if (updateArr.length > 0 || addArr.length > 0) {
            me.mixUpdateRequest(updateArr, addArr, []);
        }
        if(updateBasePrcArr.length > 0){
            me.updateRationBasePrcRq(updateBasePrcArr);
        }
    },
    updateRationBasePrcRq: function (basePrcArr) {
        $.ajax({
            type: 'post',
            url: '/complementaryRation/api/updateRationBasePrc',
            data:{data: JSON.stringify({repId: pageOprObj.rationLibId, lastOpr: userAccount, basePrcArr: basePrcArr})},
            dataType: 'json',
            success: function (result) {
                if(result.error){
                    alert("计算定额基价失败");
                }
            }
        });
    },
    getRationGljIds: function (repId) {
        let me = repositoryGljObj;
        $.ajax({
            type: 'post',
            url: '/complementaryRation/api/getRationGljIds',
            data: {data: JSON.stringify({repId: repId})},
            dataType: 'json',
            success: function(result){
                if(!result.error){
                    me.rationGljIds = result.data;
                }
            }
        });
    },
    mixUpdateRequest: function(updateArr, addArr, removeIds) {
        var me = repositoryGljObj;
        $.ajax({
            type:"POST",
            url:"/complementaryRation/api/mixUpdateGljItems",
            data:{"repositoryId": me.currentRepositoryId, "lastOpr": userAccount, "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();
                    if(me.currentOprParent === 1){
                        me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]);
                    }
                    else{
                        me.currentCache = me.getCache();
                        //sheetCommonObj.unLockAllCells(me.workBook.getSheet(0));
                        sheetsOprObj.reLockSomeCodes(me.workBook.getSheet(0), 0, me.currentCache.length);
                        //sheetCommonObj.lockSomeCodes(me.workBook.getSheet(0), 0, me.currentCache.length);
                    }
                    me.showGljItems(me.gljList, me.gljCurTypeId);
                }
            },
            error:function(err){
                alert("保存失败");
            }
        })
    },
    getParentCache: function (nodes) {
        let me = repositoryGljObj, rst = [];
        for(let i = 0; i < me.gljList.length; i++){
            if(nodes.indexOf(me.gljList[i].gljClass) !== -1){
                rst.push(me.gljList[i]);
            }
        }
        rst.sort(function (a, b) {
            let rst = 0;
            if(a.code > b.code) rst = 1;
            else if(a.code < b.code)rst = -1;
            return rst;
        });
        return rst;
    },
    getCache: function() {
        var me = this, rst = [];
        for (var i = 0; i < me.gljList.length; i++) {
            if (me.gljList[i].gljClass == 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;
        if (me.parentNodeIds["_pNodeId_" + treeNode.ID]) {
            me.currentOprParent = 1;
            me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + treeNode.ID]);
           // sheetCommonObj.lockCodeCells(me.workBook.getSheet(0), me.currentCache.length);
            me.workBook.getSheet(0).setRowCount(me.currentCache.length);
        } else {
            me.currentOprParent = 0;
            me.currentCache = me.getCache();
            me.workBook.getSheet(0).setRowCount(me.currentCache.length);
            /*sheetCommonObj.unLockAllCells(me.workBook.getSheet(0));
            sheetCommonObj.reLockSomeCodes(me.workBook.getSheet(0), 0, me.currentCache.length);*/
        }
        me.showGljItems(me.gljList, gljTypeId);
        me.workBook.getSheet(0).setRowCount(me.currentCache.length);
    },
    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){
        let me = this;
        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:"/complementaryRation/api/deleteGljNodes",
            data:{"repId": pageOprObj.rationLibId, "lastOpr": userAccount, "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:"/complementaryRation/api/updateGljNodes",
                data:{"repId": pageOprObj.rationLibId, "lastOpr": userAccount, "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:"/complementaryRation/api/createNewGljTypeNode",
            data:{"lastOpr": userAccount, "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) {
        if(typeof treeNode.doing !== 'undefined' && treeNode.doing){
            return false;
        }
        hoverOpr();
        function hoverOpr(){
            //console.log(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(){
                treeNode.doing = true;
                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;
                        if(treeNode.items.length > 0){
                            treeNode.items[treeNode.items.length - 1].NextSiblingID = rst.data.ID;
                        }
                        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);
                        }
                        treeNode.doing = false;
                        hoverOpr();
                    }
                });
            });
        }
    },
    removeHoverDom: function(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    }

}
