/**
 * Created by Zhong on 2017/8/14.
 */
const locked = lockUtil.getLocked();
$(document).ready(function () {
    let moduleName = 'stdGLj';
    function refreshALlWorkBook() {
        if (gljClassTreeObj.workBook) {
            gljClassTreeObj.workBook.refresh();
        }
        if (repositoryGljObj.workBook) {
            repositoryGljObj.workBook.refresh();
        }
        if (gljComponentOprObj.workBook) {
            gljComponentOprObj.workBook.refresh();
        }
    }
    SlideResize.loadHorizonWidth(moduleName, [$('#slideResizeLeft'), $('#slideResizeRight')], [$('#leftContent'), $('#midContent'), $('#rightContent')], function () {
        refreshALlWorkBook();
    });
    //章节树与人材机表
    let leftElesObj = {};
    leftElesObj.module = moduleName;
    leftElesObj.resize = $('#slideResizeLeft');
    leftElesObj.parent = $('#dataRow');
    leftElesObj.left = $('#leftContent');
    leftElesObj.right = $('#midContent');
    SlideResize.horizontalSlide(leftElesObj, {min: 200, max: `$('#dataRow').width() - $('#rightContent').width() - 200`}, function () {
        refreshALlWorkBook();
    });
    //人材机表与人材机组成物表
    let rightElesObj = {};
    rightElesObj.module = moduleName;
    rightElesObj.resize = $('#slideResizeRight');
    rightElesObj.parent = $('#dataRow');
    rightElesObj.left = $('#midContent');
    rightElesObj.right = $('#rightContent');
    SlideResize.horizontalSlide(rightElesObj, {min: 200, max: `$('#dataRow').width() - $('#leftContent').width() - 200`}, function () {
        let resizeRate = SlideResize.resizeWidth * 100 / $('#midContent').width(),
            sheetRate = 100 - resizeRate;
        $('#slideResizeLeft').css('width', `${resizeRate}%`);
        $('#GLJListSheet').css('width', `${sheetRate}%`);
       refreshALlWorkBook();
    });
});


const digital = {
    basePrice: -2,
    consumeAmt: -3
};

let pageOprObj = {
    gljLibName : null,
    gljLibId: null,
    initPage : function(container, containerComponent, containerC) {
        let me = this, gljLibId = getQueryString("gljLibId");//获取定额库参数
        me.gljLibId = gljLibId;
        //生成人材机表格列头
        repositoryGljObj.setting.header = repositoryGljObj.initHeaders(priceProperties);
        //生成列映射
        sheetCommonObj.initColMapping(repositoryGljObj, repositoryGljObj.setting.header);
        //生成单价列下标数组
        repositoryGljObj.initPriceCols(priceProperties, repositoryGljObj.colMapping);
        repositoryGljObj.getGljLib(gljLibId, function () {
            repositoryGljObj.buildSheet(container);
            gljComponentOprObj.buildSheet(containerComponent);
            componentOprObj.buildSheet(containerC);
            //获得定额库中引用此工料机库中的，所有被定额所套的工料机的ID
            //repositoryGljObj.getRationGljIds(gljLibId);
            repositoryGljObj.getGljDistType(function () {
                repositoryGljObj.currentRepositoryId = parseInt(gljLibId);
                repositoryGljObj.getGljItems(gljLibId, function () {
                    gljClassTreeObj.getGljClassTree(gljLibId, function () {
                        const spreads = [gljClassTreeObj.workBook, repositoryGljObj.workBook, gljComponentOprObj.workBook];
                        const $range = $(document.body);
                        lockUtil.lockSpreadsAndTools(spreads, $range, locked);
                    });
                })
            });
        });
    }
};
let repositoryGljObj = {
    colMapping: null,
    treeObj : null,
    workBook: null,
    gljCurTypeId: -1,
    currentRepositoryId: -1,
    currentCache: null,
    parentNodeIds: {},
    gljList: [],
    materialType: {textArr: ['钢材', '钢筋', '木材', '水泥', '商品砼','商品砂浆'], comboItems: [{text: '钢材', value: 1}, {text: '钢筋', value: 2},{text: '木材', value: 3},//三材类型：钢材1、钢筋2、木材3、水泥4、商品砼5、商品砂浆6
         {text: '水泥', value: 4}, {text: '商品砼', value: 5},{text: '商品砂浆', value: 6}]},
    materialTypeIdx: {'1': '钢材', '2': '钢筋', '3': '木材', '4': '水泥', '5': '商品砼', '6': '商品砂浆'},
    machineModel: {textArr: ['特', '大', '中', '小'], comboItems: [{text: '特', value: 1}, {text: '大', value: 2},{text: '中', value: 3}, {text: '小', value: 4}]},
    machineModelIdx: {'1': '特', '2': '大', '3': '中', '4': '小'},
    taxRateTypes: [201, 205, 206, 302, 4, 5],
    distTypeTree: null,//add
    setting: {
        owner: "glj",
        header:[ // 默认情况下这个header会在initHeaders方法中被追加到全的头部中，可能也会被一些费用定额覆盖
            {headerName:"调整系数",headerWidth:60,dataCode:"adjCoe", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"三材类别",headerWidth:90,dataCode:"materialType", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"三材系数",headerWidth:60,dataCode:"materialCoe", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"机型",headerWidth:60,dataCode:"model", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"工料指标类别",headerWidth:90,dataCode:"materialIndexType", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"工料指标单位",headerWidth:90,dataCode:"materialIndexUnit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单位转换系数",headerWidth:90,dataCode:"materialIndexCoe", dataType: "Number", hAlign: "center", vAlign: "center"}
        ],
        view:{
            comboBox:[
                {row:-1,col:3,rowCount:-1,colCount:1}
            ],
            lockedCells:[
            ]
        }
    },
    //根据费用定额的单价属性获取人材机的单价属性
    getPriceProperty: function (priceProperties) {
        let priceProperty = {};
        for(let priceProp of priceProperties){
            priceProperty[priceProp.price.dataCode] = 0;
        }
        return priceProperty;
    },
    //根据单价字段获取消耗量字段
    getConsumeAmtField: function (consumeAmtProperties, priceField) {
        if(!consumeAmtProperties || consumeAmtProperties.length === 0){
            return 'consumeAmt';
        }
        for(let consumeAmtProp of consumeAmtProperties){
            if(consumeAmtProp.consumeAmt.refPrice === priceField){
                return consumeAmtProp.consumeAmt.dataCode;
            }
        }
        return 'consumeAmt';
    },
    //初始单价相关的列（单价列、单价属性列）
    initPriceCols: function (priceProperties, colMapping) {
        let priceCols = [],
            pricePropertyCols = [];
        if(!priceProperties || priceProperties.length === 0){
            priceCols.push(colMapping.fieldToCol['basePrice']);
        }
        for(let priceProp of priceProperties){
            pricePropertyCols.push(colMapping.fieldToCol[priceProp.price.dataCode]);
            priceCols.push(colMapping.fieldToCol[priceProp.price.dataCode]);
        }
        this.priceCols = priceCols;
        this.pricePropertyCols = pricePropertyCols;
    },
    getPriceFields: function () {
        let rst = [];
        for(let priceCol of this.priceCols){
            rst.push(this.colMapping.colToField[priceCol]);
        }
        return rst;
    },
    //获取更新定额价的人材机价格（人材机只有一个单价取basePrice, 人材机有多个单价，取第一个单价）
    getRationGljPrice: function (glj) {
        if(glj.priceProperty){
            let keys = Object.keys(glj.priceProperty);
            if(keys.length > 0){
                return glj.priceProperty[keys[0]];
            }
        }
        return glj.basePrice;
    },
    //生成列头（多单价）
    initHeaders: function (priceProperties) {
        let headers = [
            {headerName:"编码",headerWidth:80,dataCode:"code", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"名称",headerWidth:160,dataCode:"name", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"规格型号",headerWidth:80,dataCode:"specs", dataType: "String", formatter: "@", hAlign: "left", vAlign: "center"},
            {headerName:"单位",headerWidth:60,dataCode:"unit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"类型",headerWidth:90,dataCode:"gljType", dataType: "String", hAlign: "center", vAlign: "center"},
        ];
        //生成单价列
        if(!priceProperties || priceProperties.length === 0){
            headers.push({headerName:"定额价",headerWidth:80,dataCode:"basePrice", dataType: "Number", formatter: "0.00", hAlign: "right", vAlign: "center"});
        }
        else {
            for(let priceProp of priceProperties){
                let colData = {
                    headerName: priceProp.price.dataName,
                    headerWidth: 100,
                    dataCode: priceProp.price.dataCode,
                    dataType: 'Number',
                    formatter: '0.00',
                    hAlign: 'right',
                    vAlign: 'center'
                };
                headers.push(colData);
            }
        }
        /* let tailHeaders = [
            {headerName:"调整系数",headerWidth:60,dataCode:"adjCoe", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"三材类别",headerWidth:90,dataCode:"materialType", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"三材系数",headerWidth:60,dataCode:"materialCoe", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"机型",headerWidth:60,dataCode:"model", dataType: "Number", hAlign: "center", vAlign: "center"},
            {headerName:"工料指标类别",headerWidth:90,dataCode:"materialIndexType", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"工料指标单位",headerWidth:90,dataCode:"materialIndexUnit", dataType: "String", hAlign: "center", vAlign: "center"},
            {headerName:"单位转换系数",headerWidth:90,dataCode:"materialIndexCoe", dataType: "Number", hAlign: "center", vAlign: "center"}
        ]; */
        headers = headers.concat(this.setting.header);
        return headers;
    },
    //工料机单价赋初始值（没有单价属性，则单价字段为basePrice，否则单价字段为单价属性对象中的属性）
    initPrice: function (glj) {
        if(!priceProperties || priceProperties.length === 0){
            glj.basePrice = glj.basePrice && !isNaN(parseFloat(glj.basePrice)) ? scMathUtil.roundTo(parseFloat(glj.basePrice), -2) : 0;
        }
        else {
            if(!glj.priceProperty){
                glj.priceProperty = {};
            }
            for(let priceProp of priceProperties){
                let gljPrice = glj['priceProperty'][priceProp.price.dataCode];
                gljPrice = gljPrice && !isNaN(parseFloat(gljPrice)) ? scMathUtil.roundTo(parseFloat(gljPrice), -2) : 0;
            }
        }
    },
    //人材机单价是否变化
    isGljPriceChange: function (glj, newPrice) {
        //多单价，与人材机单价属性比较
        if(typeof newPrice === 'object'){
            return !_.isEqual(glj.priceProperty, newPrice);
        }
        return !_.isEqual(glj.basePrice, newPrice);
    },
    //粘贴数据含有单价
    pasteIncludesPrice: function (pasteObj) {
        let me = repositoryGljObj;
        for(let priceCol of me.priceCols){
            let priceField = me.colMapping.colToField[priceCol];
            if(typeof pasteObj[priceField] !== 'undefined'){
                return true;
            }
        }
        return false;
    },
    //获取人材机价格
    getPrice: function (glj, col) {
        let me = repositoryGljObj;
        if(!priceProperties || priceProperties.length === 0){
            return glj.basePrice;
        }
        return glj.priceProperty[me.colMapping.colToField[col]];
    },
    //工料机价格是否相同
    priceIsEqual: function (gljA, gljB) {
        if(!priceProperties || priceProperties.length === 0){
            return gljA.basePrice == gljB.basePrice;
        }
        return _.isEqual(gljA.priceProperty, gljB.priceProperty);
    },
    setGljPrice: function (glj, newPrice, col) {
        if(!priceProperties || priceProperties.length === 0){
            glj.basePrice = newPrice;
        }
        else {
            glj.priceProperty[this.colMapping.colToField[col]] = newPrice;
        }
    },
    setUnitCombo: function (sheet, headers) {
        let me = this;
        sheet.suspendPaint();
        sheet.suspendEvent();
        let combo = sheetCommonObj.getDynamicCombo();
        combo.items(rationAndGljUnits).itemHeight(10).editable(true);
        let unitCol = me.colMapping.fieldToCol['unit'];
        if(unitCol){
            sheet.getRange(-1, unitCol, -1, 1).cellType(combo);
        }
        sheet.resumePaint();
        sheet.resumeEvent();
    },
    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(allowGljType.includes(distTypeObj.data.ID)){
                distTypeTree.comboDatas.push({text: distTypeObj.data.fullName, value: distTypeObj.data.ID});
            }
        });
        return distTypeTree;
    },
    getGljDistType: function (callback) {
        let me = this;
        $.ajax({
            type: 'post',
            url: "api/getGljDistType",
            dataType: 'json',
            success: function (result) {
                if(!result.error && callback){
                    me.distTypeTree = me.getComboData(result.data);
                    console.log(me.distTypeTree);
                    callback();
                }
            }
        })
    },
    getGljLib: function (libId, callback) {
        let me = repositoryGljObj;
        $.ajax({
            type: 'post',
            url: 'api/getGljLib',
            data: {libId: libId},
            dataType: 'json',
            success: function (result) {
                if(!result.error){
                    if(result.data.length > 0){
                        me.rationLibs = result.data[0].rationLibs;
                        $(".navbar-text").append(
                            "<a href='/stdGljRepository/main'>人材机库</a><i class='fa fa-angle-right fa-fw'></i>"+result.data[0].dispName
                        );
                        pageOprObj.gljLibName = result.data[0].dispName;
                    }
                    callback();
                }
            }
        })
    },
    getGljTree: function(gljLibId, callback) {
        let me = this;
        $.ajax({
            type:"POST",
            url:"api/getGljTree",
            data:{"gljLibId": gljLibId},
            dataType:"json",
            cache:false,
            timeout:20000,
            success:function(result,textStatus,status){
                if(status.status == 200) {
                    zTreeHelper.createTree(result.data, gljSetting, "repositoryTree", me);
                    zTreeHelper.createTree(result.data, componentSetting, "componentTree", componentOprObj);
                    if (result.data && result.data.length > 0) {
                        me.gljCurTypeId = result.data[0].ID;
                    } else {
                        //重新创建库？
                        gljTypeTreeOprObj.addRootNode();
                    }
                    callback();
                }
            },
            error:function(err){
                alert(err.responseJSON.error);
            }
        })
    },
    getGljItems: function(repId, callback) {
        let me = this;
        $.ajax({
            type:"POST",
            url:"api/getGljItems",
            data:{"repositoryId": repId},
            dataType:"json",
            cache:false,
            timeout:240000,
            success:function(result){
                if(!result.error) {
                    me.gljList = result.data;
                    // test
                    /*const temp = [];
                    const map = {};
                    me.gljList.forEach(glj => {
                        if (!map[glj.code]) {
                            map[glj.code] = 1;
                        } else {
                            temp.push(glj);
                        }
                    });
                    temp.sort((a, b) => b.ID - a.ID);
                    console.log(temp);*/
                    // test
                    me.workBook.getSheet(0).setRowCount(result.data.length);
                    me.sortGlj();
                    me.currentGlj = me.gljList.length > 0 ? me.gljList[0] : null;//初始
                    if(callback){
                        callback();
                    }
                }
            },
            error:function(err){
                alert(err);
            }
        })
    },
    showGljItems: function(data, type) {
        let me = repositoryGljObj;
        if (me.workBook) {
            let cacheSection = data;
            me.sortGljDeep(cacheSection);
            sheetCommonObj.cleanData(me.workBook.getSheet(0), me.setting, -1);
            sheetsOprObj.showData(me, me.workBook.getSheet(0), me.setting, cacheSection, me.distTypeTree, me.materialTypeIdx, me.machineModelIdx);
            let gljTypeCol = me.colMapping.fieldToCol['gljType'],
                materialTypeCol = me.colMapping.fieldToCol['materialType'],
                modelCol = me.colMapping.fieldToCol['model'];
            sheetCommonObj.setDynamicCombo(me.workBook.getActiveSheet(), 0, gljTypeCol, me.workBook.getActiveSheet().getRowCount(), me.distTypeTree.comboDatas, 10, 'text');
            sheetCommonObj.setDynamicCombo(me.workBook.getActiveSheet(), 0, materialTypeCol, me.workBook.getActiveSheet().getRowCount(), me.materialType.comboItems, false, 'text');
            sheetCommonObj.setDynamicCombo(me.workBook.getActiveSheet(), 0, modelCol, me.workBook.getActiveSheet().getRowCount(), me.machineModel.comboItems, false, 'text');
            cacheSection = null;
            let selRow =  me.workBook.getActiveSheet().getSelections()[0].row;
            me.initSel(selRow);
        }
    },
    bindEnterKey: function () {
        let me = this;
        let sheet = me.workBook.getActiveSheet();
        me.workBook.commandManager().register("myEnter", function(){
            let orgRow = sheet.getActiveRowIndex();
            let orgCol = sheet.getActiveColumnIndex();
            if(sheet.isEditing()){
                sheet.endEdit();
            }
            let codeCol = me.colMapping.fieldToCol['code'];
            let code = sheet.getValue(orgRow, codeCol);
            let newRow, newCol;
            if(!me.currentCache[orgRow] && code !== undefined && code !== null && orgCol !== me.setting.header.length - 1){
                newRow = orgRow;
                newCol = orgCol + 1;
                sheet.setActiveCell(newRow, newCol);
            }
            else{
                newRow = orgRow + 1;
                newCol = me.currentCache[orgRow + 1] ? orgCol : 0;
                sheet.setActiveCell(newRow, newCol);
            }
            //触发事件
            me.onLeaveCell({type: 'LeaveCell'}, {sheet: sheet, sheetName: sheet.name(), cancel: false, row: orgRow, col: orgCol});
            me.onEnterCell({type: 'EnterCell'}, {sheet: sheet, sheetName: sheet.name(), cancel: false, row: newRow, col: newCol});
            let newSels = [{row: newRow, rowCount: 1, col: newCol, colCount: 1}];
            let oldSels = [{row: orgRow, rowCount: 1, col: orgRow, colCount: 1}];
            me.onSelectionChanged({type: 'SelectionChanged'}, {sheet: sheet, sheetName: sheet.name(), newSelections: newSels, oldSelections: oldSels});
        });
        me.workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.enter, false, false, false, false);
        me.workBook.commandManager().setShortcutKey("myEnter", GC.Spread.Commands.Key.enter, false, false, false, false);
    },
    buildSheet: function(container) {
        let me = repositoryGljObj;
        me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30, me);
        sheetCommonObj.bindEscKey(me.workBook, [{sheet: me.workBook.getSheet(0), editStarting: me.onCellEditStart, editEnded: me.onCellEditEnd}]);
        me.bindEnterKey();
        me.repositoryGljDelOpr();
        me.onContextmenuOpr();
        me.setUnitCombo(me.workBook.getActiveSheet(), me.setting.header);
        me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
        if(priceProperties && priceProperties.length > 0){
            me.workBook.getSheet(0).frozenColumnCount(5);
        }
        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.EnterCell, me.onEnterCell);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.LeaveCell, me.onLeaveCell);
        me.workBook.getSheet(0).bind(GC.Spread.Sheets.Events.SelectionChanged, me.onSelectionChanged);
    },

    isDef: function (v) {
        return v !== undefined && v !== null;
    },

    //成为了组成物,暂时只需要判断主材的
    isComponent: function (gljId, gljList) {
        for(let i = 0, len = gljList.length; i < len; i++){
            let gljComponent = gljList[i].component;
            if(gljList[i].gljType === 4 && this.isDef(gljComponent) && gljComponent.length > 0){
                for(let j = 0, jLen = gljComponent.length; j < jLen; j++){
                    if(gljComponent[j].ID === gljId){
                        return true;
                    }
                }
            }
        }
        return false;
    },

    getCurrentComponent: function (gljComponent, sort = false) {
        let me = repositoryGljObj,
            rst = [],
            IDCodeMapping = {};
        for(let i = 0; i < gljComponent.length; i++){
            let obj = {};
            for(let j = 0; j < me.gljList.length; j++){
                let specs = me.gljList[j].specs ? ' ' + me.gljList[j].specs : '';
                if(gljComponent[i].ID == me.gljList[j].ID){
                    obj.ID = me.gljList[j].ID;
                    obj.code = me.gljList[j].code;
                    obj.name = me.gljList[j].name + specs;
                    obj.unit = me.gljList[j].unit;
                    obj.basePrice = me.gljList[j].basePrice;
                    obj.priceProperty = me.gljList[j].priceProperty ? me.gljList[j].priceProperty : {};
                    obj.consumeAmt = gljComponent[i].consumeAmt;
                    obj.consumeAmtProperty = gljComponent[i].consumeAmtProperty ? gljComponent[i].consumeAmtProperty : {};
                    rst.push(obj);
                    IDCodeMapping[obj.ID] = obj.code;
                }
            }
        }
        if(sort){
            rst.sort(function (a, b) {
                let r = 0;
                if(a.code > b.code) r = 1;
                else if(a.code < b.code) r = -1;
                return r;
            });
            gljComponent.sort(function (a, b) {
               let aV = IDCodeMapping[a.ID],
                   bV = IDCodeMapping[b.ID];
               if (aV > bV) {
                   return 1;
               } else if (aV < bV) {
                   return -1;
               }
               return 0;
            });
        }
        return rst;
    },
    //获得引用了组成物id为componentId的工料机，和重新变化组成物数组、重新计算单价
    getUpdateGljs: function (rObj, isDelete) {
        let me = repositoryGljObj, that = gljComponentOprObj,
            rst = {updateArr: [], updateBasePrcArr: []};
        //改变单价，以便reCalGljBasePrc方法可行
        if(!isDelete){
            for(let i = 0; i < me.gljList.length; i++){
                if(me.gljList[i].ID === rObj.ID){
                    me.gljList[i].basePrice = rObj.basePrice;
                    me.gljList[i].priceProperty = rObj.priceProperty ? rObj.priceProperty : {};
                    break;
                }
            }
        }
        for(let i = 0; i < me.gljList.length; i++){
            let thisComponent = me.gljList[i].component, isChange = false;
            for(let j = 0; j < thisComponent.length; j++){
                if(thisComponent[j].ID === rObj.ID){
                    //删除
                    isChange = true;
                    if(isDelete){
                        thisComponent.splice(j--, 1);
                    }
                    else {
                        break;
                    }
                }
            }
            if(isChange){//引用了此组成物
                rst.updateArr.push(me.gljList[i]);
            }
        }
        return rst;
    },
    reshowGljBasePrc: function (glj) {
        let me = repositoryGljObj;
        let cacheSection = me.currentCache;
        let sheet = me.workBook.getActiveSheet();
        let row = _.findIndex(cacheSection, {ID: glj.ID});
        sheet.suspendEvent();
        sheet.suspendPaint();
        for(let priceCol of me.priceCols){
            sheet.setValue(row, priceCol, glj[me.colMapping.colToField[priceCol]]);
        }
        sheet.resumeEvent();
        sheet.resumePaint();
    },
    reSetGljBasePrc: function (gljs) {
        let me = repositoryGljObj;
        let cacheSection = me.currentCache;
        let sheet = me.workBook.getSheet(0);
        let basePriceCol = me.colMapping.fieldToCol['basePrice'];
        sheet.suspendPaint();
        sheet.suspendEvent();
        for(let i = 0; i < cacheSection.length; i++){
            for(let glj of gljs){
                if(glj.ID === cacheSection[i].ID){
                    for(let priceCol of me.priceCols){
                        sheet.setValue(i, priceCol, glj[me.colMapping.colToField[priceCol]]);
                    }
                    //sheet.setValue(i, basePriceCol, glj.basePrice);
                }
            }
        }
        sheet.resumePaint();
        sheet.resumeEvent();

    },
    initSel: function (row) {
        let me = repositoryGljObj, that = gljComponentOprObj;
        sheetCommonObj.cleanData(that.workBook.getSheet(0), that.setting, -1);
        //sheetCommonObj.cleanSheet(that.workBook.getSheet(0), that.setting, -1);
        me.workBook.focus(true);
        me.currentComponent = [];
        that.workBook.getSheet(0).setRowCount(10);
        if(row < me.currentCache.length){
            //标记当前工料机
            me.currentGlj = me.currentCache[row];
            if(allowComponent.includes(me.currentCache[row].gljType)){
                //展示数据
                if(me.currentGlj.component.length > 0){
                    me.currentComponent = me.getCurrentComponent(me.currentGlj.component, true);
                    if(me.currentComponent.length > 0){
                        sheetsOprObj.showData(that, that.workBook.getSheet(0), that.setting, me.currentComponent);
                    }
                }
            }
        }
        else{
            me.currentGlj = null;
        }
    },
    onSelectionChanged: function (sender, info) {
        let me = repositoryGljObj, that = gljComponentOprObj;
        //混凝土202、砂浆203、配合比204、机械3
        if(info.oldSelections.length === 0 && info.newSelections.length > 0 || info.oldSelections[0].row !== info.newSelections[0].row){
            let row = info.newSelections[0].row;
            me.initSel(row);
        }
    },
    onLeaveCell: function (sender, args) {
        let me = repositoryGljObj;
        me.lastCell = {row: args.row, col: args.col};
    },
    onEnterCell: function (sender, args) {
        let me = repositoryGljObj;
        let thisDataCode = me.setting.header[args.col].dataCode,
            lastDataCode = me.setting.header[me.lastCell.col].dataCode;
        if(thisDataCode === 'unit'|| lastDataCode === 'unit' || thisDataCode === 'gljType' || lastDataCode === 'gljType'
            || thisDataCode === 'materialType' || lastDataCode === 'materialType' || thisDataCode === 'model' || lastDataCode === 'model'){
            let rects = [];
            rects.push(args.sheet.getCellRect(args.row, args.col));
            if(me.lastCell){
                rects.push(args.sheet.getCellRect(me.lastCell.row, me.lastCell.col));
            }
            for(let rect of rects){
                args.sheet.repaint(rect);
            }
            //args.sheet.repaint();
        }
        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 focusToCol;
                function getFocusToCol (me){
                    if(!me.addGljObj.code){
                        $('#alertGljTxt').text('编号不能为空，继续增加人材机?');
                        return me.colMapping.fieldToCol['code'];
                    }
                    else if(!me.addGljObj.name){
                        $('#alertGljTxt').text('名称不能为空，继续增加人材机?');
                        return me.colMapping.fieldToCol['name'];
                    }
                    else if(!me.addGljObj.gljType){
                        $('#alertGljTxt').text('类型不能为空，继续增加人材机?');
                        return me.colMapping.fieldToCol['gljType'];
                    }
                    else {
                        return -1;
                    }
                }
                focusToCol = getFocusToCol(me);
                if(focusToCol !== -1) {
                    $('#gljAlertBtn').click();
                    $('#aleConfBtn').unbind('click');
                    $('#aleConfBtn').bind('click', function () {
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, focusToCol);
                        me.workBook.focus(true);
                    });
                    $('#gljAleClose').click(function () {
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, focusToCol);
                        me.workBook.focus(true);
                    });
                    $('#aleCanceBtn').unbind('click');
                    $('#aleCanceBtn').bind('click', function () {
                        me.addGljObj = null;
                        args.sheet.suspendEvent();
                        args.sheet.suspendPaint();
                        for(let col=0; col<me.setting.header.length; col++){
                            if(col === 0){
                                me.workBook.getSheet(0).getCell(me.editingRowIdx, 0).formatter("@");
                            }
                            me.workBook.getSheet(0).getCell(me.editingRowIdx, col).value('');
                        }
                        me.workBook.getSheet(0).setActiveCell(me.editingRowIdx, 0);
                        me.workBook.focus(true);
                        args.sheet.resumeEvent();
                        args.sheet.resumePaint();
                    });
                }
            }
        }
    },
    onCellEditStart: function(sender, args) {
        let me = repositoryGljObj;
        me.orgCode = me.workBook.getSheet(0).getValue(args.row, me.colMapping.fieldToCol['code']);
        let rObj = sheetsOprObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row, me);
        if(me.prevent){
            args.cancel = true;
            return;
        }
        me.currentEditingGlj = rObj;
        if(args.row < me.currentCache.length){
            let dataCode = me.setting.header[args.col].dataCode;
            me.currentGlj = me.currentCache[args.row];
            if(dataCode === 'code'
                || (dataCode === 'taxRate' && !me.taxRateTypes.includes(me.currentGlj.gljType))
                || (dataCode === 'adjCoe' && me.currentGlj.gljType !== 1 && me.currentGlj.gljType !== 303)
                || (dataCode === 'materialCoe' && !me.currentGlj.materialType)
                || (dataCode === 'model' && me.currentGlj.gljType !== 301)){
                args.cancel = true;
            }
            else {
                rObj.ID = me.currentGlj.ID;
                rObj.gljClass = me.currentGlj.gljClass;
            }
        }
        else {
            me.currentGlj = null;
        }
    },
    dataChanged: function (objA, objB, col) {
        let me = repositoryGljObj;
        if(me.priceCols.includes(col)){
            if(!priceProperties || priceProperties.length === 0){
                return objA.basePrice !== objB.basePrice;
            }
            else {
                return objA.priceProperty[me.colMapping.colToField[col]] !== objB.priceProperty[me.colMapping.colToField[col]]
            }
        }
        return objA[me.colMapping.colToField[col]] !== objB[[me.colMapping.colToField[col]]];
    },
    onCellEditEnd: function(sender, args) {
        let me = repositoryGljObj,
            that = gljComponentOprObj,
            updateArr = [],
            addArr = [],
            updateBasePrcArr = [];
        // 输入编号、名称、规格时，如果输入回车符或粘贴回车符，提交时应转换为空格。
        let deESCFields = ['code', 'name', 'specs'];
        if(deESCFields.includes(me.setting.header[args.col]['dataCode'])){
            args.editingText = me.isDef(args.editingText) ? args.editingText.toString().replace(/[\r\n]/g, ' ') : '';
            args.sheet.setValue(args.row, args.col, args.editingText);
        }
        let rObj = sheetsOprObj.combineRowData(me.workBook.getSheet(0), me.setting, args.row, me);
        me.editingRowIdx = args.row;
        //rObj.basePrice = rObj.basePrice ? rObj.basePrice : 0;
        me.initPrice(rObj);
        //更新
        if (me.currentEditingGlj["ID"] && me.currentGlj) {
            rObj["ID"] = me.currentEditingGlj["ID"];
            rObj.gljClass = me.currentEditingGlj.gljClass;
            if(me.dataChanged(me.currentEditingGlj, rObj, args.col)){
                if(rObj.code && rObj.name && rObj.gljType &&
                    rObj.code.toString().trim().length !== 0 && rObj.name.toString().trim().length !== 0 && rObj.gljType.toString().trim().length !== 0){
                    if(rObj.gljType !== me.currentEditingGlj.gljType){//修改了工料机类型
                        if(!$('#typeAlert').is(':visible')){
                            $('#typeAlert').modal('show');
                        }
                        $('#typeConfirm').unbind('click');
                        $('#typeConfirm').bind('click', function () {
                            $('#typeAlert').modal('hide');
                            if(me.currentGlj){
                                me.currentGlj.component = [];
                            }
                            /*if(me.allowComponent.indexOf(rObj.gljType) !== -1){//更改成可添加组成物的类型，则将定额价设成零
                             rObj.basePrice = 0;
                             }*/
                            // 工料机类型不为普通材料、商品混凝土、商品砂浆、机械组成物、主材、设备时，清空税率
                            if (!me.taxRateTypes.includes(rObj.gljType)) {
                                rObj.taxRate = null;
                            }
                            //调整系数,工料机类型为人工和机上人工时，可输入整数
                            if((me.currentEditingGlj.gljType === 1 || me.currentEditingGlj.gljType === 303) && !(rObj.gljType === 1 || rObj.gljType === 303)){
                                rObj.adjCoe = null;
                            }
                            //工料机类型不为机械台班时，清空机型
                            if(me.currentEditingGlj.gljType === 301 && rObj.gljType !== 301 && me.currentEditingGlj.model){
                                rObj.model = null;
                            }
                            if(componentType.includes(me.currentEditingGlj.gljType)&&
                                !(machineComponent.includes(me.currentEditingGlj.gljType) && machineComponent.includes(rObj.gljType)) &&
                                !(materialComponent.includes(me.currentEditingGlj.gljType) && materialComponent.includes(rObj.gljType))){//修改了原本是组成物的工料机
                                //寻找所有引用了此组成物的工料机,并从组成物中删去此工料机,并重算单价
                                let updateGljs = me.getUpdateGljs(rObj, true);
                                if(updateGljs.updateArr.length > 0 || updateGljs.updateBasePrcArr.length > 0){
                                    for(let i = 0; i < updateGljs.updateArr.length; i++){
                                        updateArr.push(updateGljs.updateArr[i]);
                                    }
                                    for(let i = 0; i < updateGljs.updateBasePrcArr.length; i++){
                                        updateArr.push(updateGljs.updateBasePrcArr[i]);
                                    }
                                }
                            }
                            sheetCommonObj.cleanData(that.workBook.getSheet(0), that.setting, 5);
                            rObj.component = me.currentGlj.component;
                            updateArr.push(rObj);
                            me.mixUpdateRequest(updateArr, [], []);
                        });
                        $('.typeClose').unbind('click');
                        $('.typeClose').bind('click', function () {
                            args.sheet.setValue(args.row, args.col, _.find(me.distTypeTree.comboDatas, {value: me.currentGlj.gljType}).text);
                        });
                        return;
                    }
                    else if (rObj.taxRate !== me.currentEditingGlj.taxRate) {
                        if (isNaN(rObj.taxRate)) {
                            args.sheet.setValue(args.row, args.col, me.currentEditingGlj.taxRate || '');
                            alert('税率只能输入数值！');
                            return;
                        }
                        rObj.taxRate = scMathUtil.roundTo(parseFloat(rObj.taxRate), -2);
                    }
                    else if(rObj.adjCoe !== me.currentEditingGlj.adjCoe){//修改调整系数，整数控制
                        if(isNaN(rObj.adjCoe) || rObj.adjCoe % 1 !== 0){
                            args.sheet.setValue(args.row, args.col, me.currentEditingGlj.adjCoe ? me.currentEditingGlj.adjCoe : '');
                            alert('调整系数只能输入整数！');
                            return;
                        }

                    }
                    else if(rObj.materialCoe !== me.currentEditingGlj.materialCoe){
                        if(isNaN(rObj.materialCoe)){
                            args.sheet.setValue(args.row, args.col, me.currentEditingGlj.materialCoe ? me.currentEditingGlj.materialCoe : '');
                            alert('三材系数只能输入数值！');
                            return;
                        }
                        rObj.materialCoe = scMathUtil.roundTo(parseFloat(rObj.materialCoe), -5);
                    }
                    else if(!me.priceIsEqual(rObj, me.currentEditingGlj)){//修改了单价,可修改单价的必为可成为组成物的
                        let rObjPrice = me.getPrice(rObj, args.col),
                            editingGljPrice = me.getPrice(me.currentEditingGlj, args.col);
                        //寻找所有引用了此组成物的工料机,并从组成物中删去此工料机,并重算单价
                        if(isNaN(parseFloat(rObjPrice))){
                            alert('单价只能输入数值！');
                            args.sheet.setValue(args.row, args.col, editingGljPrice ? editingGljPrice : 0);
                            return;
                        }
                        me.setGljPrice(rObj, scMathUtil.roundTo(parseFloat(rObjPrice), -2), args.col);
                        let updateGljs = me.getUpdateGljs(rObj);
                        if(updateGljs.updateArr.length > 0 || updateGljs.updateBasePrcArr.length > 0){
                            for(let i = 0; i < updateGljs.updateArr.length; i++){
                                updateArr.push(updateGljs.updateArr[i]);
                            }
                            for(let i = 0; i < updateGljs.updateBasePrcArr.length; i++){
                                updateArr.push(updateGljs.updateBasePrcArr[i]);
                            }
                        }
                    }
                    rObj.component = me.currentGlj.component;
                    updateArr.push(rObj);
                }
                else{
                    if(me.setting.header[args.col].dataCode === 'gljType'){
                        let distTypeVal =  me.distTypeTree.distTypes[me.distTypeTree.prefix + me.currentEditingGlj[me.setting.header[args.col].dataCode]].data.fullName;
                        args.sheet.setValue(args.row, args.col, distTypeVal);
                    }
                    else{
                        args.sheet.setValue(args.row, args.col, me.currentEditingGlj[me.setting.header[args.col].dataCode]);
                    }
                }
            }
            if(!me.priceIsEqual(rObj, me.currentEditingGlj)){
                //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: me.getRationGljPrice(rObj)};
                if(gljBasePrcObj.gljType !== -1){
                    updateBasePrcArr.push(gljBasePrcObj);
                    if(me.rationLibs.length > 0){//重算定额单价
                        me.updateRationBasePrcRq(updateBasePrcArr);
                    }
                }
            }
        }
        //新增
        else {
            if(typeof rObj.code !== 'undefined'){
                me.addGljObj = rObj;
                let isCanSav = true;
                if(!rObj.code || !rObj.name || !rObj.gljType){
                    isCanSav = false;
                }
                if(isCanSav){
                    me.addGljObj = null;
                    rObj.component = [];
                    //rObj.basePrice = !isNaN(parseFloat(rObj.basePrice)) && (rObj.basePrice && typeof rObj.basePrice !== 'undefined') ? scMathUtil.roundTo(parseFloat(rObj.basePrice), -2) : 0;
                    me.initPrice(rObj);
                    addArr.push(rObj);
                }
            }
        }
        if(!me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]){
            rObj.gljClass = me.gljCurTypeId;
        }
        if(updateArr.length >0 || addArr.length >0){
            me.currentEditingGlj = null;
            me.mixUpdateRequest(updateArr, addArr, []);
        }
    },
    delGljs: function (sels) {
        let me = repositoryGljObj;
        let sheet = me.workBook.getSheet(0),
            updateArr = [], removeArr = [],
            removeIDs = [],
            removeNames = [],
            updateBasePrcArr = [],//删除基价单位后重新计算
            canUpdate = false,
            cacheSection = me.currentCache,
            updateBackups = [];
        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){
                            removeArr.push(cacheSection[sels[i].row + j]);
                            removeIDs.push(cacheSection[sels[i].row + j].ID);
                            removeNames.push(cacheSection[sels[i].row + j].name);
                            //删除后重新计算引用了此工料机的定额单价
                            updateBasePrcArr.push({gljId: cacheSection[sels[i].row + j].ID, gljType: cacheSection[sels[i].row + j].gljType, basePrice: 0, delete: 1});
                        }
                    }
                }
                else{
                    let maxCol = sels[i].col + sels[i].colCount - 1;
                    let cantNullDataCode = ['code', 'name', 'gljType'];
                    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++){
                                let dataCode = me.setting.header[col].dataCode;
                                if(cantNullDataCode.includes(dataCode)){
                                    $('#alertText').text(me.setting.header[col].headerName + "不可为空！");
                                    $('#codeAlert').modal('show');
                                    return false;
                                }
                                else {
                                    canUpdate = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if(canUpdate){
                //删除警告
                let upAlertText = '确认删除选中字段？';
                $('#alertGljTxt').text(upAlertText);
                $('#gljAlert').modal('show');
                $('#aleConfBtn').unbind('click');
                //确认
                $('#aleConfBtn').bind('click', function () {
                    for(let i = 0; i < sels.length; i++) {
                        let maxCol = sels[i].col + sels[i].colCount - 1;
                        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++) {
                                    let dataCode = me.setting.header[col].dataCode;
                                    if (me.priceCols.includes(col)) {
                                        me.setGljPrice(updateObj, 0, col);
                                        updateBasePrcArr.push({
                                            gljId: updateObj.ID,
                                            gljType: updateObj.gljType,
                                            basePrice: 0
                                        });
                                    }
                                    else {
                                        if (dataCode === 'materialType') {
                                            updateObj['materialCoe'] = null;
                                        }
                                        updateObj[dataCode] = '';
                                    }
                                }
                                updateArr.push(updateObj);
                            }
                        }
                    }
                    me.mixUpdateRequest(updateArr, [], []);
                    if(updateBasePrcArr.length > 0 && me.rationLibs.length > 0){
                        me.updateRationBasePrcRq(updateBasePrcArr);
                    }
                });

            }
            if(removeArr.length > 0){
                $.bootstrapLoading.start();
                CommonAjax.post('/stdGljRepository/api/isUsed', {gljIds: removeIDs}, function (rstData) {
                    $.bootstrapLoading.end();
                    //存在被引用的人材机（标准/补充定额库）
                    if(rstData.isUsed){
                        $('#gljAlert').find('.modal-body h5').text('已有定额引用了当前人材机，不可删除。');
                        $('#gljAlert').modal('show');
                        $('#aleConfBtn').unbind('click');
                        $('#aleConfBtn').bind('click', function () {
                            $('#gljAlert').modal('hide');
                            me.workBook.focus(true)
                        });
                    }
                    else {
                        $('#gljAlert').find('.modal-body h5').text(`确定要删除人材机 “${removeNames.join('，')}” 吗？ `);
                        setTimeout(function () {
                            $('#gljAlert').modal('show');
                        }, 200);
                        //确认
                        $('#aleConfBtn').unbind('click');
                        $('#aleConfBtn').bind('click', function () {
                            for(let removeD of removeArr){
                                let updateGljs = me.getUpdateGljs(removeD, true);
                                if(updateGljs.updateArr.length > 0){
                                    for(let i = 0; i < updateGljs.updateArr.length; i++){
                                        updateArr.push(updateGljs.updateArr[i]);
                                    }
                                }
                            }
                            me.mixUpdateRequest(updateArr, [], removeIDs);
                           /* if(updateBasePrcArr.length > 0 && me.rationLibs.length > 0){
                                me.updateRationBasePrcRq(updateBasePrcArr);
                                me.workBook.focus(true);
                            }*/
                        });
                    }
                }, function () {
                    $.bootstrapLoading.end();
                    $('#gljAlert').find('.modal-body h5').text('查询引用错误，不可删除。');
                    $('#gljAlert').modal('show');
                    $('#aleConfBtn').unbind('click');
                    $('#aleConfBtn').bind('click', function () {
                        $('#gljAlert').modal('hide');
                        me.workBook.focus(true);
                    });
                });
            }
        }
    },
    //删除人材机前需要判断人材机是否有被引用，被引用了则不可删除
    repositoryGljDelOpr: function () {
        if (locked) {
            return;
        }
        let me = repositoryGljObj;
        me.workBook.commandManager().register('repositoryGljDel', function () {
            let sels = me.workBook.getActiveSheet().getSelections();
            me.delGljs(sels);
        });

        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);
    },
    onContextmenuOpr: function () {
        let me = repositoryGljObj;
        $.contextMenu({
            selector: '#GLJListSheet',
            build: function($triggerElement, e){
                //控制允许右键菜单在哪个位置出现
                let sheet = me.workBook.getSheet(0);
                let offset = $("#GLJListSheet").offset(),
                    x = e.pageX - offset.left,
                    y = e.pageY - offset.top;
                let target = sheet.hitTest(x, y);
                let sel = sheet.getSelections()[0];
                if(sel.row === -1){
                    sel.row = 0;
                }
                if(sel.col === -1){
                    sel.col = 0;
                }
                if(target.hitTestType === 3 && typeof target.row !== 'undefined' && typeof target.col !== 'undefined'){//在表格内
                    me.initSel(target.row);
                    if(sel.row > target.row || sel.row + sel.rowCount - 1 < target.row ||
                        sel.col > target.col || sel.col + sel.colCount - 1 < target.col ){
                        sheet.setActiveCell(target.row, target.col);
                    }
                    return {
                        callback: function(){},
                        items: {
                            delete: {
                                name: "删除",
                                disabled: function () {
                                    return locked || !(me.currentCache && me.currentCache[target.row]);
                                },
                                icon: "fa-remove",
                                callback: function (key, opt) {
                                    let curSel = _.cloneDeep(sheet.getSelections()[0]);
                                    curSel.colCount = me.setting.header.length;
                                    me.delGljs([curSel]);
                                }
                            },
                            getReference: {
                                name: '查找引用',
                                disabled: function () {
                                    return !(me.currentCache && me.currentCache[target.row]);
                                },
                                icon: 'fa-search',
                                callback: function () {
                                    const glj = me.currentCache[target.row];
                                    me.getReference(glj);
                                }
                            },
                        }
                    };
                }
                else{
                    return false;
                }
            }
        });
    },
    getReference: function (glj) {
        const $info = $('#info');
        const $infoBody = $('#infoBody');
        $.bootstrapLoading.start();
        CommonAjax.post('/stdGljRepository/api/getReference', {repositoryId: glj.repositoryId, gljId: glj.ID}, function (info) {
            const htmlArr = [];
            if (!info || !Object.keys(info).length) {
                htmlArr.push('<li>无引用数据</li>');
            }
            for (let libName in info) {
                htmlArr.push(`<li class="list-title">${libName}</li>`);
                const rations = info[libName];
                const rationList = rations.map(ration => {
                    if (ration.rationRepId) {
                        return `<li>
                                    <span>${ration.code}</span>
                                    <a target="_blank" href="/rationRepository/ration?repository=${ration.rationRepId}&locked=${locked}#${ration.code}">定位</a>
                                </li>`;
                    }
                    return `<li><span>${ration.code}</span></li>`;
                });
                htmlArr.push(...rationList);
            }
            $infoBody.html(htmlArr.join(''));
            $info.modal('show');
            $.bootstrapLoading.end();
        }, function () {
            $.bootstrapLoading.end();
        });
    },
    validUpdateObj: function (pasteObj, rowIdx) {
        let rst = {updateGlj: [], updateBasePrcArr: []}, backUpObj = {},
            me = repositoryGljObj,
            that = gljComponentOprObj,
            tempObj = me.currentCache[rowIdx],
            reCalBasePrc = false,
            isValid = true,
            materialTypeValid = 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){
                    pasteObj.gljType = me.distTypeTree.comboDatas[i].value;
                    isExsit = true;
                    if (!me.taxRateTypes.includes(pasteObj.taxRate) && me.taxRateTypes.includes(tempObj.taxRate)) {
                        tempObj.taxRate = null;
                    }
                    //调整系数
                    if(pasteObj.gljType !== 1 && pasteObj.gljType !== 303){
                        tempObj.adjCoe = null;
                    }
                    else if((pasteObj.gljType === 1 || pasteObj.gljType === 303) && typeof pasteObj.adjCoe !== 'undefined' && !isNaN(pasteObj.adjCoe) && pasteObj.adjCoe % 1 === 0) {
                        tempObj.adjCoe = pasteObj.adjCoe;
                    }
                    if(pasteObj.gljType !== 301 && tempObj.gljType === 301){
                        tempObj.model = null;
                    }
                    if(componentType.includes(tempObj.gljType) &&
                        //!(tempObj.gljType === 302 && pasteObj.gljType === 303) && !(tempObj.gljType === 303 && pasteObj.gljType === 302)){//修改了原本是组成物的工料机
                        !(machineComponent.includes(tempObj.gljType) && machineComponent.includes(pasteObj.gljType)) &&
                        !(materialComponent.includes(tempObj.gljType) && materialComponent.includes(pasteObj.gljType))){//修改了原本是组成物的工料机
                        //寻找所有引用了此组成物的工料机,并从组成物中删去此工料机,并重算单价
                        let updateGljs = me.getUpdateGljs(tempObj, true);
                        if(updateGljs.updateArr.length > 0 || updateGljs.updateBasePrcArr.length > 0){
                            for(let i = 0; i < updateGljs.updateArr.length; i++){
                                rst.updateGlj.push(updateGljs.updateArr[i]);
                            }
                            for(let i = 0; i < updateGljs.updateBasePrcArr.length; i++){
                                rst.updateBasePrcArr.push(updateGljs.updateBasePrcArr[i]);
                            }
                        }
                    }
                    tempObj.component = tempObj.gljType === pasteObj.gljType ? tempObj.component : [];
                    /*if(me.allowComponent.indexOf(tempObj.gljType) !== -1){//更改成可含组成物的工料机类型，定额价设置为零
                        tempObj.basePrice = tempObj.gljType === me.distTypeTree.comboDatas[i].value ? tempObj.basePrice : 0;
                    }*/
                    tempObj.gljType = pasteObj.gljType;
                    tempObj.shortName = me.distTypeTree.distTypes[me.distTypeTree.prefix + tempObj.gljType].data.shortName;
                    break;
                }
            }
            if(!isExsit) {
                isValid = false;
            }
        }
        if (typeof pasteObj.taxRate !== 'undefined' 
            && typeof pasteObj.gljType === 'undefined') {
            if (me.taxRateTypes.includes(tempObj.gljType)) {
                tempObj.taxRate = pasteObj.taxRate && !isNaN(pasteObj.taxRate) ? scMathUtil.roundTo(parseFloat(pasteObj.taxRate), -2) : null;
            } else {
                isValid = false;
            }
        }
        if(typeof pasteObj.adjCoe !== 'undefined' && typeof pasteObj.gljType === 'undefined'){
            if(tempObj.gljType && (tempObj.gljType === 1 || tempObj.gljType === 303) && typeof pasteObj.adjCoe !== 'undefined' && !isNaN(pasteObj.adjCoe) && pasteObj.adjCoe % 1 === 0) {
                tempObj.adjCoe = pasteObj.adjCoe;
            }
            else {
                isValid = false;
            }
        }
        //单价相关
        if(me.pasteIncludesPrice(pasteObj)){
            if(!priceProperties || priceProperties.length === 0){
                pasteObj.basePrice = pasteObj.basePrice && !isNaN(parseFloat(pasteObj.basePrice)) ?
                    scMathUtil.roundTo(parseFloat(pasteObj.basePrice), -2) : me.currentCache[rowIdx].basePrice;
                if(pasteObj.basePrice !== me.currentCache[rowIdx].basePrice){
                    reCalBasePrc = true;
                    tempObj.basePrice = pasteObj.basePrice;
                }
            }
            else {
                //多单价粘贴
                let pastePriceProperty = {};
                let priceFields = me.getPriceFields();
                for(let priceField of priceFields){
                    if(typeof pasteObj[priceField] !== 'undefined' && pasteObj[priceField] && !isNaN(parseFloat(pasteObj[priceField]))){
                        pastePriceProperty[priceField] = scMathUtil.roundTo(parseFloat(pasteObj[priceField]), -2);
                    }
                }
                if(!me.priceIsEqual(tempObj, pasteObj)){
                    reCalBasePrc = true;
                    //更新人材机单价
                    for(let priceField in pastePriceProperty){
                        tempObj.priceProperty[priceField] = pastePriceProperty[priceField];
                    }
                }
            }
            let updateGljs = me.getUpdateGljs(tempObj, false);
            if(updateGljs.updateArr.length > 0 || updateGljs.updateBasePrcArr.length > 0){
                for(let i = 0; i < updateGljs.updateArr.length; i++){
                    rst.updateGlj.push(updateGljs.updateArr[i]);
                }
                for(let i = 0; i < updateGljs.updateBasePrcArr.length; i++){
                    rst.updateBasePrcArr.push(updateGljs.updateBasePrcArr[i]);
                }
            }
        }
        if(typeof pasteObj.materialType !== 'undefined'){
            if(!me.materialType.textArr.includes(pasteObj.materialType)){
                isValid = false;
                materialTypeValid = false;
            } else {
                me.materialType.comboItems.forEach(function (item) {
                   if(item.text === pasteObj.materialType){
                       tempObj.materialType = item.value;
                   }
                });
            }
        }
        if(typeof pasteObj.materialCoe !== 'undefined'){
            if(isNaN(pasteObj.materialCoe) ||
                (!tempObj.materialType && (!pasteObj.materialType || !me.materialType.textArr.includes(pasteObj.materialType)))){
                tempObj.materialType = '';
                tempObj.materialCoe = null;
                isValid = false;
            }
            else{
                tempObj.materialCoe = pasteObj.materialCoe !== '' ? scMathUtil.roundTo(parseFloat(pasteObj.materialCoe), -5) : null;
            }
        }
        if(typeof pasteObj.model !== 'undefined'){
            if(!me.machineModel.textArr.includes(pasteObj.model)){
                isValid = false;
            }
            else {
                let existsModel = false;
                if((typeof pasteObj.gljType !== 'undefined' && pasteObj.gljType === 301) ||
                    (tempObj.gljType && tempObj.gljType === 301)){
                    me.machineModel.comboItems.forEach(function (item) {
                        if(item.text === pasteObj.model){
                            tempObj.model = item.value;
                            existsModel = true;
                        }
                    });
                    if(!existsModel){
                        isValid = false;
                    }
                }
                else {
                    isValid = false;
                }
            }
        }
        if(typeof pasteObj.materialIndexType !== 'undefined'){
            tempObj.materialIndexType = pasteObj.materialIndexType;
        }
        if(typeof pasteObj.materialIndexUnit !== 'undefined'){
            tempObj.materialIndexUnit = pasteObj.materialIndexUnit;
        }
        if(typeof pasteObj.materialIndexCoe !== 'undefined'){
            tempObj.materialIndexCoe = pasteObj.materialIndexCoe;
        }
        if(isValid){
            rst.updateGlj.push(tempObj);
            if(reCalBasePrc){
                //重新计算定额基价对象
                let newReObj = {gljId: tempObj.ID, gljType: tempObj.gljType, basePrice: me.getRationGljPrice(tempObj)};
                rst.updateBasePrcArr.push(newReObj);
            }
        }
        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;
                }
            }
        }
        if (pasteObj.taxRate && (isNaN(pasteObj.taxRate) || !me.taxRateTypes.includes(pasteObj.gljType))) {
            return false;
        }
        if(pasteObj.adjCoe && typeof pasteObj.adjCoe !== 'undefined'){
            if(isNaN(pasteObj.adjCoe) || pasteObj.adjCoe % 1 !== 0){
                return false;
            }
        }
        if(pasteObj.materialType){
            if(!me.materialType.textArr.includes(pasteObj.materialType)){
                return false;
            }
            else {
                me.materialType.comboItems.forEach(function (item) {
                    if(item.text === pasteObj.materialType){
                        pasteObj.materialType = item.value;
                    }
                });
            }
        }
        if(pasteObj.materialCoe){
            if(isNaN(pasteObj.materialCoe) || !pasteObj.materialType){
                return false;
            }
        }
        if(typeof pasteObj.model !== 'undefined' && pasteObj.model){
            if(!me.machineModel.textArr.includes(pasteObj.model) || pasteObj.gljType !== 301){
                return false;
            }
            me.machineModel.comboItems.forEach(function (item) {
                if(item.text === pasteObj.model){
                    pasteObj.model = item.value;
                }
            });
        }
        if(!priceProperties || priceProperties.length === 0){
            pasteObj.basePrice = !isNaN(parseFloat(pasteObj.basePrice)) && (pasteObj.basePrice && typeof pasteObj.basePrice !== 'undefined') ? parseFloat(pasteObj.basePrice) : 0;

        }
        else {
            let pastePriceProperty = {};
            let priceFields = me.getPriceFields();
            for(let priceField of priceFields){
                if(typeof pasteObj[priceField] !== 'undefined' && pasteObj[priceField] && !isNaN(parseFloat(pasteObj[priceField]))){
                    pastePriceProperty[priceField] = scMathUtil.roundTo(parseFloat(pasteObj[priceField]), -2);
                }
                else {
                    pastePriceProperty[priceField] = 0;
                }
            }
            pasteObj.priceProperty = pastePriceProperty;
        }
        //pasteObj.basePrice = !isNaN(parseFloat(pasteObj.basePrice)) && (pasteObj.basePrice && typeof pasteObj.basePrice !== 'undefined') ? parseFloat(pasteObj.basePrice) : 0;
        if(!me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]){
            pasteObj.gljClass = me.gljCurTypeId;
        }
        return true;
    },
    canPasted: function (info) {
        let rst = true;
        let me = repositoryGljObj;
        if(me.gljCurTypeId < 0){
            return false;
        }
        //粘贴的最大列下标不超过总列数
        if(info.cellRange.col + info.cellRange.colCount - 1 > me.setting.header.length - 1){
            return false;
        }
        if(info.cellRange.row < me.currentCache.length){
            if(info.cellRange.col === 0){
                return false;
            }
        }
        return rst;
    },
    onClipboardPasting: function(sender, args) {
        let me = repositoryGljObj;
        //复制的列数超过正确的列数，不可复制
        if(me.prevent){
            args.cancel = true;
            return;
        }
        if(!me.canPasted(args)){
            args.cancel = true;
        }
    },
    onClipboardPasted: function(e, info) {
        $.bootstrapLoading.start();
        let me = repositoryGljObj;
        let updateArr = [], addArr = [];
        let items = sheetCommonObj.analyzePasteData(me.setting, info);
        let beginRow = info.cellRange.row, endRow = info.cellRange.row + info.cellRange.rowCount - 1,
            maxRow = me.currentCache.length - 1,
            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' && updateObj.updateGlj.length > 0){
                    //updateArr = updateObj.updateGlj;
                    updateArr = updateArr.concat(updateObj.updateGlj);
                    if(typeof updateObj.updateBasePrcArr !== 'undefined'){
                        //updateBasePrcArr = updateObj.updateBasePrc;
                        updateBasePrcArr = updateBasePrcArr.concat(updateObj.updateBasePrcArr);
                    }
                }
            }
        }
        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 = updateArr.concat(updateObj.updateGlj);
                    if(typeof updateObj.updateBasePrcArr !== 'undefined'){
                        updateBasePrcArr = updateBasePrcArr.concat(updateObj.updateBasePrcArr);
                    }
                }
            }
            //if(info.cellRange.colCount >= me.setting.header.length - 4 && info.cellRange.colCount <= me.setting.header.length){
            //[code, ..., gljType]
            if(info.cellRange.colCount >= 5 && info.cellRange.colCount <= me.setting.header.length){
                for(let i = updateCount ; i < items.length; i++){
                    if(me.isValidObj(items[i])){
                        items[i].component = [];
                        addArr.push(items[i]);
                    }
                }
            }
        }
        else{
            //if(info.cellRange.colCount >= me.setting.header.length - 4 && info.cellRange.colCount <= me.setting.header.length && info.cellRange.col + info.cellRange.colCount - 1 >= 5){
            //粘贴的的最大列至少要等于工料机类型列，因为工料机类型必须有效才可新增
            if(info.cellRange.colCount >= 5 && info.cellRange.colCount <= me.setting.header.length && info.cellRange.col + info.cellRange.colCount - 1 >= me.colMapping.fieldToCol['gljType']){
                for(let i = 0; i < items.length; i++){
                    if(me.isValidObj(items[i])){
                        items[i].component = [];
                        addArr.push(items[i]);
                    }
                }
            }
        }
        //repaint
        for(let i = 0; i < info.cellRange.rowCount; i++){
            resumeArr.push(info.cellRange.row + i);
        }
        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++){
                        let dCode = me.setting.header[col].dataCode;
                        if(me.priceCols.includes(col)){
                            let price = me.getPrice(me.currentCache[resumeArr[i]], col);
                            info.sheet.setValue(resumeArr[i], col, price ? price : 0);
                        }
                        else if(dCode === 'gljType'){
                            let gljType = me.currentCache[resumeArr[i]][dCode];
                            info.sheet.setValue(resumeArr[i], col, me.distTypeTree.distTypes["gljType" + gljType].data.fullName);
                        }
                        else if(dCode === 'materialType'){
                            info.sheet.setValue(resumeArr[i], col, me.currentCache[resumeArr[i]][dCode] ? me.materialTypeIdx[me.currentCache[resumeArr[i]][dCode]]: '');
                        }
                        else if(dCode === 'model'){
                            info.sheet.setValue(resumeArr[i], col, me.currentCache[resumeArr[i]][dCode] ? me.machineModelIdx[me.currentCache[resumeArr[i]][dCode]]: '');
                        }
                        else{
                            info.sheet.setValue(resumeArr[i], col, me.currentCache[resumeArr[i]][dCode]);
                        }
                    }
                }
                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, []);
        } else {
            $.bootstrapLoading.end();
        }
        if(updateBasePrcArr.length > 0 && me.rationLibs.length > 0){
            me.updateRationBasePrcRq(updateBasePrcArr);
        }
    },
    updateRationBasePrcRq: function (basePrcArr, workBook, callback) {
        let me = this;
        me.prevent = true;
        me.calcRation = true;
        if (!$.bootstrapLoading.isLoading()) {
            $.bootstrapLoading.start();
        }
        $.ajax({
            type: 'post',
            url: 'api/updateRationBasePrc',
            data:{basePrcArr: JSON.stringify(basePrcArr), repId: pageOprObj.gljLibId},
            dataType: 'json',
            success: function (result) {
                me.calcRation = false;
                if(result.error){
                    alert("计算定额基价失败");
                }
                if(workBook){
                    workBook.focus(true);
                }
                else {
                    me.workBook.focus(true);
                }
                me.prevent = false;
                if(callback){
                    callback();
                }
                if ($.bootstrapLoading.isLoading()) {
                    $.bootstrapLoading.end();
                }
            }
        });
    },
    mixUpdateRequest: function(updateArr, addArr, removeIds) {
        let me = repositoryGljObj;
        if(updateArr.length > 0){
            me.saveInString(updateArr)
        }
        if(addArr.length > 0){
            const codeMap = {};
            const uniqueCodeAddArr =[];
            addArr.forEach(item => {
                if (!codeMap[item.code]) {
                    codeMap[item.code] = 1;
                    uniqueCodeAddArr.push(item);
                }
            });
            addArr = uniqueCodeAddArr;
            me.saveInString(addArr);
        }
        $.ajax({
            type:"POST",
            url:"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:50000,
            success:function(result){
                if (result.error) {
                    alert(result.message);
                } else {
                    const failCodes = result.data.failCode;
                    if (failCodes && failCodes.length) {
                        let failText = '';
                        failCodes.forEach(code => {
                            failText += `<p>编码“${code}”已存在</p>`;
                        });
                        $('#alertText').html(failText);
                        $('#codeAlert').modal('show');
                    }
                    const insertData = result.data.insertData;
                    me.updateCache(insertData, updateArr, removeIds);
                    //me.sortGlj();
                    if(me.currentOprParent === 1){
                        me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]);
                    }
                    else{
                        me.currentCache = me.getCache();
                    }
                    me.showGljItems(me.currentCache, me.gljCurTypeId);
                    //getCurrentGlj
                    let row = me.workBook.getSheet(0).getSelections()[0].row;
                    me.currentGlj = row < me.currentCache.length ? me.currentCache[row] : null;
                    me.currentComponent = me.currentGlj ?  me.getCurrentComponent(me.currentGlj.component) : [];
                    sheetCommonObj.cleanData(gljComponentOprObj.workBook.getSheet(0), gljComponentOprObj.setting, -1);
                    sheetsOprObj.showData(gljComponentOprObj, gljComponentOprObj.workBook.getSheet(0), gljComponentOprObj.setting, me.currentComponent);
                }
                if (!me.calcRation && $.bootstrapLoading.isLoading()) {
                    $.bootstrapLoading.end();
                }
            },
            error:function(err){
                if ($.bootstrapLoading.isLoading()) {
                    $.bootstrapLoading.end();
                }
                console.log(err);
                alert("保存失败");
            }
        });
    },
    saveInString: function (datas) {
        for(let i = 0, len = datas.length; i < len; i++){
            let data = datas[i];
            if(_exist(data, 'basePrice')){
                data['basePrice'] = data['basePrice'].toString();
            }
            if(_exist(data, 'component')){
                for(let j = 0, jLen = data['component'].length; j < jLen; j++){
                    let comGljObj = data['component'][j];
                    if(_exist(comGljObj, 'consumeAmt')){
                        comGljObj['consumeAmt'] = comGljObj['consumeAmt'].toString();
                    }
                }
            }
        }
        function _exist(data, attr){
            return data && data[attr] !== undefined && data[attr];
        }
    },
    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() {
        let me = this, rst = [];
        for (let i = 0; i < me.gljList.length; i++) {
            if (me.gljList[i].gljClass == me.gljCurTypeId) {
                rst.push(me.gljList[i]);
            }
        }
        return rst;
    },
    updateCache: function(insertData, updateArr, removeIds) {
        let me = this, cacheSection = me.gljList;
        if (insertData && insertData.length > 0) {
            me.gljList = me.gljList.concat(insertData);
            cacheSection = me.gljList;
        }
        for (let i = removeIds.length - 1; i >= 0; i--) {
            for (let j = cacheSection.length - 1; j >= 0 ; j--) {
                if (cacheSection[j]["ID"] == removeIds[i]) {
                    cacheSection.splice(j,1);
                }
            }
        }
        /*if (result && result.data && result.data.ops && result.data.ops.length > 0) {
            for (let i = 0; i < result.data.ops.length; i++) {
                for (let j = 0; j < cacheSection.length; j++) {
                    if (cacheSection[j]['code'] == result.data.ops[i]['code']) {
                        cacheSection[j]["ID"] = result.data.ops[i]["ID"];
                    }
                }
            }
        }*/
        for (let i = 0; i < updateArr.length; i++) {
            for (let 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]['code'] == updateArr[i]['code']) {
                        cacheSection[j] = updateArr[i];
                    }
                }
            }
        }
    },
    updateParentNodeIds: function (nodes, caller) {
        let private_build_parentNodeIds = function(pNodeId, nodesArr){
            let rst = [];
            for (let i = 0; i < nodesArr.length; i++) {
                if (nodesArr[i].children.length > 0) {
                    rst = rst.concat(private_build_parentNodeIds(nodesArr[i].data.ID, nodesArr[i].children));
                } else {
                    rst.push(nodesArr[i].data.ID);
                }
            }
            if (pNodeId && rst.length > 0) {
                caller.parentNodeIds["_pNodeId_" + pNodeId] = rst;
            }
            return rst;
        };
        if (caller.parentNodeIds) {
            private_build_parentNodeIds(null, nodes);
        }
    },
    sortGljDeep: function (datas) {
        function recurCompare(a, b, index){
            if (a[index] && !b[index]) {
                return 1;
            } else if (!a[index] && b[index]) {
                return -1;
            } else if (a[index] && b[index]) {
                let aV = a[index],
                    bV = b[index];
                if (!isNaN(aV) && !isNaN(bV)) {
                    aV = parseFloat(a[index]);
                    bV = parseFloat(b[index]);
                }
                if (aV > bV) {
                    return 1;
                } else if (aV < bV) {
                    return -1;
                } else {
                    return recurCompare(a, b, index + 1);
                }
            }
            return 0;
        }
        //排序符号-
        datas.sort(function (a, b) {
            let aArr = a.code.split('-'),
                bArr = b.code.split('-');
            return recurCompare(aArr, bArr, 0);
        });
    },
    //工料机排序
    sortGlj: function() {
        let me = this;
        me.gljList.sort(function(a, b){
            let rst = 0;
            if (a.code > b.code) rst = 1
            else if (a.code < b.code) rst = -1;
            return rst;
        });
    }
}

let gljTypeTreeOprObj = {
    onClick: function(event,treeId,treeNode) {
        let me = repositoryGljObj,
            that = gljComponentOprObj,
            gljTypeId = treeNode.ID;
        me.gljCurTypeId = treeNode.ID;
        me.addGljObj = null;
        sheetCommonObj.cleanSheet(that.workBook.getSheet(0), that.setting, 10);
        if (me.parentNodeIds["_pNodeId_" + treeNode.ID]) {
            me.currentOprParent = 1;
            me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + treeNode.ID]);
            me.workBook.getSheet(0).setRowCount(me.currentCache.length);
        } else {
            me.currentOprParent = 0;
            me.currentCache = me.getCache();
        }
        me.showGljItems(me.currentCache, gljTypeId);
    },
    beforeRename: function(treeId, treeNode, newName, isCancel) {
        if (newName.length == 0) {
            return false;
        }
        return true;
    },
    onRename : function(e, treeId, treeNode, isCancel) {
        let 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;
        }
        let 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 (let i = 0; i < pItem.items.length; i++) {
                    private_fetchAllSubItems(pItem.items[i]);
                }
            }
        };
        nodeIds.push(treeNode.ID);
        for (let i = 0; i < treeNode.items.length; i++) {
            private_fetchAllSubItems(treeNode.items[i]);
        }
        $.ajax({
            type:"POST",
            url:"api/deleteGljNodes",
            data:{"repId": pageOprObj.gljLibId, "lastOpr": userAccount, "nodes": JSON.stringify(nodeIds), "preNodeId": preNodeId, "preNodeNextId": treeNode.NextSiblingID},
            dataType:"json",
            cache:false,
            timeout:5000,
            success:function(result,textStatus,status){
                let pNode = treeNode.getParentNode();
                if (pNode && pNode.items && pNode.items.length == 1) {
                    pNode.isParent = false;
                }
            },
            error:function(){
            }
        });
        return true;
    },
    onRemove: function(e, treeId, treeNode){
        let 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) {
            let reqData = []
            for (let i = 0; i < nodes.length; i++) {
                let 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;
                reqData.push(node);
            }
            $.ajax({
                type:"POST",
                url:"api/updateGljNodes",
                data:{"repId": pageOprObj.gljLibId, "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() {
        let me = repositoryGljObj, rawNode = {ParentID: -1, NextSiblingID: -1, Name: "所有"}, lastNodeId = -1;
        if (me.treeObj) {
            let rootNodes = me.treeObj.getNodes();
            if (rootNodes.length == 0) {
                gljTypeTreeOprObj.addNewNode(rawNode, lastNodeId, function(err, rst){
                    if (!(err)) {
                        let 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:{"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(){
            let me = repositoryGljObj, sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
            let addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增子节点' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            let btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(){
                treeNode.doing = true;
                let 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)) {
                        let 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();
    }

};
const setTimeoutSync = (handle, time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            try {
                if (handle && typeof handle === 'function') {
                    handle();
                }
                resolve();
            } catch (err) {
                reject(err);
            }
        }, time);
    });
};
setTimeoutSync(() => {
    //throw new Error('a');
}).then(v => {
    setTimeoutSync(() => {
        //Promise.reject(new Error('b'))
        //throw new Error('b');
    });
}).catch(err => console.log(err));