/**
 * Created by Mai on 2017/6/21.
 */
var projectObj = {
    project: null,
    mainSpread: null,
    mainController: null,
    gljSpreed:null,
    beforeMainTreeSelectedChange: function (pre) {
        /*if (node) {
            subViewObj.saveComments(node);
        }*/
    },
    // CSL, 2018-02-09 用于测试显示。使用示例：projectObj.testDisplay(‘总额’, 100);
    testDisplay: function (caption, value) {
        let c = '';
        if (caption) c = caption + ': ';
        let s = `&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${c}${value}`;
        $('#testDisplay').html(s);
    },
    selectedChangeNowTime: 0,
    selectedChangeDelayTime: 20,
    treeSelectedChanged: function (node) {
        let me = this;
        let project = projectObj.project;
        let mainSheet = projectObj.mainController.sheet;
        let init = true;
        locateToCache(node);
        //设置选中行底色和恢复前选中行底色
        let refreshNodes = [node];
        if(!project.mainTree.preSelected){
            refreshNodes.push(project.mainTree.items[0]);
        }
        else {
            refreshNodes.push(project.mainTree.preSelected);
            init = !(project.mainTree.preSelected == node)
        }
        mbzm_obj.nodeChanged = init;
        project.mainTree.preSelected = node;
        projectObj.setNodesStyle(projectObj.mainController.sheet, refreshNodes);
        function delayOpr(callback) {
            let nowTime = Date.now();
            me.selectedChangeNowTime = nowTime;
            setTimeout(function () {
                if (nowTime - me.selectedChangeNowTime == 0) {
                    callback();
                }
            }, me.selectedChangeDelayTime);
        }
        delayOpr(function () {
            if($('#linkComments').hasClass('active')){
                subViewObj.loadComments(node);
            }
            let nodeID = node ? node.getID() : null;
            gljOprObj.mainTreeSelectedChange = gljOprObj.selectedNodeId != nodeID;
            if(init) subObj.initNavItem(node);
            /*
             2018-11-9 在NavItem里设置了默认显示的item,在里执行了click这个操作所以这两个操作不用重复执行了
             gljOprObj.showDataIfRationSelect(node);
             if (activeSubSheetIsCalcProgram())
             calcProgramObj.refreshCalcProgram(node, 3);*/

            //zhong 2017-9-1 特征及内容
            if(pageCCOprObj.active){
                pageCCOprObj.mainActiveCell = projectObj.mainSpread.getActiveSheet().getSelections()[0];//mainSpread焦点单元格
                pageCCOprObj.setCacheAndShow(node);
            }
        });
    },
    refreshBaseActn: function (tree) {
        let setButtonValid = function (valid, btn) {
            if (!projectReadOnly && valid) {
                btn.removeClass('disabled');
            } else {
                btn.addClass('disabled');
            }
        };
        let selected = tree.selected, that = projectObj;

        let canUpLevel = function (node) {
            if(!node){
                return false;
            }
            if(projectObj.project.isBillsLocked()== true && projectObj.project.withinBillsLocked(node)){
                return false;
            }
            if(node.depth()<=1){//焦点行是树结构的第一/二层节点，灰显。
                return false;
            }
            if(node.sourceType !== that.project.Bills.getSourceType()){//焦点行是定额/量价/工料机，灰显。
                return false;
            }else {
                if(node.data.type == billType.FX || node.data.type == billType.BX){//是分项，或者补项灰显。
                    return false;
                }
                if(node.data.type == billType.FB&&node.nextSibling&&node.children.length>0){//焦点行是分部有后兄弟，有子项.
                     if(node.children[0].data.type==billType.FX || node.children[0].data.type==billType.BX){ //焦点行子项是分项
                         return false;
                     }
                }
                if(node.data.type == billType.BILL &&node.nextSibling){//焦点行是清单有后兄弟
                    if(node.data.calcBase&&node.data.calcBase!=""){//有基数计算
                        return false;
                    }
                    if(node.children.length>0&&node.children[0].sourceType !== that.project.Bills.getSourceType()){//有子项,并且子项不是清单
                        return false;
                    }
                }
            }
            return true;
        };
        let canDownLevel = function (node) {
            if(!node){
                return false;
            }
            if(projectObj.project.isBillsLocked()== true && projectObj.project.withinBillsLocked(node)){
                return false;
            }
            if(node.depth()==0){//焦点行是树结构的第一层节点，灰显。
                return false;
            }
            if(node.sourceType !== that.project.Bills.getSourceType()) {//焦点行是定额/量价/工料机，灰显。
                return false;
            }else {
                if(node.data.type == billType.FX || node.data.type == billType.BX){//是分项，灰显。
                    return false;
                }
                if(!node.preSibling){//无前兄弟，灰显
                    return false;
                }else if(node.preSibling.data.calcBase&&node.preSibling.data.calcBase!=""){//前兄弟有基数计算
                    return false
                }
                if(node.preSibling.children.length>0){//前兄弟有子项，子项是分项，灰显。
                    if(node.data.type==billType.FB&&(node.preSibling.children[0].data.type==billType.FX||node.preSibling.children[0].data.type==billType.BX)){//焦点行是分部前兄弟有子项，子项是分项，灰显。
                        return false;
                    }
                    if(node.data.type==billType.BILL&&node.preSibling.children[0].sourceType !== that.project.Bills.getSourceType()){//焦点行是清单，子项不是清单
                        return false
                    }
                }
            }
            return true;
        };
        let canUpMove = function (node) {
            if(node&&node.sourceType!= ModuleNames.ration_glj &&node.preSibling){//有前兄弟 并且不是定额工料机
                if(node.sourceType==that.project.Bills.getSourceType()){
                    if(projectObj.project.isBillsLocked()== true && projectObj.project.withinBillsLocked(node)){
                        return false;
                    }
                    if(node.data.type == billType.DXFY&&node.data.isAdd!==1){
                        return false;
                    }
                }
                return true
            }
            return false
        };
        let canDownMove = function (node) {
            if(node&& node.sourceType!= ModuleNames.ration_glj &&node.nextSibling){//并且不是定额工料机
                if(node.sourceType==that.project.Bills.getSourceType()){
                    if(projectObj.project.isBillsLocked()== true && projectObj.project.withinBillsLocked(node)){
                        return false;
                    }
                    if(node.data.type == billType.DXFY&&node.data.isAdd!==1){
                        return false;
                    }
                }
                return true;
            }
            return false
        };

        setButtonValid(projectObj.project.Ration.canAdd(selected), $('#insertRation'));
        setButtonValid(ifCanDelete(), $('#delete'));
        setButtonValid(canUpLevel(selected), $('#upLevel'));
        setButtonValid(canDownLevel(selected), $('#downLevel'));
        setButtonValid(canUpMove(selected) , $('#upMove'));
        setButtonValid(canDownMove(selected), $('#downMove'));
        setButtonValid(!projectObj.project.isBillsLocked(), $('#ZLFB_btn'));
        setButtonValid(!projectObj.project.isBillsLocked(), $('#ZLQD_btn'));

    },
    checkCommonField: function (editingText, colSetting) {
        let value;
        if (colSetting.data.decimal) {
            value = Number(editingText);
            if (number_util.isNumber(value)) {
                if (colSetting.data.decimal) {
                    value = value.toDecimal(colSetting.data.decimal);
                }
            } else {
                value = null;
                alert('当前输入的数据类型不正确，请重新输入。');
            }
        } else {
            value = editingText;
        }
        return value;
    },
    checkFormulaValidField: function (editingText, colSetting) {
        let value = Number(editingText);
        if(isNaN(value)) return value;
        if (!value) {
            try {
                let exp = new Expression('');
                exp.Expression(editingText);
                value = Number(exp.Evaluate());
            } catch (error) {
                value = null;
            }
        }
        if (value!=undefined||value!=null) {
            if (colSetting.data.decimal) {
                value = value.toDecimal(colSetting.data.decimal);
            }
        } else if (editingText && editingText !== '') {
            value = null;
            alert('当前输入的数据类型不正确，请重新输入。');
        }
        return value;
    },
    checkSpreadEditingText: function (editingText, colSetting) {
        if (colSetting.data.field === 'contain'||colSetting.data.field === 'feesIndex.common.unitFee'|| colSetting.data.field === 'feesIndex.common.totalFee') {//colSetting.data.field === 'quantity'
            return this.checkFormulaValidField(editingText, colSetting);
        }
        else if (colSetting.data.field === 'programID') {
            return this.project.calcProgram.compiledTemplateMaps[editingText];
        }
        else if (colSetting.data.field === 'subType') {
            if (typeof(editingText) !== "number")
                return volumePriceMaps[editingText]
            else
                return editingText;
        }
        else {
            return this.checkCommonField(editingText, colSetting);
        }
    },
    getVisibleRows: function (sRow, count) {
        let rst = [];
        let nodes = projectObj.project.mainTree.items;
        for(let i = sRow, len = nodes.length; i < len; i++){
            if(count <= 0){
                break;
            }
            if(nodes[i].visible){
                rst.push(i);
                count--;
            }
        }
        return rst;
    },
    //根据列标段设置焦点单元格
    setActiveCell(field, moveScroll){
        projectObj.mainSpread.focus(true);
        let mainSheet = projectObj.mainSpread.getActiveSheet();
        TREE_SHEET_HELPER.massOperationSheet(mainSheet,function(){
          let fieldCol = colSettingObj.getColByField(field);
          if(fieldCol){
              if(moveScroll){
                  mainSheet.showColumn(fieldCol, GC.Spread.Sheets.HorizontalPosition.center);
              }
              mainSheet.setActiveCell(projectObj.project.mainTree.selected.serialNo(), fieldCol);
          }
        });
    },
    //获取粘贴更改的单元格（粘贴时，跳过隐藏行）
    checkSpreadChangedCells: function (info) {
        let rst = {refreshRows: [], changedCells: []};
        //获取显示行号
        let vRows = projectObj.getVisibleRows(info.row, info.rowCount);
        let vCount = vRows.length;
        let lastRow = null, count = 0;
        for(let cell of info.changedCells){
            cell.text = info.sheet.getCell(cell.row, cell.col).text();
            if(cell.row !== lastRow){
                count++;
                lastRow = cell.row;
            }
            if(count <= vCount){
                if(vRows[count - 1] !== cell.row){
                    rst.refreshRows.push(cell.row);
                }
                rst.changedCells.push({row: vRows[count - 1], col: cell.col, text: cell.text});
            }
            else {
                rst.refreshRows.push(cell.row);
            }
        }
        rst.refreshRows = Array.from(new Set(rst.refreshRows));
        return rst;
    },
    updateBillsCode: function (node, value) {
        let project = projectObj.project,me = this;
        let stdMatchCode, formatCode, matchs;
        let searchStdBillsAndUpdate = function (stdCode, formatCode) {
            let orgCode = node.data.code?node.data.code.substr(0, 9):"";
            if (projectObj.project.projectInfo.engineeringInfo.bill_lib.length === 0 || updateCodeCheck(value,stdCode === orgCode)) {
                normalUpdate(node,value,stdCode === orgCode);
            } else if (projectObj.project.projectInfo.engineeringInfo.bill_lib.length > 0) {
                let libId = projectObj.project.projectInfo.engineeringInfo.bill_lib[0].id;
                CommonAjax.post('/stdBillsEditor/getStdBillsByCode', {userId: userID, billsLibId: libId, code: stdCode}, function (data) {
                    if (data) {

                        function updateBeforeInsert(node, data) {
                            node.data.name = data.name;
                            if(node.data.type == billType.BX){//从清单库中找到标准清单的话，要把补项改成分项
                                node.data.type = billType.FX;
                            }
                            //sortItems(data.items, data.itemCharacter);//2018-12-03 这里改成在后端获取
                           // sortItems(data.jobs, data.jobContent);
                            pageCCOprObj.setItemContentNode(node, data.jobContent, data.itemCharacter, node.data.name);
                            pageCCOprObj.setCacheAndShow(node);
                        }
                        if (/\//.test(data.unit)) {
                            let existB = projectObj.project.Bills.sameStdCodeBillsData(data.code);
                            if (existB) {
                                updateBeforeInsert(node, data);
                                data.unit = existB.unit;
                                project.Bills.replaceBills(node.source, data, formatCode);
                                projectObj.mainController.refreshTreeNode([node], false);
                                BillsSub.billsSelSub(node.data.code);
                            } else {
                                ConfirmModal.stdBillsUnit.check(data, function (std) {
                                    updateBeforeInsert(node, data);
                                    project.Bills.replaceBills(node.source, std, formatCode);
                                    projectObj.mainController.refreshTreeNode([node], false);
                                    BillsSub.billsSelSub(node.data.code);
                                }, function () {
                                    projectObj.mainController.refreshTreeNode([node], false);
                                });
                            }
                        } else {
                            updateBeforeInsert(node, data);
                            project.Bills.replaceBills(node.source, data, formatCode);
                            projectObj.mainController.refreshTreeNode([node], false);
                            BillsSub.billsSelSub(node.data.code);
                        }
                    } else {
                        normalUpdate(node,value);
                    }
                });
            }
        };
        //分部分项、措施项目才匹配
        let withinValidFixed = false;
        let matchFixedFlags = [fixedFlag.SUB_ENGINERRING, fixedFlag.MEASURE];
        let rootNode = getRootFixedNode(node);
        if(rootNode && rootNode.data.flagsIndex && rootNode.data.flagsIndex.fixed && matchFixedFlags.includes(rootNode.data.flagsIndex.fixed.flag)){
            withinValidFixed = true;
        }
        if(withinValidFixed && (node.data.type==billType.FX||node.data.type==billType.BX||(node.data.type==billType.BILL&&node.source.children.length==0))){//是分项、补项或者叶子清单的情况下才需要查找替换
            if (value&&value.length === 9) {//&& /^[\d]+$/.test(value)  去掉全数字判断    07-31 zhang
                stdMatchCode = value;
                formatCode = project.Bills.newFormatCode(stdMatchCode);
                searchStdBillsAndUpdate(stdMatchCode, formatCode);
                return;
            } else if (value&&value.length === 12 ) {//&& /^[\d]+$/.test(value) 去掉全数字判断    07-31 zhang
                stdMatchCode = value.substr(0, 9);
                matchs = project.Bills.sameStdCode(stdMatchCode, node.data.code);
                if (matchs.indexOf(value) === -1) {
                    searchStdBillsAndUpdate(stdMatchCode, value);
                    return;
                } else {
                    hintBox.infoBox("系统提示","已存在该编码的清单，将自动修改编码后3位，是否继续？",2,function () {
                        let newFormatCode = project.Bills.newFormatCode(stdMatchCode);
                        searchStdBillsAndUpdate(stdMatchCode, newFormatCode);
                    },function () {
                        me.mainController.refreshTreeNode([node], false);
                    },['确定','取消']);
                    return;
                }
            }
        }
        normalUpdate(node,value);

        function normalUpdate(billnode,codeValue,no_Need_Check) {//在标准库中没有找到清单时改分项为补项再更新
            let toBX = false;
            if(no_Need_Check!==true && billnode.data.type == billType.FX){
                billnode.data.type = billType.BX;
                 toBX = true;
            }
            project.Bills.updateField(billnode.source, 'code', codeValue, toBX);
            me.mainController.refreshTreeNode([billnode], false);
        }

        function updateCodeCheck(value,sameStdCode) {//如果前9位相同，只改前三位，则只更新编号就行了，不用做其它处理
            return sameStdCode && value && value.length == 12
        }
    },
    updateRationCode: function (node, value) {
        if(!isDef(node.data.code) && (!isDef(value) || value.toString().trim() == '')){
            return;
        }
        if (projectObj.project.projectInfo.engineeringInfo.ration_lib.length === 0) {
            alert('当前项目无定额库，请添加定额库。');
            this.mainController.refreshTreeNode([node], false);
        } else {
            let libId = parseInt($('#stdRationLibSelect').val());
            CommonAjax.post('/complementaryRation/api/getRationItem', {user_id: userID, rationRepId: libId, code: value}, function (data) {
                if (data) {
                    projectObj.project.Ration.replaceRation(node.source, data);
                    projectObj.project.ration_glj.addRationGLJ(node.source, data);
                } else {
                    alert('当前库中找不到定额"' + value + '"');
                }
                projectObj.mainController.refreshTreeNode([node], false);
            });
        }
    },
    updateCode: function (node, value) {
        let project = projectObj.project;
        if (node.sourceType === project.Bills.getSourceType()) {
            this.updateBillsCode(node, value);   // 新清单不适合实时计算，下面套什么还不能确定，无数量计算也无意义
        } else if (node.sourceType === project.Ration.getSourceType()) {
            if(value && typeof(value) == 'string'){//小写转换成大写
                value = value.toUpperCase();
            }
            project.Ration.updateRationCodes([{'node':node,value:value}]);
          //  this.updateRationCode(node, value);  // 新套定额适合实时计算
            // 这里因异步问题暂时缺少工料机价格。该过程移到：ration_glj.js的refreshAfterSave方法中。
        }
    },
    updateNodeField : function (node,value,filedID,callback) {
        if(node.data[filedID] == value){
            return;
        }
        let data =  {
            type:node.sourceType,
            data:{
                ID:node.data.ID
            }
        };
        data.data[filedID] = value;
        $.bootstrapLoading.start();
        projectObj.project.updateNodes([data],function () {
            node.data[filedID] = value;
            if(callback){
                callback();
            }
            $.bootstrapLoading.end();
        })
    },
    updateCellValue: function (node, value, colSetting,editingText) {
        let project = projectObj.project, fieldName = colSetting.data.field;
        if(node.sourceType==project.ration_glj.getSourceType()){
            project.ration_glj.updateFromMainSpread(value,node,fieldName);
        }
        else if (fieldName === 'overHeight') {
            OVER_HEIGHT.handleValueChanged([{ node, value }]);
            return;
        }
        else if(fieldName === 'remark'){
            projectObj.updateNodeField(node,value,'remark');
        }
        else if(calcTools.isGljRation(node)){
            gljOprObj.updateRationTypeGLJ(value,node,fieldName,editingText);
        }
        else if (value !== calcFees.getFee(node.data, fieldName)||fieldName == 'quantity') {//工程量需要进行转换，所以做特殊处理
            if (fieldName === 'code' && value != '' && !calcTools.isVolumePrice(node)) {
                projectObj.updateCode(node, value);
            }
            else if(fieldName ==='feeRate'){
                project.FeeRate.updateFeeRateFromBills(value,node,fieldName);
            }
            else if(fieldName ==='contain'){//编辑含量
                project.Ration.updateContain(value,node);
            }
            else if (fieldName === 'quantity' || fieldName === 'marketUnitFee' || fieldName === 'feesIndex.common.unitFee'||fieldName === 'feesIndex.common.totalFee' || fieldName === 'programID' ||
                fieldName === 'subType' || fieldName === 'calcBase' || fieldName === 'isSubcontract'){
                if (fieldName === 'quantity') {
                    quantityEditObj.checkingAndUpdate(editingText,node);
                   // project.quantity_detail.editMainTreeNodeQuantity(value,node,fieldName,editingText);
                    return;
                } else if (fieldName === 'marketUnitFee' || fieldName === 'feesIndex.common.unitFee'||fieldName === 'feesIndex.common.totalFee') {
                    if(isNaN(value)){//说明输入的是无效的字符
                        //value == null && editingText!=null && editingText!=""
                        alert("当前输入的数据类型不正确，请重新输入。");
                        projectObj.mainController.refreshTreeNode([node]);
                        return
                    }
                    if (value) {
                        if(fieldName === 'feesIndex.common.unitFee') {
                            value = parseFloat(value).toDecimal(decimalObj.decimal("unitPrice", node));
                            //当前是量价/人材机，综合单价可输入，输入的值读取到市场单价，重算综合单价。
                            if(node.sourceType == ModuleNames.ration && node.data.type != rationType.ration){
                                fieldName = 'marketUnitFee';
                            }
                        }
                        if(fieldName === 'feesIndex.common.totalFee'){//修改了综合合价后，反算综合单价，然后再由计算程序算个综合合价出来
                            let unitfee = 0;
                            if(node.data.quantity){//如果工程量为0或空，综合合单直接填到综合单价
                                let t_quantity = scMathUtil.roundForObj(node.data.quantity,getDecimal("quantity",node));
                                value = scMathUtil.roundForObj(value,getDecimal("unitPrice", node));
                                unitfee = scMathUtil.roundForObj(value/t_quantity,getDecimal("totalPrice", node));
                            }else {
                                unitfee = scMathUtil.roundForObj(value,getDecimal("totalPrice", node));
                            }
                            calcTools.setFieldValue(node, 'feesIndex.common.unitFee', unitfee);
                        }
                    }
                } else if (fieldName === 'calcBase') {
                    //zhong
                    if(value === undefined ||value === null || value.toString().trim() === ''){
                        value = '';
                    }
                    if(value === node.data.calcBase){
                        return;
                    }
                    node.data.userCalcBase = value;
                    project.calcBase.calculate(node);

                    if(!project.calcBase.success){
                        let activeCell = projectObj.mainSpread.getActiveSheet().getSelections()[0];
                        projectObj.mainController.refreshTreeNode([node]);
                        return;
                    } else if (value === '') {//删除清单基数，单价要清空
                        calcTools.setFieldValue(node, 'feesIndex.common.unitFee', 0);
                    }
                };
                //计算基数赋值要经过解析和标准化，已在calculate里赋值
                if(fieldName !== 'calcBase'){
                  calcTools.setFieldValue(node, fieldName, value);
                  projectObj.mainController.refreshTreeNode([node]);  // 量价，输入单价x，反算单价x1，第二次输入单价x，单价不再反算。（实际反算了，没刷新）
                };

                project.calcProgram.calcAndSave(node);
                gljOprObj.showRationGLJSheetData();
            } else if (node.sourceType === project.Bills.getSourceType()&&fieldName === 'unit'){//修改清单单位的时候清单工程量要重新4舍5入
                node.data[fieldName] = value;
                node.changed = true;
                if(node.data.quantity){
                    node.data.quantity =scMathUtil.roundForObj(node.data.quantity,getDecimal("quantity",node));
                }
                project.calcProgram.calcAndSave(node);
            } else {
                if (node.sourceType === project.Bills.getSourceType()) {
                    if(fieldName === "maxPrice" || fieldName === 'minPrice'){
                        if(value == null){
                            value = "";
                        }else {
                            value = scMathUtil.roundToString(value,getDecimal("unitPrice", node))
                        }
                    }
                    project.Bills.updateField(node.source, fieldName, value, false);
                } else if (node.sourceType === project.Ration.getSourceType()) {
                    project.Ration.updateField(node.source, fieldName, value);
                }
                if (colSetting.data.wordWrap) {
                    this.mainSpread.getActiveSheet().autoFitRow(node.serialNo());
                }
                projectObj.mainController.refreshTreeNode([node]);
            }
        } else if(value==null && fieldName ==='feeRate'){
            project.FeeRate.cleanFeeRateID(node);
        } else {
            projectObj.mainController.refreshTreeNode([node], false);
        }
    },
    mainSpreadLeaveCell: function (sender, info) {
        let colSetting = projectObj.mainController.setting.cols[info.col];
        projectObj.lastCol = colSetting;
        projectObj.lastCell = {row: info.row, col: info.col};
        if(colSetting.data.field === 'quantity'){
            SheetDataHelper.hideMoreButton()
        }
    },
    //滚动造价书鼠标时，工程量的更多按钮跟着移动
    TopRowChanged:function(type,info){
        let colSetting = projectObj.mainController.setting.cols[info.sheet.getActiveColumnIndex()];
        if(colSetting.data.field === 'quantity'){
            SheetDataHelper.moveMoreButton(info.sheet)
        }

    },

    //repaint 动态下拉框
    mainSpreadEnterCell: function (sender, info) {
        let colSetting = projectObj.mainController.setting.cols[info.col];
        if(colSetting.data.field === 'unit' || (projectObj.lastCol&&projectObj.lastCol.data.field === 'unit')||colSetting.data.field ==='subType'
            || (projectObj.lastCol&&projectObj.lastCol.data.field === 'subType') || colSetting.data.field === 'programID' ||(projectObj.lastCol&&projectObj.lastCol.data.field === 'programID')){
            let rects = [];
            rects.push(info.sheet.getCellRect(info.row, info.col));
            if(projectObj.lastCell){
                rects.push(info.sheet.getCellRect(projectObj.lastCell.row, projectObj.lastCell.col));
            }
            for(let rect of rects){
                info.sheet.repaint(rect);
            }
        }
    },
    mainSpreadEditStarting: function (sender, info) {
        let project = projectObj.project;
        let node = project.mainTree.items[info.row];
        let fieldName = projectObj.mainController.setting.cols[info.col].data.field;
        let value = info.sheet.getValue(info.row, info.col);
        if(fieldName === 'code' && node && calcTools.isRationItem(node) && isDef(node.data.code)&&isDef(value)){
            if (isDef(node.data.prefix) && node.data.prefix !== rationPrefix.none){
                 value = value.replace(new RegExp(node.data.prefix), '');
            };
            value = value.replace(new RegExp(rationPrefix.replace), '');
            info.sheet.setValue(info.row, info.col, value);
        }
        if(node&&fieldName =='quantity'&&(node.data.quantityEXP !==null||node.data.quantityEXP !==undefined)){
            info.sheet.setValue(info.row, info.col, node.data.quantityEXP);
        }
    },
    onCellDoubleClick: function (sender, info){
        let project = projectObj.project;
        if(info.row && info.col){
            let node = project.mainTree.items[info.row];
            let fieldName = projectObj.mainController.setting.cols[info.col].data.field;
            if(fieldName == 'marketUnitFee'){
                if(gljOprObj.hasComposition(node.data,true)){
                    alert("当前人材机的市场价由组成物计算得出，不可直接修改。");
                    return;
                }
            }
            if(fieldName == 'code' && node){
                projectObj.showBillOrRationLib(node)
            }
        }
    },
    showBillOrRationLib(node){
        let BILLS = projectObj.project.Bills;
        let code = node.data.code ? node.data.code : '';
        if(node.sourceType == ModuleNames.bills){//当清单是“分部分项工程”、“措施项目工程”时，要展开清单规则节点
            if(BILLS.isFXorBX(node)||(node.data.type == billType.BILL && BILLS.isMeasure(node))){//是分项或补项，是清单并且属于措施项目节点
                if(!billsGuidance.bills.tree){
                    doAfterLoadGuidance = function () {
                        billsGuidance.locateAtBills(code);
                        doAfterLoadGuidance = null;
                    }
                } else {
                    billsGuidance.locateAtBills(code);
                }
                if(!$("#zy").is(":visible"))  {
                    $('#stdBillsGuidanceTab').click();
                }
            }
        }
        if(node.sourceType == ModuleNames.ration){ //在定额编码中双击，如果右侧定额库没有展开，则自动展开。
            if(node.data.type != rationType.ration) return ;//只有定额类型才需要自动展开，其它都不用
            let libID = node.data.libID;
            if (node.data.from === 'cpt') {
                libID = node.data.fromUser ? `${rationLibObj.compleRationLibId}*${node.data.fromUser}` : rationLibObj.compleRationLibId;
            }
            if(!rationLibObj.tree){
                if(isDef(libID)) sessionStorage.setItem('stdRationLib', libID);
                rationLibObj.doAfterGetRationTree = function () {
                    this.locateAtRation(libID, code);
                    this.doAfterGetRationTree = null;
                };
            } else {
                if($('#stdRationLibSelect').select().val() != libID){
                    let libOpts = $('#stdRationLibSelect').find('option');
                    for(let libOpt of libOpts){
                        if($(libOpt).val() == libID){
                            $(libOpt).prop('selected', 'selected');
                            break;
                        }
                    }
                    $('#stdRationLibSelect').change();
                    rationLibObj.doAfterGetRationTree = function () {
                        this.locateAtRation(libID, code);
                        this.doAfterGetRationTree = null;
                    };
                } else {
                    rationLibObj.locateAtRation(node.data.libID, code);
                }
            }
            if(!$("#de").is(":visible"))  $('#stdRationTab').click();
        }

    },
    onColumnWidthChanged: function (sender, info) {         // CSL,2018.07.25
        if (info.colList.includes(4) || info.colList.includes(5)){
            let items = projectObj.project.mainTree.items;
            let sheet = projectObj.mainSpread.getActiveSheet();
            for (let i = 0; i < items.length; i++) {
                let need = false;
                if (items[i].data.itemCharacterText){
                    sheet.getCell(i, 4).wordWrap(true);
                    need = true;
                }
                if (items[i].data.jobContentText){
                    sheet.getCell(i, 5).wordWrap(true);
                    need = true;
                }
                if (need) sheet.autoFitRow(i);
            }
        }
    },
    onClipboardPasting: function (sender, info){
        let rIdx = info.sheet.getActiveRowIndex();
        let node = projectObj.project.mainTree.items[rIdx];
        if (!node.parent){
            info.cancel = true;
            hintBox.infoBox('系统提示','大项费用不允许粘贴！', 1);
            return false;
        };

        let colName = projectObj.project.projSetting.main_tree_col.cols[info.cellRange.col].data.field;
        if (colName == 'code'){
            info.cancel = true;

            function getNodeType(node) {
                let t = null;
                if (calcTools.isRationItem(node))
                    t = 1
                else if (calcTools.isBill(node)){
                    if (calcTools.isBill_FB(node))
                        t = 2
                    else if (calcTools.isBill_FX(node) || calcTools.isBill_BX(node))
                        t = 3
                    else if (calcTools.isBill_BILL(node))
                        t = 4;
                };
                return t;
            };
            function getPasteTextArr(info) {
                let copyText = info.pasteData.text.trim();
                if (!copyText) return null;
                let spliter = '';
                if (copyText.includes('\r\n')){
                    spliter = '\r\n'
                }
                else if (copyText.includes('\n')){      // 兼容Unix、Mac 等系统回车换行符
                    spliter = '\n'
                }
                else{
                    spliter = '\r'
                };
                let rows = copyText.split(spliter);
                let rstArr = [];
                for (let row of rows) {
                    row = row.trim();
                    row = row.split('\t');
                    rstArr.push(row);
                }
                return rstArr;
            };
            function getPasteNodes(node, nodeType, count) {
                let nodesArr = [];
                let curNode = null;
                for (let i = rIdx; i < rIdx + count; i++) {
                    curNode = projectObj.project.mainTree.items[i];
                    if (curNode && calcTools.isSameTypeNode(curNode, node)){
                        nodesArr.push(curNode);
                    }
                    else{
                        curNode = projectObj.project.mainTree.items[i - 1];
                        break;
                    }
                }

                if (nodesArr.length < count){
                    if (projectObj.project.mainTree.selected != curNode)
                        projectObj.project.mainTree.selected = curNode;

                    let add = count - nodesArr.length;
                    for (let i = 0; i < add; i++) {
                        switch (nodeType) {
                            case 1:
                                curNode = projectObj.project.Ration.addNewRationFast(rationType.ration);
                                break;
                            case 2:
                                curNode = ProjectController.addFB(projectObj.project, projectObj.mainController);
                                break;
                            case 3:
                                curNode = ProjectController.addFX(projectObj.project, projectObj.mainController);
                                break;
                            case 4:
                                curNode = ProjectController.addBills(projectObj.project, projectObj.mainController);
                                break;
                        }

                        if (!curNode){
                            hintBox.infoBox('系统提示','插入新结点出错，粘贴失败！', 1);
                            return nodesArr;
                        }
                        else{
                            nodesArr.push(curNode);
                            if (projectObj.project.mainTree.selected != curNode)
                                projectObj.project.mainTree.selected = curNode;
                        }
                    }
                };

                return nodesArr;
            };
            function doPaste(nodes, nodeType, datas) {
                if (nodeType == 1){  // 批量粘贴定额有严重的异步问题，这里要和清单分开处理
                    let updateRationCodes = [];
                    for (let i = 0; i < datas.length; i++) {
                        let ptNode = nodes[i];
                        let code = datas[i][0];
                        // 编号去掉“换、借、补”等多余的字
                        code = code.replace(new RegExp(rationPrefix.complementary), '');
                        code = code.replace(new RegExp(rationPrefix.borrow), '');
                        code = code.replace(new RegExp(rationPrefix.replace), '');
                        updateRationCodes.push({'node':ptNode, value:code});
                    }
                    projectObj.project.Ration.updateRationCodes(updateRationCodes);
                }
                else {
                    for (let i = 0; i < datas.length; i++) {
                        let ptNode = nodes[i];
                        let code = datas[i][0];
                        if (!(ptNode.data && ptNode.data.code && ptNode.data.code.sameText(code))){
                            projectObj.updateCode(ptNode, code);
                        };
                    }
                }
                projectObj.mainController.refreshTreeNode(nodes);
            };

            let tagType = getNodeType(node);
            if (!tagType){
                hintBox.infoBox('系统提示', '该树结点类型不支持从项目编码列粘贴！', 1);
                return false;
            };
            let datas = getPasteTextArr(info);
            if (!datas) return;
            let pasteNodes = getPasteNodes(node, tagType, datas.length);
            doPaste(pasteNodes, tagType, datas);
        };
    },
    mainSpreadEditEnded: function (sender, info) {
        let project = projectObj.project;
        let node = project.mainTree.items[info.row];
        project.withinBillsLocked(node);
        let colSetting = projectObj.mainController.setting.cols[info.col];
        let fieldName = projectObj.mainController.setting.cols[info.col].data.field;
        //提前处理
        if (fieldName === 'code' || fieldName === 'name' || fieldName === 'unit') {
            info.editingText = info.editingText ? info.editingText.toString().replace(new RegExp(/[\r\n]/g), '') : info.editingText;
        }
        // 检查输入类型等
        let value = projectObj.checkSpreadEditingText(info.editingText, colSetting);
        projectObj.updateCellValue(node, value, colSetting,info.editingText);

        // 自动行高
        const autoHeight = project.property.displaySetting.autoHeight;
        if (autoHeight) {
            projectObj.mainSpread.getActiveSheet().autoFitRow(info.row);
        }
    },
    msClipboardChanged: function (sender, info) {
        let colSettings = projectObj.mainController.setting.cols;
        let cDatas = sheetCommonObj.getTableData(info.sheet, colSettings);
        sheetCommonObj.copyTextToClipboard(cDatas);
        return;
    },
    mainSpreadRangeChanged: function (sender, info) {
        let project = projectObj.project, setting = projectObj.mainController.setting;
        let changedObj = projectObj.checkSpreadChangedCells(info);
        let refreshNodes = [];
        for(let row of changedObj.refreshRows){
            refreshNodes.push(project.mainTree.items[row]);
        }
        let updateRationCodes = [];//更新定额编码时要用同步的方式
        // 超高降效的操作比较耗时，需要减少触发
        const overHeightChangedData = [];
        if(changedObj.changedCells.length > 0){
            console.log(changedObj.changedCells);
            for (let changedCell of changedObj.changedCells) {
                let node = project.mainTree.items[changedCell.row];
                let colSetting = setting.cols[changedCell.col];
                let value = projectObj.checkSpreadEditingText(changedCell.text, colSetting);
                if(colSetting.data.field=='code' && node.sourceType == project.Ration.getSourceType()&&node.data.type==rationType.ration){//如果是更新定额的编码
                    updateRationCodes.push({'node':node,value:value});
                } else if (colSetting.data.field === 'overHeight') {
                    overHeightChangedData.push({ node, value });
                } else {
                    projectObj.updateCellValue(node, value, colSetting,changedCell.text);
                }
            }
        }
        if (overHeightChangedData.length) {
            OVER_HEIGHT.handleValueChanged(overHeightChangedData);
        }
        if(updateRationCodes.length>0){
            project.Ration.updateRationCodes(updateRationCodes);
        }
        if(refreshNodes.length > 0){
            projectObj.mainController.refreshTreeNode(refreshNodes);
        }
    },
    checkMainSpread: function () {
        if (!this.mainSpread) {
            this.mainSpread = SheetDataHelper.createNewSpread($('#billsSpread')[0]);
            sheetCommonObj.spreadDefaultStyle(this.mainSpread);
            this.mainSpread.getActiveSheet().selectionPolicy(GC.Spread.Sheets.SelectionPolicy.muliRange);
            this.mainSpread.getActiveSheet().name('mainSheet');
            this.mainSpread.getActiveSheet().options.isProtected = true;
            this.mainSpread.getActiveSheet().options.frozenlineColor = '#ababab';
        }
    },
    refreshMainSpread: function () {
        if (this.mainSpread) {
            this.mainSpread.refresh();
        }
    },
    loadProjectData: function () {
        var that = this;
        this.project = PROJECT.createNew(scUrlUtil.GetQueryString('project'), userID);
        let startTime = +new Date();
        console.log("开始加载-----"+startTime);
        $.bootstrapLoading.start();
        this.project.loadDatas(function (err) {
            let mTime = +new Date();
            console.log(`get data时间——${mTime - startTime}`);
            //快速列设置
            if(!colSettingObj.getVisible('itemCharacterText')){
                switchTznrHtml(true);
            }
            if(colSettingObj.getVisible('itemCharacterText')){
                switchTznrHtml(false);
            }
            if (!err) {
                that.project.projectGLJ.calcQuantity(true);//计算分部分项和技术措施项目消耗量;
                let quantityTime = +new Date();
                console.log(`计算quantity时间——${quantityTime - mTime}`);
                //that.project.property = projectObj.project.projectInfo.property;  改在doAfterLoad的时候设置
                if (typeof overwriteRationCalcBases === 'function')
                    overwriteRationCalcBases(that.project.property.taxType);
                //that.project.calcProgram.compileAllTemps();
                if (typeof dynamicLoadCalcBase !== 'undefined') {
                    dynamicLoadCalcBase();
                }
                that.project.calcBase.init(that.project);
                // that.project.calcFields = JSON.parse(JSON.stringify(cpFeeTypes));
                // that.project.initCalcFields();
                let str = JSON.stringify(that.project.projSetting.main_tree_col);
                that.project.projSetting.mainGridSetting = JSON.parse(str);
                that.project.projSetting.mainGridSetting.frozenCols = 4;
                TREE_SHEET_HELPER.initSetting($('#billsSpread')[0], that.project.projSetting.mainGridSetting);
                that.project.projSetting.mainGridSetting.setAutoFitRow = MainTreeCol.getEvent("setAutoFitRow");
                that.project.projSetting.mainGridSetting.cols.forEach(function (col) {
                    col.data.splitFields = col.data.field.split('.');
                    if (col.data.getText && Object.prototype.toString.apply(col.data.getText) === "[object String]") {
                        col.data.getText = MainTreeCol.getEvent(col.data.getText);
                    }
                    if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object String]") {
                        col.readOnly = MainTreeCol.getEvent(col.readOnly);
                    }
                    if (col.data.cellType && Object.prototype.toString.apply(col.data.cellType) === "[object String]") {
                        let getCellType = MainTreeCol.getEvent(col.data.cellType);
                        col.data.cellType = getCellType;
                    }
                    // if (col.data.digit && Object.prototype.toString.apply(col.data.digit) === "[object String]") {
                    //     col.data.decimal = that.project.getDecimal(col.data.digit);
                    //     col.data.formatter = MainTreeCol.getNumberFormatter(col.data.decimal);
                    // }
                    if (col.data.field === 'code') {
                        col.data.formatter = '@';
                    }
                    col.setAutoHeight = MainTreeCol.getEvent("setAutoHeight");
                    col.editChecking = MainTreeCol.getEvent("editChecking");
                    // 根据配置设置自动行高,在这里先做个标记，然后对每个单元格单独配置
                    if (col.data.field === 'name' || col.data.field === 'itemCharacterText' ||
                        col.data.field === 'jobContentText' || col.data.field === 'adjustState') {
                        col.data.autoHeight = true;
                        col.showHint = true;
                    }
                    if(col.data.field ==='quantity' || col.data.field ==='remark'){
                        col.showHint = true;
                    }

                    // 综合单价、综合合价，小数部分应补0对齐。  CSL
                    // if (col.data.field.hasSubStr("common")){
                        if (col.data.field.hasSubStr(".totalFee"))
                            col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.totalPrice, true);
                        else if (col.data.field.hasSubStr(".unitFee")||col.data.field.hasSubStr("maxPrice"))
                            col.data.formatter = MainTreeCol.getNumberFormatter(decimalObj.ration.unitPrice, true);
                    // }

                });
                let startShowTime = +new Date();
                that.mainController = TREE_SHEET_CONTROLLER.createNew(that.project.mainTree, that.mainSpread.getActiveSheet(), that.project.projSetting.mainGridSetting);

                let endShowTime = +new Date();
                console.log(`show data时间——${endShowTime - startShowTime}`);
                that.mainController.bind('refreshBaseActn', that.refreshBaseActn);
                that.mainController.bind(TREE_SHEET_CONTROLLER.eventName.beforeTreeSelectedChange, that.beforeMainTreeSelectedChange);
                that.mainController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, that.treeSelectedChanged);
                gljCol.initGljCol(that.project.projSetting.glj_col?that.project.projSetting.glj_col.showAdjustPrice:false,
                  that.project.property.tenderSetting.showTenderFields?that.project.property.tenderSetting.showTenderFields:false,true);
                  that.mainController.showTreeData();
                subObj.initSubSpread();//初始化主界面下方的表格
                if(!projectReadOnly){
                    that.mainSpreadEscKey(that.mainSpread, that.mainSpreadEditStarting, that.mainSpreadEditEnded);
                    sheetCommonObj.bindEnterKey(that.mainSpread, that.mainSpreadEnterKey);
                    that.bindPaseBlockKey(that.mainSpread);
                }
                setTimeout(function () {
                    that.mainSpread.getActiveSheet().startEdit();//这两句需要挺多时间,而又需要在editend 事件前触发，而这些又不影响计算，所以这里用异步的方法
                    that.mainSpread.getActiveSheet().endEdit();

                    that.mainSpread.bind(GC.Spread.Sheets.Events.EditEnded, that.mainSpreadEditEnded);
                    that.mainSpread.bind(GC.Spread.Sheets.Events.EditStarting, that.mainSpreadEditStarting);
                },100);
                that.mainSpread.bind(GC.Spread.Sheets.Events.SelectionChanged, that.amountAreaNumber);//选中统计专用，节点相关操作在treeSelectedChanged里些
                that.mainSpread.bind(GC.Spread.Sheets.Events.LeaveCell, that.mainSpreadLeaveCell);
                that.mainSpread.bind(GC.Spread.Sheets.Events.EnterCell, that.mainSpreadEnterCell);

                that.mainSpread.bind(GC.Spread.Sheets.Events.RangeChanged, that.mainSpreadRangeChanged);
                that.mainSpread.bind(GC.Spread.Sheets.Events.ClipboardChanged, that.msClipboardChanged);
                that.mainSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, that.onButtonClick);
                that.mainSpread.bind(GC.Spread.Sheets.Events.CellDoubleClick, that.onCellDoubleClick);
                that.mainSpread.bind(GC.Spread.Sheets.Events.ColumnWidthChanged, that.onColumnWidthChanged);
                that.mainSpread.bind(GC.Spread.Sheets.Events.ClipboardPasting, that.onClipboardPasting);


                //工程量悬浮窗移动事件
                that.mainSpread.bind(GC.Spread.Sheets.Events.TopRowChanged, that.TopRowChanged);
                //let loadOtherStartTime = +new Date();
                //if(!projectReadOnly){
                    that.loadMainSpreadContextMenu();
                //}

                socketObject.connect('main', { projectReadOnly: !!projectReadOnly, user: { ...projectObj.project.projectInfo.opener } });//连接socket服务器
                let endTime = +new Date();
                console.log(`其它时间——${endTime - endShowTime}`);
                console.log("加载完成-----"+endTime);
                console.log(`时间——${endTime - startTime}`);
                that.project.projectMarkChecking();//是否需要重新进行造价计算
                autoFlashHeight();
                that.loadFocusLocation();
                projectObj.refreshMainSpread();
                //定位到会话中的选项
                let mainTabFocus = sessionStorage.getItem('mainTab') ? sessionStorage.getItem('mainTab') : '#tab_zaojiashu';
                $(`${mainTabFocus}`).click();
                if(projectReadOnly){
                    sheetCommonObj.disableSpread(that.mainSpread);
                }

                // 检查旧项目是否有调价数据，没有则自动生成 ----- 有种情况不行，如下：
                // 未知情况：有调价数据，但调价算的不对，所以这里无论什么情况，打开时都要全局算一遍，牺牲速度体验，换来数据稳定。
                // let node = projectObj.project.mainTree.firstNode();
                // if (node.data.feesIndex && node.data.feesIndex.common && node.data.feesIndex.common.totalFee
                //     && node.data.feesIndex.common.totalFee != 0){
                //     if (node.data.feesIndex.common.tenderTotalFee == undefined || node.data.feesIndex.common.tenderTotalFee == 0)
                // };
                 if (projectObj.project.projectInfo.lastFileVer != VERSION){
                     projectObj.project.calcProgram.doTenderCalc();
                     // console.log('旧项目，打开前进行了全局调价计算。')
                 }

                $.bootstrapLoading.end();
            }
            else {

            }
            const onceAlert = getLocalCache(commonConstants.StorageKey.ONCE_MAIN_LOADED);
            if (onceAlert) {
                alert(onceAlert);
                removeLocalCache(commonConstants.StorageKey.ONCE_MAIN_LOADED);
            }
        });

    },
    //绑定复制整块，粘贴整块快捷键
    bindPaseBlockKey:function(workBook){
        workBook.commandManager().register('paseBlock', function () {
            //  console.log("teest Z")
            // BlockController.copyRightClickCallback();
        })

        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.z, true, false, false, false);
        workBook.commandManager().setShortcutKey('paseBlock', GC.Spread.Commands.Key.z, true, false, false, false);
    },

    //mainSpread有一些单元格进入编辑状态后，会动态改变值，公用的bindEscKey方法不适用
    mainSpreadEscKey: function (workBook, editStarting = null, editEnded = null) {
        workBook.commandManager().register('myEsc', function () {
            let sheet = workBook.getActiveSheet();
            if(editStarting){
                sheet.unbind(GC.Spread.Sheets.Events.EditStarting);
            }
            if(editEnded){
                sheet.unbind(GC.Spread.Sheets.Events.EditEnded);
            }
            let row = sheet.getActiveRowIndex();
            let col = sheet.getActiveColumnIndex();
            let orgV = sheet.getValue(row, col);
            let node = projectObj.project.mainTree.items[row];
            let field = colSettingObj.getFieldByCol(col);
            //进入编辑状态后改变了单元格值的时候特殊处理
            if(isDef(field) && field === 'code'){
                if(node && node.sourceType === projectObj.project.Ration.getSourceType() && node.data.type === rationType.ration
                    && isDef(node.data.code) && isDef(node.data.prefix) && node.data.prefix !== rationPrefix.none){
                    orgV = node.data.prefix + orgV;
                }
            }
            else if(isDef(field) && field === 'quantity'){
                orgV = isDef(node) && isDef(node.data.quantity) ? node.data.quantity : '';
            }
            if(!isDef(orgV)){
                orgV = '';
            }
            if(sheet.isEditing()){
                sheet.endEdit();
                sheet.setValue(row, col, orgV);
            }
            if(editStarting){
                sheet.bind(GC.Spread.Sheets.Events.EditStarting, editStarting);
            }
            if(editEnded){
                sheet.bind(GC.Spread.Sheets.Events.EditEnded, editEnded);
            }
        });
        workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.esc, false, false, false, false);
        workBook.commandManager().setShortcutKey('myEsc', GC.Spread.Commands.Key.esc, false, false, false, false);

    },
    mainSpreadEnterKey: function () {
        let me = projectObj;
        let sheet = me.mainSpread.getActiveSheet();
        let orgRow = sheet.getActiveRowIndex();
        let orgCol = sheet.getActiveColumnIndex();
        let orgField = colSettingObj.getFieldByCol(orgCol);
        let selected = me.project.mainTree.items[orgRow];
        if(sheet.isEditing()){
            sheet.endEdit();
        }
        //正常情况，焦点应该是在下一行的同一列
        let newRow = orgRow + 1, newCol = orgCol;
        //getColByField getVisible都不提出来，减少调用次数
        if(selected){
            //在分项/补项的编码单元格回车，焦点应跳动至本行的工程量单元格
            if(orgField && orgField === 'code' && selected.sourceType === me.project.Bills.getSourceType() && [billType.FX, billType.BX].includes(selected.data.type)){
                let quantityCol = colSettingObj.getColByField('quantity');
                let quantityVisible = colSettingObj.getVisible('quantity');
                if(quantityCol !== null && quantityVisible !== false){
                    newRow = orgRow;
                    newCol = quantityCol;
                }
            }
            else if(orgField && orgField === 'quantity' && selected.sourceType === me.project.Bills.getSourceType() && [billType.FX, billType.BX].includes(selected.data.type)){
                //在分项/补项的工程量单元格回车，如果其下有定额/量价/人材机，焦点应跳动至其下第一条定额/量价/人材机的工程量，如果是空行，则跳到至第一条定额xx的编码；
                if(selected.children.length !== 0 && !(isDef(selected.children[0].data.code) && selected.children[0].data.code.toString().trim() !== '')){
                    let codeCol = colSettingObj.getColByField('code');
                    let codeVisible = colSettingObj.getVisible('code');
                    newRow = orgRow + 1;
                    if(codeCol !== null && codeVisible !== false){
                        newCol = codeCol;
                    }
                }
                //如果其下没有定额/量价/人材机，则自动在其下插入一条定额空行，在其后自动插入一条分项空行，焦点跳动至定额空行的编码单元格。
                else if(selected.children.length === 0){
                    //分项没有后兄弟，且没有锁定清单时在其后插入分项
                    if(!selected.nextSibling && !(projectObj.project.projectInfo.property.lockBills && projectObj.project.withinBillsLocked(projectObj.project.mainTree.selected))){
                        ProjectController.addFX(me.project, me.mainController);
                        //将焦点行设置成原本的行，以插入定额
                        me.mainController.setTreeSelected(me.project.mainTree.items[orgRow]);
                    }
                   /* 2021-04-26 只插入清单不插入定额  
                   //插入定额
                    me.project.Ration.addNewRation(null, rationType.ration, function () {
                        newRow = sheet.getActiveRowIndex();
                        let codeCol = colSettingObj.getColByField('code');
                        let codeVisible = colSettingObj.getVisible('code');
                        if(codeCol !== null && codeVisible !== false){
                            newCol = codeCol;
                        }
                        sheet.setActiveCell(newRow, newCol);
                    },true); */
                }
            }
            //在定额/量价/人材机的编码单元格回车，焦点应跳动至本行的工程量单元格
            else if(orgField && orgField === 'code' && selected.sourceType === me.project.Ration.getSourceType()){
                let quantityCol = colSettingObj.getColByField('quantity');
                let quantityVisible = colSettingObj.getVisible('quantity');
                if(quantityCol !== null && quantityVisible !== false){
                    newRow = orgRow;
                    newCol = quantityCol;
                }
            }
            //在定额/量价/人材机的工程量单元格回车
            else if(orgField && orgField === 'quantity' && selected.sourceType === me.project.Ration.getSourceType()){
                let nextSibling = selected.nextSibling;
                //如果其后有定额/量价/人材机(空行:编码为空不算)，焦点应跳动至下一行定额/量价/人材机的工程量，不需处理

                //如果其后没有定额/量价/人材机(空行也没有)，则自动在其后插入一行定额空行，焦点跳动至定额空行的编码单元格
             /*    if(!nextSibling){
                    let codeCol = colSettingObj.getColByField('code');
                    let codeVisible = colSettingObj.getVisible('code');
                    me.project.Ration.addNewRation(null, rationType.ration, function () {
                        newRow = sheet.getActiveRowIndex();
                        if(codeCol !== null && codeVisible !== false){
                            newCol = codeCol;
                        }
                        sheet.setActiveCell(newRow, newCol);
                    }, true);
                } */
                //如果其后有定额空行，焦点跳动至定额空行的编码单元格
                if(nextSibling && !(isDef(nextSibling.data.code) && nextSibling.data.code.toString().trim() !== '')) {
                    let codeCol = colSettingObj.getColByField('code');
                    let codeVisible = colSettingObj.getVisible('code');
                    if(codeCol !== null && codeVisible !== false){
                        newRow = orgRow + 1;
                        newCol = codeCol;
                    }
                }
            }
            //在清单的编码单元格回车，如果清单是叶子节点，焦点跳动至本行的工程量单元格
            else if(orgField && orgField === 'code' && selected.sourceType === me.project.Bills.getSourceType()
                && selected.data.type === billType.BILL && selected.source.children.length === 0){
                let quantityCol = colSettingObj.getColByField('quantity');
                let quantityVisible = colSettingObj.getVisible('quantity');
                if(quantityCol && quantityVisible){
                    newRow = orgRow;
                    newCol = quantityCol;
                }
            }
        }
        //设置焦点
        sheet.setActiveCell(newRow, newCol);
        //触发表格事件
        me.mainController.setTreeSelected(me.project.mainTree.items[newRow]);//SelectionChanged
        me.mainSpreadLeaveCell({type: 'LeaveCell'}, {sheet: sheet, sheetName: sheet.name(), cancel: false, row: orgRow, col: orgCol});
        me.mainSpreadEnterCell({type: 'EnterCell'}, {sheet: sheet, sheetName: sheet.name(), cancel: false, row: newRow, col: newCol});

    },
    // 注册自定义插入清单数量
    registerFlexibleInsertBillMenu: function (type) {
        const project = projectObj.project;
        const name = `插入${billText[type]}`;
        const inputID = `insert-bills-number${type}`;
        const insertBillsHtml = `<span>${name}&nbsp;&nbsp;<input id=${inputID} class="menu-input" type="text" value="1" onfocus="this.select()">&nbsp;&nbsp;行</span>`;
        return sheetCommonObj.registerInputContextMenuItem(`insertBills${type}`, insertBillsHtml, 'fa-sign-in', async function () {
            if (project.mainTree.selected.data.type == billType.DXFY) {
                if (project.mainTree.selected.data.calcBase && project.mainTree.selected.data.calcBase != "") {
                    alert("当前有基数计算,不能插入子项。");
                    return;
                }
            }
            try {
                const number = +$(`#${inputID}`).val();
                if (!number) {
                    return;
                }
                $.bootstrapLoading.start();
                const postData = ProjectController.getBillsPostData(number, type);
                const newNodes = await ProjectController.addBillsByData(postData, true);
                if (newNodes.length) {
                    projectObj.mainController.setTreeSelected(newNodes[0]);
                    projectObj.selectColAndFocus(project.mainTree.selected);
                }
            } catch (err) {
                console.log(err);
                if (!$('hintBox_form').is(':visible')) {
                    alert(err);
                }
            } finally {
                $.bootstrapLoading.end();
            }
        });
    },
    // 注册自定义插入定额数量
    registerFlexibleInsertRatoinMenu: function () {
        const project = projectObj.project;
        const insertRationHtml = `<span>插入定额&nbsp;&nbsp;<input id='insert-ration-number' class="menu-input" type="text" value="1" onfocus="this.select()">&nbsp;&nbsp;行</span>`;
        return sheetCommonObj.registerInputContextMenuItem('insertRation', insertRationHtml, 'fa-sign-in', async function () {
            try {
                const number = +$('#insert-ration-number').val();
                if (!number) {
                    return;
                }
                $.bootstrapLoading.start();
                const newData = [];
                for (let i = 0; i < number; i++) {
                    newData.push({ itemQuery: null, rationType: rationType.ration });
                }
                await project.Ration.addMultiRation(newData);
                projectObj.setActiveCell('code', true);
            } catch (err) {
                console.log(err);
                if (!$('hintBox_form').is(':visible')) {
                    alert(err);
                }
            } finally {
                $.bootstrapLoading.end();
            }
        });
    },
    loadMainSpreadContextMenu: function () {
        var project = this.project, spread = this.mainSpread, controller = this.mainController;
        $.contextMenu({
            selector: '#billsSpread',
            selectableSubMenu: true,
            build: function ($trigger, e) {
                projectObj.cusRationCombCheck(spread.getActiveSheet());
                var target = SheetDataHelper.safeRightClickSelection($trigger, e, spread);
                controller.setTreeSelected(controller.tree.items[target.row]);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "insertRootBill": {
                    name: "插入大项费用",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return projectReadOnly || (projectObj.project.isBillsLocked() && project.withinBillsLocked(project.mainTree.selected));
                        //return project.mainTree.selected ? project.mainTree.selected.sourceType !== project.Bills.getSourceType() : false;
                    },
                    callback: function (key, opt) {
                        ProjectController.addRootBill(project, controller);
                    },
                    visible: function(key, opt){
                        return project.mainTree.selected&&project.mainTree.selected.parent==null;
                    }
                },
                "insertFB": {
                    name: "插入分部",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        let selected = project.mainTree.selected;
                        if(projectObj.project.isBillsLocked()== false&&selected&&selected.sourceType==project.Bills.getSourceType()){
                            if(selected.data.type==billType.FB){
                                return false;
                            }
                            if(selected.data.type==billType.FX ||  selected.data.type==billType.BX){// 当前定位在分项（包括补项)，
                                if(selected.preSibling){//判断分项有无前兄弟？
                                    //有，则判断父项的类型是什么,是分部，右键有效显示，点击则按②执行。
                                   return selected.parent.data.type!==billType.FB
                                }
                                return false;// 无，右键有效显示，
                            }

                            if(isFlag(selected.data)&&selected.data.flagsIndex.fixed.flag==fixedFlag.SUB_ENGINERRING){//焦点行是分部分项工程
                                if(selected.children.length>0){
                                    return selected.children[0].data.type==billType.FX ||selected.children[0].data.type==billType.BX;//焦点行是分部分项工程，且子项是分项或补项
                                }else {
                                    return false
                                }
                            }
                        }
                        return true;//除了清单，其它类型都只读
                    },
                    callback: function (key, opt) {
                        /* 2020-12-28 插入前先弹窗选择
                        let selected = project.mainTree.selected;
                        if(selected.data.type==billType.FX || selected.data.type==billType.BX){
                             //添加成分项的父亲
                             ProjectController.addFXParent(selected);
                        }else{//正常添加分部
                            ProjectController.addFB(project, controller);
                            projectObj.selectColAndFocus(project.mainTree.selected);
                        } */
                        $("#selectFBFor").val("add");
                        $('#selectFBDiv').modal('show');
                    },
                    visible: function(key, opt){
                        if(project.mainTree.selected){
                            return project.Bills.isFBFX(project.mainTree.selected );//不属于分部分项的话隐藏
                        }else {
                            return false;
                        }
                    }
                },
                "insertFX": {
                    type: projectObj.registerFlexibleInsertBillMenu(billType.FX), // 插入分项
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        let selected = project.mainTree.selected;
                        if(projectObj.project.isBillsLocked()== false&& selected&&selected.sourceType==project.Bills.getSourceType()){
                            if(selected.data.type==billType.FX||selected.data.type==billType.BX){//焦点行是分项，有效显示
                                return false
                            }
                            if(selected.data.type==billType.FB){//点行是分部，
                                if(selected.children.length>0){//且有子项，子项是分部，灰显。
                                    return selected.children[0].data.type == billType.FB
                                }else {
                                    return false;
                                }
                            }
                            if(isFlag(selected.data)&&selected.data.flagsIndex.fixed.flag==fixedFlag.SUB_ENGINERRING){//焦点行是分部分项工程
                                if(selected.children.length>0){
                                    return selected.children[0].data.type==billType.FB;//焦点行是分部分项工程，且子项是分部时灰显
                                }else {
                                    return false
                                }
                            }
                        }
                        return true;//除了清单，其它类型都只读
                    },
                    visible: function(key, opt){
                        if(project.mainTree.selected){
                            return project.Bills.isFBFX(project.mainTree.selected );//不属于分部分项的话隐藏
                        }else {
                            return false;
                        }
                    }
                },
                "insertBills": {
                    type: projectObj.registerFlexibleInsertBillMenu(billType.BILL), // 插入清单
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        let selected = project.mainTree.selected;
                        if(!(projectObj.project.isBillsLocked()== true && project.withinBillsLocked(selected)) && selected && selected.sourceType === project.Bills.getSourceType()){
                            return false
                        }
                        return true;
                    },
                    visible: function(key, opt){
                        if(project.mainTree.selected){
                            return  project.Bills.isFBFX(project.mainTree.selected)==true?false:true;
                        }else {
                            return false;
                        }
                    }
                },
                "spr1": '--------',
                "insertRation": {
                    type: projectObj.registerFlexibleInsertRatoinMenu(), // 插入定额
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        // var selected = project.mainTree.selected;
                        // return project.Ration.addRationChecking(selected);  // Vincent, 2018-01-02
                        // 工具栏要加按钮，且不能隐藏。菜单可以隐藏，两者又必须统一，所以启用新规则。怕以后又要改回来，所以保留。 CSL, 2018-01-02
                        return !project.Ration.canAdd(project.mainTree.selected);
                    },
                },
                "insertLJ": {
                    name: "插入量价",//插入量价不需要自动定位到编号列
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        return !project.Ration.canAdd(project.mainTree.selected);
                    },
                    callback: function (key, opt) {
                        /* project.Ration.addNewRation(null,rationType.volumePrice,function (newNode) {
                         projectObj.selectColAndFocus(newNode,null);
                         },true);*/
                    },
                    items:{
                        insertLabour:{
                            name: "人工",
                            icon: 'fa-sign-in',
                            callback:function(key){
                                project.Ration.insertVolumePrice(gljType.LABOUR);
                            }
                        },
                        insertMaterial:{
                            name:"材料" ,
                            icon: 'fa-sign-in',
                            callback:function(key){
                                project.Ration.insertVolumePrice(gljType.GENERAL_MATERIAL);
                            }
                        },
                        insertMachine:{
                            name:"机械" ,
                            icon: 'fa-sign-in',
                            callback:function(key){
                                project.Ration.insertVolumePrice(gljType.GENERAL_MACHINE);
                            }
                        },
                        insertMainMaterial:{
                            name:"主材" ,
                            icon: 'fa-sign-in',
                            callback:function(key){
                                project.Ration.insertVolumePrice(gljType.MAIN_MATERIAL);
                            }
                        },
                        insertEquipment:{
                            name:"设备" ,
                            icon: 'fa-sign-in',
                            visible: function () {
                                if (typeof isCQ2018 != 'undefined') {
                                    return false;
                                }else{
                                    return true;
                                }
                            },
                            callback:function(key){
                                project.Ration.insertVolumePrice(gljType.EQUIPMENT);
                            }
                        }

                    }
                },
                "insertGLJ": {
                    name: "插入人材机",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        // var selected = project.mainTree.selected;
                        // return project.Ration.addRationChecking(selected);  // Vincent, 2018-01-02
                        return !project.Ration.canAdd(project.mainTree.selected);
                    },
                    callback: function (key, opt) {
                        var selected = project.mainTree.selected;
                        if(selected.sourceType == ModuleNames.bills){
                            if(selected.data.type == billType.FX||selected.data.type ==billType.BILL){
                                if(selected.data.calcBase&&selected.data.calcBase!=""){
                                    alert("当前有基数计算，不能插入定额/量价/人材机。");
                                    return;
                                }
                            }
                        }
                        getGLJData('insert', null, true, null);// ProjectController.addRation(project, controller, rationType.volumePrice);
                    },
                    visible: function(key, opt){//2018-11-08  新需求，这个按钮先隐藏，有需要再放开
                        return true;
                    }
                },
                "insertMainMaterial": {
                    name: "按清单名称插入主材",//插入量价不需要自动定位到编号列
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        return !project.Ration.canAdd(project.mainTree.selected);
                    },
                    callback: function (key, opt) {
                        //名称取清单名称，单位取清单单位
                        let selected = project.mainTree.selected;
                        let billNode = selected;
                        if(selected.sourceType==project.Ration.getSourceType()) billNode = selected.parent;
                        let ext = {name:billNode.data.name,unit:billNode.data.unit};
                        project.Ration.insertVolumePrice(gljType.MAIN_MATERIAL,ext);
                    },
                },
                "spr2": '--------',
                "calc_installation_fee": {
                    name: "计取安装费用",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                        return false;
                    },
                    callback: function (key, opt) {
                        installationFeeObj.showCalcInstallSettingDiv();
                    },
                    visible: function(key, opt){
                        return projectObj.project.isInstall();
                    }
                },
                "calcOverHeightFee": {
                    name: '超高降效费用',
                    icon: 'fa-sign-in',
                    visible: function () {
                        return projectObj.project.isOverHeightProject();
                    },
                    items: {
                        'calcOverHeight': {
                            name: '计取超高降效',
                            icon: 'fa-sign-in',
                            disabled: function () {
                                return projectReadOnly;
                            },
                            callback: function (key, opt) {
                                OVER_HEIGHT.switchVisible(true);
                            }
                        },
                        'setOption': {
                            name: '设置子目生成方式',
                            icon: 'fa-sign-in',
                            disabled: function () {
                                return projectReadOnly;
                            },
                            callback: function (key, opt) {
                                $('#overHeightOpt').modal('show');
                            }
                        },
                        'cancelOverHeight': {
                            name: '取消超高降效',
                            icon: 'fa-sign-in',
                            disabled: function () {
                                return projectReadOnly;
                            },
                            callback: function (key, opt) {
                                OVER_HEIGHT.cancelCalc();
                            }
                        },
                    }
                },
                "cleanzmhs":{
                    name:'清空子目换算',
                    icon: 'fa-remove',
                    callback: function (key, opt) {
                        let selected = project.mainTree.selected;
                        projectObj.project.Ration.updateRationCodes([{'node':selected, value:selected.data.code}],true);
                    },
                    visible: function(key, opt){
                        let selected = project.mainTree.selected;
                        if (selected && selected.sourceType == ModuleNames.ration) {
                            return true;
                        }
                        return false;
                    },
                    disabled: function () {
                        let selected = project.mainTree.selected;
                        if (projectReadOnly) {
                            return true;
                        }
                        if(selected && selected.data.type != rationType.ration){
                            return true;
                        }
                        return false;
                    },
                },
                "areaIncreaseFee":{
                    name:"面积增加费",
                    icon: 'fa-sign-in',
                    visible:function () {
                        return  projectObj.project.property.isAreaIncrease == true;
                    },
                    items:{
                        "calcAreaIncreaseFee":{
                            name:"计取面积增加费",
                            icon: 'fa-sign-in',
                            callback:function () {
                                areaIncreaseFeeObj.setDefaultSetting();
                                colSettingObj.setVisible('areaIncreaseFee', true);
                                colSettingObj.updateColSetting(true);
                            }
                        },
                        "setArea":{
                            name:"设置调整系数",
                            icon: 'fa-sign-in',
                            callback:function(){
                                $("#areaIncreaseFeeDiv").modal('show');
                            }
                        },
                        "cancelAreaIncreaseFee":{
                            name:"取消面积增加费",
                            icon: 'fa-sign-in',
                            callback:function(){
                                colSettingObj.setVisible('areaIncreaseFee', false);
                                colSettingObj.updateColSetting(true);
                                areaIncreaseFeeObj.cancelAreaIncreaseFee();
                            }
                        }
                    }
                },
                "itemIncreaseFee":{
                    name:"子目增加费",
                    icon: 'fa-sign-in',
                    visible:function () {
                        return  projectObj.project.property.isItemIncrease == true;
                    },
                    items:{
                        "setItem":{
                            name:"设置范围",
                            icon: 'fa-sign-in',
                            callback:function(){
                                $("#itemIncreaseFeeDiv").modal('show');
                            }
                        },
                        "cancelAreaIncreaseFee":{
                            name:"取消子目增加费",
                            icon: 'fa-sign-in',
                            callback:function(){
                                itemIncreaseFeeObj.cancelItemIncreaseFee();
                            }
                        }
                    }
                },
                "setBookMark": {
                    name: '设置书签批注',
                    icon: 'fa-flag',
                    disabled: function () {
                        if (projectReadOnly || !project.mainTree.selected || project.mainTree.selected.sourceType == ModuleNames.ration_glj) {
                            return true;
                        }
                        return false
                    },
                    items: {
                        cancelMark: {
                            name: '取消书签批注',
                            icon: 'fa-remove',
                            disabled: function () {
                                const selected = project.mainTree.selected;
                                return !(selected && selected.data.bookmarkBackground);
                            },
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, null);
                            }
                        },
                        markE2F2C5: {
                            name: function () {
                                return locateObject.getDescribeByColor('E2F2C5');
                            },
                            icon: 'fa-square annotate-color-1',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'E2F2C5');
                            }
                        },
                        markF9E2CF: {
                            name: function () {
                                return locateObject.getDescribeByColor('F9E2CF');
                            },
                            icon: 'fa-square annotate-color-2',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'F9E2CF');
                            }
                        },
                        markF2EFD9: {
                            name: function () {
                                return locateObject.getDescribeByColor('F2EFD9');
                            },
                            icon: 'fa-square annotate-color-3',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'F2EFD9');
                            }
                        },
                        markF5D1DA: {
                            name: function () {
                                return locateObject.getDescribeByColor('F5D1DA');
                            },
                            icon: 'fa-square annotate-color-4',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'F5D1DA');
                            }
                        },
                        markE3E3E3: {
                            name: function () {
                                return locateObject.getDescribeByColor('E3E3E3');
                            },
                            icon: 'fa-square annotate-color-5',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'E3E3E3');
                            }
                        },
                        markB6F3F2: {
                            name: function () {
                                return locateObject.getDescribeByColor('B6F3F2');
                            },
                            icon: 'fa-square annotate-color-6',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'B6F3F2');
                            }
                        },
                        markECE0F5: {
                            name: function () {
                                return locateObject.getDescribeByColor('ECE0F5');
                            },
                            icon: 'fa-square annotate-color-7',
                            callback: function () {
                                locateObject.setOrCancelBookmark(project.mainTree.selected, 'ECE0F5');
                            }
                        },
                    }
                },
                "delete": {
                    name: '删除',
                    icon: 'fa-remove',
                    disabled: function () {
                        return !ifCanDelete();
                    },
                    callback: function () {
                        var selected = project.mainTree.selected;
                        if(selected.sourceType == project.Bills.getSourceType()&&selected.data.type==billType.FB&&selected.children.length<=0){//选中的是分部，并且没有子项，直接删除
                            project.Bills.deleteSelectedNodes();//project.Bills.deleteSelectedNode();
                        }else {
                            $("#delete_row").modal({show:true});//弹出删除提示框;
                        }
                    }
                },
                "calculateAll_RationContent": {
                    name: '造价计算',
                    icon: 'fa-calculator',
                    callback: function () {
                        $.bootstrapLoading.start();
                        setTimeout(function(){
                            project.calcProgram.calcAllNodesAndSave();
                            $.bootstrapLoading.end();
                        },100)

                    },
                    disabled: function () {
                        if (projectReadOnly) {
                            return true;
                        }
                    },
                    visible:function(key, opt){//2018-11-15 新需求隐藏右键“造价计算”。
                        return true;
                    }
                },
                "spr4":'--------',
                "copyBlock": {
                    name: '复制整块',
                    icon: 'fa-copy',
                    disabled: function () {
                        /* if (projectReadOnly) {
                            return true;
                        }
                        let selection = projectObj.mainSpread.getActiveSheet().getSelections()[0];
                        let firstNode = projectObj.project.mainTree.items[selection.row];//当多选的情况，用mainTree.selected判断不正确,要用第一个选中的节点
                        for(let i = 0;i< selection.rowCount;i++){ //多选的时候判断所有与第一个节点同级的节点
                            let temNode = projectObj.project.mainTree.items[selection.row + i];
                            if(firstNode.getParentID() == temNode.getParentID()){
                                if(BlockController.copyBtnDisable(temNode) == true){
                                    return true;
                                }
                            }
                        }
                        return false; */
                        return BlockController.disabelCopyRightClick();
                    },
                    callback: function () {
                        $.bootstrapLoading.start();
                        //let selected = project.mainTree.selected;
                        let selections = projectObj.mainSpread.getActiveSheet().getSelections();
                        setTimeout(function () {
                            BlockController.copyBlock(selections[0]);
                            $.bootstrapLoading.end();
                        },100)

                    }
                },
                "pasteBlock": {
                    name: '粘贴整块',
                    icon: 'fa-paste',
                    disabled: function (){
                        if (projectReadOnly) {
                            return true;
                        }
                        return BlockController.pasteBtnDisable(project.mainTree.selected);
                    },
                    callback: function () {
                        BlockController.pasteBlock(project.mainTree.selected);
                    }
                },
                "recoverDeletedNodes": {
                    name: '恢复删除节点',
                    icon: 'fa-undo',
                    disabled: function (){
                        return BlockController.recoverBlockDisabled();
                    },
                    callback: function () {
                        BlockController.recoverBlock();
                    }
                },
                "editEngineer": {
                    name: '编辑工程内容',
                    icon: 'fa-edit',
                    disabled: function () {
                        return projectReadOnly;
                    },
                    visible: function(key, opt){
                        let  selected = project.mainTree.selected;
                        return selected.sourceType==ModuleNames.bills&&project.Bills.isEngineerEst(selected);//当焦点行是“专业工程暂估价”时，右键可见并有效。
                    },
                    callback: function () {
                        let node = project.mainTree.selected;//project.Bills.getNodeByFlag(project.mainTree.selected,fixedFlag.ENGINEERING_ESITIMATE);
                        if(node){
                            projectObj.editContent(node,'engineeringContent');
                        }
                    }
                },
                "editService": {
                    name: '编辑服务内容',
                    icon: 'fa-edit',
                    disabled: function () {
                        return projectReadOnly;
                    },
                    visible: function(key, opt){
                        let  selected = project.mainTree.selected;
                        return selected.sourceType==ModuleNames.bills&&project.Bills.isTotalService(selected);//当焦点行是“总承包服务费”时，右键可见并有效。
                    },
                    callback: function () {
                        let node = project.mainTree.selected;//project.Bills.getNodeByFlag(project.mainTree.selected,fixedFlag.TURN_KEY_CONTRACT);
                        if(node){
                            projectObj.editContent(node,'serviceContent');
                        }
                    }
                },
                "editAccording": {
                    name: '编辑签证及索赔依据',
                    icon: 'fa-edit',
                    disabled: function () {
                        return projectReadOnly;
                    },
                    visible: function(key, opt){
                        let  selected = project.mainTree.selected;
                        return selected.sourceType==ModuleNames.bills&&project.Bills.isClaimVisa(selected);//当焦点行是“签证及索赔计价”时，右键可见并有效。
                    },
                    callback: function () {
                        let node = project.mainTree.selected;//project.Bills.getNodeByFlag(project.mainTree.selected,fixedFlag.CLAIM_VISA);
                        if(node){
                            projectObj.editContent(node,'claimVisa');
                        }
                    }
                },
                "replaceMaterial":{
                    name:'智能材料替换',
                    icon: 'fa-edit',
                    disabled:function (key,opt) {
                        if (projectReadOnly) {
                            return true;
                        }
                        let  selected = project.mainTree.selected;
                        return selected.sourceType==ModuleNames.bills ?!(project.Bills.isFXorBX(selected)||selected.source.children.length ==0):true//是分项、补项或叶子清单才有效;
                    },
                    callback:function(){
                        MaterialController.replaceMaterial([project.mainTree.selected]);
                    },
                    visible: function(key, opt){//2018-11-15 暂时隐藏
                        return false
                    }
                },
                "createBlocks":{
                    name:'生成组价模板',
                    icon: 'fa-puzzle-piece',
                    disabled:function (key,opt) {
                        if (projectReadOnly) {
                            return true;
                        }
                        let selected = project.mainTree.selected;
                        return selected.sourceType != ModuleNames.bills;
                    },
                    callback: function(){
                        blockLibObj.checkShow();
                    },
                    visible: function(key, opt){
                        return G_SHOW_BLOCK_LIB;
                    }
                }
            }
        });
    },
    // 计算node及node的所有父项
    converseCalculateBills: function (node) {
        projectObj.project.calcProgram.calcAndSave(node);
    },

    // 获取上次退出时的焦点位置
    loadFocusLocation: function(orow,ocol) {
        const projectId = scUrlUtil.GetQueryString('project');
        let row = gljUtil.isDef(orow)?orow:getLocalCache('lastRow:' + projectId);
        let col = gljUtil.isDef(ocol)?ocol:getLocalCache('lastCol:' + projectId);
        if(row == null || col == null){
            //默认焦点定位到造价书的第一行“分项”。
            col = 1;
            row = 0;
            for(let i =0;i<this.mainController.tree.items.length;i++){
                let node = this.mainController.tree.items[i];
                if(node &&  node.sourceType == ModuleNames.bills && (node.data.type === billType.FX ||node.data.type === billType.BX )){//默认字位到第一条分项或补项
                    row = i;
                    break;
                }
            }
       }
        row = parseInt(row);
        col = parseInt(col);
        const sheet = this.mainSpread.getActiveSheet();
        sheet.setSelection(row, col, 1, 1);
        row=row<this.mainController.tree.items.length?row:0;
        this.mainController.setTreeSelected(this.mainController.tree.items[row]);//触发树节点选中事件
        sheet.showRow(row, GC.Spread.Sheets.VerticalPosition.center);
    },
    // 选中区域合计数字
    amountAreaNumber: function(e, info) {
        if (info.newSelections === undefined || info.newSelections.length <= 0) {
            return false;
        }
        const selectedArea = info.newSelections[0];
        const sheet = info.sheet;
        if (selectedArea.colCount <= 1 && selectedArea.rowCount <= 1) {
            return false;
        }
        //获取最左最右坐标
        let maxCell = {row: selectedArea.row, col: selectedArea.col + selectedArea.colCount};
        let maxCellX = sheet.getCellRect(maxCell.row, maxCell.col).x ? sheet.getCellRect(maxCell.row, maxCell.col).x : sheet.getCellRect(maxCell.row, maxCell.col - 1).x;
        let minCell = {row: selectedArea.row, col: selectedArea.col};
        let minCellX = sheet.getCellRect(minCell.row, minCell.col).x ? sheet.getCellRect(minCell.row, minCell.col).x : sheet.getCellRect(minCell.row, minCell.col + 1).x;
        // 获取鼠标位置
        let x = window.event.clientX;
        let y = window.event.clientY;

        // 匹配数字或小数
        const regular = /^([0-9]+[.]{1}[0-9]+)$|^([1-9]{1}\d*)$/;
        // 小数点最高位数
        let max = 0;
        let total = 0;
        let counter = 0;
        let notNumber = false; //如果有非数字，则不显示
        for (let col = selectedArea.col; col < (selectedArea.colCount + selectedArea.col); col++) {
            for (let row = selectedArea.row; row < (selectedArea.rowCount + selectedArea.row); row++) {
                const value = sheet.getCell(row, col).text();
                if (!regular.test(value)) {
                    if(value) notNumber = true; 
                    continue;
                }
                counter++;
                // 获取当前数据小数位数
                let pointPosition = value.toString().indexOf(".");
                pointPosition = pointPosition < 0 ? pointPosition : pointPosition + 1;
                const current = pointPosition > 0 ? value.toString().substring(pointPosition, value.toString().length).length : 0;
                max = current > max ? current : max;
                total += parseFloat(value);
            }
        }
        //选中的都是数字， 如果不为0则悬浮显示
        if (notNumber === false && total > 0 && counter > 1) {
            const totalString = total.toFixed(max);
            const div = $(`<div id="total-tips"><p>合计:<label id="total">${totalString}</label> </p><p><a href="javascript:void(0);">复制</a></p></div>`);
            div.css({
                position: "absolute",
                border: "1px #C0C0C0 solid",
                background: "#fff",
                boxShadow: "1px 2px 5px rgba(0,0,0,0.4)",
            });
            div.children("p").css({
                textAlign: "center",
                padding: 8,
                marginBottom: 2,
            });
            div.children("p").first().css({
                borderBottom: "1px #C0C0C0 solid"
            });
            // input长度
            const inputWidth = totalString.length * 8;
            // 计算是否会超出显示范围
            const baseWidth = 48;
            const baseHeight = 81;
            const canvasWidth = $("#billsSpreadvp_vp").width();
            const canvasHeight = $("#billsSpreadvp_vp").height();
            //x = x + baseWidth + inputWidth > canvasWidth ? x - baseWidth - inputWidth : x;
            x = maxCellX + baseWidth + inputWidth > canvasWidth ? minCellX - baseWidth - inputWidth : maxCellX + baseWidth;
            y = y + baseHeight > canvasHeight ? y - baseHeight : y;
            //test
            let testT = sheet.getParent().hitTest(x, y);
            //test
            div.css({
                left: x,
                top: y,
            });

            $("body").append(div);
            // 用于判断是否要关闭窗体
            setTimeout(function() {
                isTotalShowing = true;
            }, 200);
        };
    },

    onButtonClick: function (e, info) {
        let colSetting = projectObj.mainController.setting.cols[info.col];
        let node = projectObj.project.mainTree.items[info.row];
        let fieldName = colSetting.data.field;
        if(fieldName == "isSubcontract"){
            projectObj.onSubcontractClick(node);
        }else if(fieldName == "isEstimate"){
            projectObj.onIsEstimateClick(node,info);
        }else if(fieldName == "evaluationProject"){
            projectObj.onEvaluationProjectClic(node,info);
        }else if(fieldName == "mainBills"||fieldName == "outPutMaxPrice"||fieldName=="outPutLimitPrice"||fieldName=="areaIncreaseFee"||fieldName == "lockUnitPrice"){
            projectObj.onCasCadeButtonClick(node,info,fieldName);
        }
    },
    onEvaluationProjectClic:function (node,info) {
        let checkboxValue = info.sheet.getCell(info.row, info.col).value();
        let newval = checkboxValue?0:1;
        projectObj.project.updateEvalproject(newval,node.data,function (programID) {
            node.data.evaluationProject = newval;
            node.data.programID = programID;
            node.changed=true;
            projectObj.project.calcProgram.calcAndSave(node);
        })
    },
    onIsEstimateClick: function(node,info){
        let checkboxValue = info.sheet.getCell(info.row, info.col).value();
        let cell = info.sheet.getCell(info.row, info.col), newval = 0;
        if (checkboxValue) {
            newval = 0;
            cell.value(newval);
        } else {
            newval = 1;
            cell.value(newval);
        }
        if(MainTreeCol.readOnly.bills(node)){
            projectObj.updateNodeField(node,newval,'isEstimate');
        }else if(node.data.projectGLJID){//更新的是定额类型的工料机或者是显示在造价书页面的主材、设备
            console.log(node);
            let updateData = {id: node.data.projectGLJID, field: 'is_evaluate', value: newval};
            projectObj.project.projectGLJ.pGljUpdate(updateData);
        }
    },
   /* onMainBillsClick:function (node,info) {//清单有三种状态，true,false,null。 打勾：true, 不打勾 false 子项有打勾和不打勾的情况 null
        let checkboxValue = info.sheet.getCell(info.row, info.col).value();
        let cell = info.sheet.getCell(info.row, info.col), newval = true;
        if (checkboxValue == true) {
            newval = false;
        } else {
            newval = true;
        }
        projectObj.project.updateMainBills(node,newval);
    },*/
    onCasCadeButtonClick:function (node,info,fieldName) {
        let checkboxValue = info.sheet.getCell(info.row, info.col).value();
        let cell = info.sheet.getCell(info.row, info.col), newval = true;
        if (checkboxValue == true) {
            newval = false;
        } else {
            newval = true;
        }
        if(fieldName == "areaIncreaseFee"){
            areaIncreaseFeeObj.casCadeUpdate(node,newval,fieldName);
        } else {
            projectObj.project.updateCasCadeBills(node,newval,fieldName,fieldName != "lockUnitPrice");
        }
    },
    onSubcontractClick:function (node) {//点击分包费checkbox
        if (node.data.isSubcontract) node.data.isSubcontract = false;
        else node.data.isSubcontract = true;
        node.changed = true;
        projectObj.project.calcProgram.calcAndSave(node);
    },
    //根据节点获取行style(颜色、字体加粗)
    getNodeColorStyle: function (sheet, node, tree) {
        let colorSetting = optionsOprObj.getOption(optionsOprObj.optionsTypes.COLOROPTS);
        let mapping = {DEFAULT: 'DEFAULT', SELECTED: 'SELECTED', DXFY: 'DXFY', FB: 'FB', UNLEAFBILL: 'UNLEAFBILL',
            FX: 'FX', BX: 'BX', UNCBBILL: 'UNCBBILL', CBBILL: 'CBBILL', ZCSB: 'ZCSB'};
        let styleMap = null;
        tree?'':tree =  this.project.mainTree;
        //中文字段名，由于同一节点中，中文字体大小和数字字体大小不同
        if(colorSetting == null){
            return null;
        }
        let stringFields = [
            'code',
            'subType',
            'name',
            'unit',
            'itemCharacterText',
            'jobContentText',
            'adjustState',
            'calcBase',
            'programID',
            'ruleText'
        ];
        if(!isDef(node)){
            return null;
        }
        //清单大类
        if(node.sourceType === this.project.Bills.getSourceType()){
            //大项费用
            if(node.data.type === billType.DXFY){
                styleMap = mapping.DXFY;
            }
            //分部
            if(node.data.type === billType.FB){
                styleMap = mapping.FX;
            }
            //分项
            else if(node.data.type === billType.FX){
                styleMap = mapping.FB;
            }
            //补项
            else if(node.data.type === billType.BX){
                styleMap = mapping.BX;
            }
            //清单
            else if(node.data.type === billType.BILL){
                //非叶子节点的清单
                if(node.source.children.length > 0){
                    styleMap = mapping.UNCBBILL;
                    // styleMap = mapping.UNLEAFBILL;
                }
                //未使用基数计算的叶子节点的清单
                else if(node.source.children.length === 0 && (!isDef(node.data.calcBase) || node.data.calcBase === '')){
                    // styleMap = mapping.UNCBBILL;
                    styleMap = mapping.UNLEAFBILL;
                }
                //使用基数计算的叶子节点的清单
                else if(node.source.children.length === 0 && isDef(node.data.calcBase && node.data.calcBaseValue !== '')){
                    // styleMap = mapping.CBBILL;
                    styleMap = mapping.UNLEAFBILL;
                }
            }
        }
        //定额下的主材、设备
        else if(node.sourceType === this.project.ration_glj.getSourceType()){
            styleMap = mapping.ZCSB;
        }
        else {
            styleMap = mapping.DEFAULT;
        }
        let styleSetting = colorSetting[styleMap];
        let defaultSetting = colorSetting[mapping.DEFAULT];
        if(!isDef(styleSetting)){
            return null;
        }
        let style = new GC.Spread.Sheets.Style();
        //设置style属性
        for(let attr in styleSetting){
            if(attr !== 'stringFont' && attr !== 'numFont'){
                style[attr] = styleSetting[attr] === 'default' || !isDef(styleSetting[attr]) ? defaultSetting[attr] : styleSetting[attr];
            }
            //暂时不开放字体设置，开放的话只能每个单元格进入此方法
           /* else {
                if(stringFields.indexOf(colSetting.data.field) > 0){
                    style.font = styleSetting.stringFont === 'default' || !isDef(styleSetting.stringFont) ? defaultSetting.stringFont : styleSetting.stringFont;
                }
                else {
                    style.font = styleSetting.numFont === 'default' || !isDef(styleSetting.numFont) ? defaultSetting.numFont : styleSetting.numFont;
                }
            }*/
        }
        //选中行-替换底色
        if(node === tree.selected){
             style.backColor = colorSetting[mapping.SELECTED]['backColor'];
        }
        if(_ && !_.isEmpty(node.data.bookmarkBackground)) style.backColor = "#"+ node.data.bookmarkBackground;//设置书签和批注背景色
        //大项费用加粗（数字与中文字符大小不一问题由字体造成，暂时不考虑分别设置大小）
       /* if(node.sourceType === this.project.Bills.getSourceType() && node.data.type === billType.DXFY){
            style.font = 'bold 14px Arial';
        }*/
        style.borderLeft = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderTop = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderRight = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        style.borderBottom = new GC.Spread.Sheets.LineBorder("#D4D4D4", GC.Spread.Sheets.LineStyle.thin);
        return style;
    },
    //大项费用则字体加粗，String 15px, Number 13px
    getBoldFontStyle: function (node, colSetting) {
        let style = new GC.Spread.Sheets.Style();
        if(node.sourceType !== this.project.Bills.getSourceType() || node.data.type !== billType.DXFY){
            return null;
        }

        //备注暂无字段
        let stringFields = [
            'code',
            'subType',
            'name',
            'unit',
            'itemCharacterText',
            'jobContentText',
            'adjustState',
            'calcBase',
            'programID',
            'ruleText'
        ];
        style.font = 'bold 14px Arial';
        return style;
    },
   //设置节点style
    setNodesStyle: function (sheet, nodes,tree) {
        let me = this;
        TREE_SHEET_HELPER.massOperationSheet(sheet, function () {
            for(let node of nodes){
                if(node && node.serialNo()!= -1){
                    sheet.getRange(node.serialNo(), -1, 1, -1).backColor(me.getNodeColorStyle(sheet, node,tree)?me.getNodeColorStyle(sheet, node,tree).backColor:null);
                }
            }
        });

    },
    loadLockBillsButton:function () {
        if(projectObj.project.projectInfo.property.lockBills == true){
            //$("a[name='lockBills']").attr("data-original-title","解锁清单");
            $("a[name='lockBills']").html('<i class="fa fa-unlock-alt" aria-hidden="true"></i> 解锁清单');
        }else {
            //$("a[name='lockBills']").attr("data-original-title","锁定清单");
            $("a[name='lockBills']").html('<i class="fa fa-lock" aria-hidden="true"></i> 锁定清单');
        }
    },
    editContent:function (node,fieldID) {//右键编辑工程内容、服务内容、签证及索赔依据
        let infoText = "请输入";
        switch (fieldID){
            case "engineeringContent":
                infoText +='工程内容:';
                break;
            case "serviceContent":
                infoText +='服务内容:';
                break;
            case "claimVisa":
                infoText +='签证及索赔依据:';
                break;
        }

        hintBox.valueBox(infoText, node.data[fieldID], function () {
            let newValue = hintBox.value;
            projectObj.updateNodeField(node,newValue,fieldID);
        },3);
    },
    ifItemCharHiden:function (setting) {//项目特征及内容列是否隐藏
        if(this.itemCol == null||this.itemCol == undefined){
            this.itemCol = _.find(setting.cols,function (item) {
                return  item.data.field == "itemCharacterText";
            })
        }
        return !this.itemCol.visible;
    },
    onCommonTotalFeeButtonClick:function(hitinfo) {
        let me = calcBaseView;
        if(hitinfo.sheet.getParent() === projectObj.mainSpread){
            let node = projectObj.project.mainTree.items[hitinfo.row] ? projectObj.project.mainTree.items[hitinfo.row] : null;
            projectObj.mainController.setTreeSelected(node);
        }
        hitinfo.sheet.setActiveCell(hitinfo.row, hitinfo.col);
        calcBaseView.confirmBtn.attr('toggle', 'commonTotalFee');
        changeCalcBaseFeeRate('commonTotalFee');
        $('#tabCalcBase').tab('show');
        let field = projectObj.mainController.setting.cols[hitinfo.col].data.field;
        calcBaseView.initCalctor('bills',field);
        feeRateObject.showSelectModal(hitinfo);
    },
    selectColAndFocus :function (newNode,field = 'code') {//选中单元格并设置焦点
        if(newNode){
            if(field != null) projectObj.mainController.sheet.setSelection(newNode.serialNo(), colSettingObj.getColByField(field), 1, 1);  //自动定位到编号单元格
            projectObj.mainSpread.focus();
        }
    },
    cusRationCombCheck:function (sheet) {//检查自定义定额编号下拉框，右键的时候不自动消失，现手动结束编辑，并删除元素
        if(sheet.isEditing()){
            sheet.endEdit()
        }
        if($("#rationCheckBox").is(':visible'))  $("#rationCheckBox").parent().parent().remove();
    }


};

// 点击合计框中的复制
$("body").on("click", "#total-tips a", function() {
    const totalElement = $(this).parent().siblings("p").find("#total");
    sheetCommonObj.copyTextToClipboard(totalElement.text());
    $(this).text("已复制");
});
// 合计框点击其他位置关闭
let isTotalShowing = false;
$("body").on("click",  function(e) {
    if (isTotalShowing && !$(e.target).is("#total-tips") && !$(e.target).is("#total-tips p") && !$(e.target).is("#total-tips p a")) {
        $("#total-tips").remove();
        isTotalShowing = false;
    }
});

$('#insert').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;

    if (!selected || selected.sourceType === project.Bills.getSourceType()) {
        ProjectController.addBills(project, controller);
    } else if (selected.sourceType === project.Ration.getSourceType()) {
        ProjectController.addRation(project, controller, selected.data.type);
    };
});

$('#delete').click(function () {
    let project = projectObj.project;
    let selected = project.mainTree.selected;
    if(isSingleSelect()&&selected.sourceType == project.Bills.getSourceType()&&selected.data.type==billType.FB&&selected.children.length<=0){//选中的是分部，并且没有子项，直接删除
        project.Bills.deleteSelectedNode();
    }else {
        $("#delete_row").modal({show:true});//弹出删除提示框;
    }
});

$('#upLevel').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, orgParent = selected.parent;

    if (selected && selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.upLevelBills(selected.source);
        controller.upLevel();
        controller.refreshTreeNode([orgParent]);
        projectObj.project.calcProgram.calcNodesAndSave([selected,orgParent]);
    }
});
$('#downLevel').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;
    if (selected && selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.downLevelBills(selected.source);
        controller.downLevel();
        controller.refreshTreeNode([selected.parent]);
        projectObj.converseCalculateBills(selected.parent);
    }
});
$('#insertRation').click(function () {
    // projectObj.project.Ration.addNewRation(null,rationType.ration);
    // 连续点工具栏的插入定额按钮，显示树结构画线有问题。
    //projectObj.project.Ration.addNewRationFast(rationType.ration,projectObj.selectColAndFocus);
    //2020-01-08  要限制定额数量，所以还是要用等回传信息的方式插入定额
    projectObj.project.Ration.addNewRation(null,rationType.ration,projectObj.selectColAndFocus,false);
});
$('#upMove').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, pre = selected.preSibling, preSerialNo;

    if (selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.upMoveBills(selected.source);
        controller.upMove();
    } else if (selected.sourceType === project.Ration.getSourceType()) {
        project.Ration.changePos(selected.source, selected.preSibling.source);
        controller.upMove();
    };
});
$('#downMove').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, next, nextSerialNo;

    if (selected) {
        if (selected.sourceType === project.Bills.getSourceType()) {
            project.Bills.downMoveBills(selected.source);
            controller.downMove();
        } else if (selected.sourceType === project.Ration.getSourceType()) {
            project.Ration.changePos(selected.source, selected.nextSibling.source);
            controller.downMove();
        };
    }
});
$("a[name='lockBills']").click(function () {//点击锁定/解锁清单
    let lockBills = projectObj.project.projectInfo.property.lockBills;
    lockBills = !lockBills;
    projectObj.project.updateLockBills(lockBills,function () {
        var controller = projectObj.mainController, project = projectObj.project;
        var selected = controller.tree.selected;
        let nodes = _.filter(project.mainTree.items,{'sourceType':ModuleNames.bills});
        controller.refreshTreeNode(nodes);
        projectObj.mainController.setTreeSelected(selected);//触发树节点选中事件
        projectObj.loadLockBillsButton();
        $('#tzCharacterText').prop('readonly', lockBills);
        if(!projectReadOnly){
            pageCCOprObj.refreshRuleTools(lockBills);
        }
        //$("[data-toggle='tooltip']").tooltip('hide'); bs 与 jqueryUI冲突
    });
});
$('#ZLFB_btn').click(function () {
    zlfb_object.getSectionInfo();
});

//显示至..
let displayLevel = function(nodes, depth, type){
    let refreshNodes = [];
    function getExpandedController(){
        if(type === 'DXFY' || type === 'FB'){
            if(type === 'FB'){
                projectObj.project.mainTree.items[0].setExpanded(true);
                refreshNodes.push(projectObj.project.mainTree.items[0]);
            }
            return  function expandedControl(nodes, depth){
                let bType = type === 'FB' ? billType.FB : billType.DXFY;
                for(let node of nodes){
                    let nodeDepth = node.depth();
                    if(nodeDepth <= depth){
                        let expanded = nodeDepth === depth && !node.children[0] || nodeDepth < depth && node.children[0] && node.children[0].data.type === bType ? true : false;
                        node.setExpanded(expanded);
                        refreshNodes.push(node);
                        if(nodeDepth < depth){
                            expandedControl(node.children, depth);
                        }
                    }
                }
            }
        }
        else if(type === 'FX' || type === 'ZM' || type === 'ZD'){
            return  function expandedControl(nodes){
                for(let node of nodes){
                    if(type !== 'FX' || node.sourceType === projectObj.project.Bills.getSourceType()){
                        let expanded = true;
                        if(type === 'FX'){
                            expanded =  !node.children[0] || node.children[0] && node.children[0].sourceType === projectObj.project.Bills.getSourceType() ? true : false;
                        }
                        else if(type === 'ZM'){
                            expanded =  !node.children[0] || node.children[0] && node.children[0].sourceType !== projectObj.project.ration_glj.getSourceType() ? true : false;
                        }
                        node.setExpanded(expanded);
                        refreshNodes.push(node);
                        expandedControl(node.children);
                    }
                }
            }
        }
    }
    getExpandedController()(nodes, depth);
    let sheet = projectObj.mainSpread.getActiveSheet();
    TREE_SHEET_HELPER.massOperationSheet(sheet, function () {
        TREE_SHEET_HELPER.refreshNodesVisible(refreshNodes, projectObj.mainSpread.getActiveSheet(), true)
    });
};
//导入下拉
$('#importSpan').click(function () {
    $('[data-toggle="tooltip"]').tooltip('hide');
    let toggle = $('#importDropDown').attr('data-toggle');
    if (toggle) {
        $('#importDropDown').removeAttr('data-toggle');
    }
    $('#importDropDown').dropdown('toggle');
    setTimeout(function () {
        $('#importDropDown').attr('data-toggle', 'dropdown');
    }, 100);
});
$('#importDropDown').click(function () {
    $('[data-toggle="tooltip"]').tooltip('hide');
});
//导出接口下拉
$('#exportSpan').click(function () {
    $('[data-toggle="tooltip"]').tooltip('hide');
    let toggle = $('#exportSpan>a').attr('data-toggle');
    if (toggle) {
        $('#exportSpan>a').removeAttr('data-toggle');
    }
    $('#exportSpan>a').dropdown('toggle');
    setTimeout(function () {
        $('#exportSpan>a').attr('data-toggle', 'dropdown');
    }, 100);
});
$('#exportSpan>a').click(function () {
    $('[data-toggle="tooltip"]').tooltip('hide');
});
$('body').click(function () {
    //点击完后隐藏子菜单
   if ($('#subDisplay').is(':visible')) {
       $('#subDisplay').removeClass('show');
   }
});
let enterDisplayA = false;
//鼠标移到显示至，自动弹出子菜单
$('#displayA').click(function () {
    return false;
});
$('#displayA').mouseenter(function (e) {
    enterDisplayA = true;
    $('#subDisplay').addClass('show');
});
$('#displayA').mouseleave(function () {
    enterDisplayA = false;
});

let enterInterfaceDropdown = false;
$('#interface-dropdown').mouseenter(function () {
    enterInterfaceDropdown = true;
    $('#interface-dropdown-sub').addClass('show');
});
$('#interface-dropdown').mouseleave(function () {
    enterInterfaceDropdown = false;
});
$('#interface-dropdown').click(function() {
    return false;
});

let enterZLFB = false
$('#ZLFB_MENU').mouseenter(function () {
    enterZLFB = true;
    $('#ZLFB_MENU_sub').addClass('show');
});

$('#ZLFB_MENU').mouseleave(function () {
    enterZLFB = false;
});

$('#ZLFB_MENU').click(function() {
    return false;
});

$('#moreMenu > a').mouseenter(function () {
    if (!enterDisplayA) {
        $('#subDisplay').removeClass('show');
    }
    if (!enterInterfaceDropdown) {
        $('#interface-dropdown-sub').removeClass('show');
    }
    if(!enterZLFB){
        $('#ZLFB_MENU_sub').removeClass('show');
    }
});



$('#displayDXFY').click(function () {
   displayLevel(projectObj.project.mainTree.items, 0, 'DXFY')
});
//显示至一级分部
$('#displayFB1').click(function () {
   displayLevel(projectObj.project.mainTree.items[0].children, 1, 'FB');
});
//二级分部
$('#displayFB2').click(function () {
    displayLevel(projectObj.project.mainTree.items[0].children, 2, 'FB');
});
//三级分部
$('#displayFB3').click(function () {
    displayLevel(projectObj.project.mainTree.items[0].children, 3, 'FB');
});
//四级分部
$('#displayFB4').click(function () {
    displayLevel(projectObj.project.mainTree.items[0].children, 4, 'FB');
});
//分项
$('#displayFX').click(function () {
    displayLevel(projectObj.project.mainTree.items, null, 'FX');
});
//子目
$('#displayZM').click(function () {
    displayLevel(projectObj.project.mainTree.items, null, 'ZM');
});
//最底层
$('#displayZD').click(function () {
   displayLevel(projectObj.project.mainTree.roots, null, 'ZD');
});

$('#poj-set').on('show.bs.modal', function () {
    //建设项目-编制说明
    let compilationIVP = projectObj.project.property.compilationIllustrationProject ? projectObj.project.property.compilationIllustrationProject : '';
    $('#compilationIllustrationP textarea').val(compilationIVP);
    //单位工程-编制说明
    let compilationIV = projectObj.project.property.compilationIllustration ? projectObj.project.property.compilationIllustration : '';
    $('#compilationIllustration textarea').val(compilationIV);
    let setCalcFlag = function (obj, val, curFlag) {
        obj.val(val);
        if (val === curFlag) {
            obj.prop('checked', true);
        } else {
            obj.prop('checked', false);
        }
    }
    if (projectObj.project) {
        //江西重定义了leafBillGetFeeType的内容
        let ft = (projectObj.project.property.billsCalcMode !== undefined && projectObj.project.property.billsCalcMode !== null) ?
            projectObj.project.property.billsCalcMode : leafBillGetFeeType.rationContent;   // 广东默认取1不是0，但这里不动，防止这种情况：旧项目默认无值，按取0算的，你改成1了，计算结果会变。
        let zg = projectObj.project.property.zanguCalcMode !== undefined &&
                 projectObj.project.property.zanguCalcMode !== null ? projectObj.project.property.zanguCalcMode : zanguCalcType.common;
        setCalcFlag($('#rationContent'), leafBillGetFeeType.rationContent, ft);
        setCalcFlag($('#rationPriceConverse'), leafBillGetFeeType.rationPriceConverse, ft);
        setCalcFlag($('#rationPrice'), leafBillGetFeeType.rationPrice, ft);
        setCalcFlag($('#billsPrice'), leafBillGetFeeType.billsPrice, ft);
        setCalcFlag($('#zangu_common'), zanguCalcType.common, zg);
        setCalcFlag($('#zangu_gatherMaterial'), zanguCalcType.gatherMaterial, zg);

        let showAdjustPrice = projectObj.project.projSetting.glj_col?projectObj.project.projSetting.glj_col.showAdjustPrice:false;
        showAdjustPrice === true ? $("#tab_poj-settings-6").show():$("#tab_poj-settings-6").hide();
        projDisplayView.init();
        calcOptions.init();
    }
});

//恢复默认列设置
$('#recColSetting').click(function () {
    let libID = projectObj.project.property.colLibID ? projectObj.project.property.colLibID : null;
    if(!libID){
        alert('项目没有绑定标准列设置');
        return;
    }
    $(this).addClass('disabled');
    CommonAjax.post('/project/getDefaultColSetting', {libID: libID}, function (rstData) {
        if(!rstData || rstData.length === 0){
            alert('标准列设置没有数据');
            $('#recColSetting').removeClass('disabled');
            return;
        }
        let sheet = colSettingObj.settingSpread.getActiveSheet();
        SheetDataHelper.massOperationSheet(sheet, function () {
            for(let row = 0; row < sheet.getRowCount(); row++){
                sheet.setValue(row, 0, rstData.main_tree_col.cols[row].visible);
            }
        });
        $('#recColSetting').removeClass('disabled');
    }, function () {
        $('#recColSetting').removeClass('disabled');
    });
});
//恢复默认系统设置
$('#property_default').click(function () {
    let project = projectObj.project,
        projectID = project.ID();
    /*
    * 清除窗口比例缓存
    * */
    //清单精灵/指引窗口比例
    removeLocalCache('stdBillsGuidanceTabmainWidth');
    removeLocalCache('stdBillsGuidanceTabmainSideWidth');
    // 清单展开状态
    window.sessionStorage.removeItem('stdBillsGuidanceExpState');
    //定额库窗口比例
    removeLocalCache('stdRationTabmainWidth');
    removeLocalCache('stdRationTabmainSideWidth');
    removeLocalCache('dedeTopDivHeight');
    removeLocalCache('dedeBottomDivHeight');
    //查找定位窗口比例
    removeLocalCache('locateTabmainWidth');
    removeLocalCache('locateTabmainSideWidth');
    removeLocalCache('locatelocateTopDivHeight');
    removeLocalCache('locatelocateBottomDivHeight');
    //块模板库窗口比例
    removeLocalCache('kmbkkmbkTopDivHeight');
    removeLocalCache('kmbkkmbkMidDivHeight');
    removeLocalCache('kmbkkmbkBottomDivHeight');
    //主界面窗口比例
    removeLocalCache('mainVerticaltop_divHeight');
    removeLocalCache('mainVerticalbottom_divHeight');
    //造价书下方-人材机和项目特征文本
    removeLocalCache('subRcjsubSpreadWidth');
    removeLocalCache('subRcjitemTextDivWidth');
    //造价书下方-子目换算下调整状态和辅助值
    removeLocalCache('subRcjitemTextDivWidth');
    removeLocalCache('subRcjitemTextDivWidth');
    //造价书下方-特征及内容窗口比例
    removeLocalCache('subZmhscoeSpreadWidth');
    removeLocalCache('subZmhsassDivWidth');
    //人材机汇总窗口比例
    removeLocalCache('projectGljprojectGljTopHeight');
    removeLocalCache('projectGljprojectGljBottomHeight');
    //补充人材机库
    removeLocalCache('compleGLjleftContentWidth');
    removeLocalCache('compleGLjmidContentWidth');
    removeLocalCache('compleGLjrightContentWidth');
    //补充定额库
    removeLocalCache('compleRationleftContentWidth');
    removeLocalCache('compleRationmainContentWidth');
    removeLocalCache('compleRationzmhsContentWidth');
    removeLocalCache('compleRationrationItemsSheetHeight');
    removeLocalCache('compleRationsubContentHeight');
    removeLocalCache('compleRationmainSpreadHeight');
    removeLocalCache('compleRationcontentSpreadHeight');

    //在后台恢复一些设置
    CommonAjax.post('/pm/api/defaultSettings', {user_id: userID, projectID: projectID}, function (rstData) {
        window.location.href = `/main?project=${projectID}`;
    });
});
$('#property_ok').click(function () {
    let project = projectObj.project,
        projectID = project.ID(),
        properties = {},
        options = {},
        labourCoes = {},
        rations = [],
        bills = [],

        mixDatas = {
            projectID: projectID,
            updateType: 'update',
            properties: properties,
            options: options,
            labourCoes: labourCoes,
            rations: rations,
            bills: bills
        },

        reCalcBills = false,
        reCalcRations = false;

    let b = parseInt($("input[name='calcFlag']:checked").val());
    if (b !== project.property.billsCalcMode) {
        properties['property.billsCalcMode'] = b;
        project.property.billsCalcMode = b;
        reCalcBills = true;
    };

    let zg = parseInt($("input[name='zangu']:checked").val());
    if (zg !== project.property.zanguCalcMode) {
        properties['property.zanguCalcMode'] = zg;
        project.property.zanguCalcMode = zg;
        reCalcRations = true;
    };

    //基本信息
    if(basicInfoView.toUpdate(basicInfoView.orgDatas, basicInfoView.datas)){
        let saveData = basicInfoView.toSaveDatas(basicInfoView.datas);
        projectObj.project.property.basicInformation = saveData;
        properties['property.basicInformation'] = saveData;
    }
    //建设项目-编制说明
    let compilationIllustrationP = $('#compilationIllustrationP textarea').val();
    if (compilationIllustrationP !== project.property.compilationIllustrationProject) {
        properties['property.compilationIllustrationProject'] = compilationIllustrationP;
        project.property.compilationIllustrationProject = compilationIllustrationP;
    }
    //工程特征
    if(projFeatureView.toUpdate(projFeatureView.orgDatas, projFeatureView.datas)){
        let saveData = projFeatureView.toSaveDatas(projFeatureView.datas);
        projectObj.project.property.projectFeature = saveData;
        properties['property.projectFeature'] = saveData;
    }
    // 清单限价
    const maxPriceRate = $('#max-price-rate') && +$('#max-price-rate').val();
    if (commonUtil.isNumber(maxPriceRate) && maxPriceRate !== projectObj.project.property.maxPriceRate) {
        properties['property.maxPriceRate'] = maxPriceRate;
    }
    const minPriceRate = $('#min-price-rate') && +$('#min-price-rate').val();
    if (commonUtil.isNumber(minPriceRate) && minPriceRate !== projectObj.project.property.minPriceRate) {
        properties['property.minPriceRate'] = minPriceRate;
    }
    //清单工程量精度
    let newBillsDecimalDatas = billsDecimalView.toBillsDecimalDatas(billsDecimalView.cache);
    if(billsDecimalView.toUpdate(billsQuanDecimal.datas, newBillsDecimalDatas)){
        billsQuanDecimal.datas = newBillsDecimalDatas;
        reCalcBills = true;
        properties['property.billsQuantityDecimal'] = newBillsDecimalDatas;
    }
    //小数位数
    let updateDecimal = m_getDecimalData($('input', '#poj-settings-decimal'));
    if(toUpdateDecimal(decimalObj, updateDecimal)) {
        let frChanged = decimalObj.feeRate != updateDecimal.feeRate;
        setDecimal(decimalObj, updateDecimal);
        if (frChanged) {
            project.calcProgram.compileAllTemps()
        }
        reCalcRations = true;
        reCalcBills = true;
        properties['property.decimal'] = updateDecimal;
    }
    // 呈现选项
    projDisplayView.updateChecking(properties);
    //列设置（独立逻辑，只是通过项目属性确定按钮触发）
    if(colSettingObj.dataChanged()){
        colSettingObj.updateColSetting();
    }
    //单位工程-编制说明
    let compilationIllustration = $('#compilationIllustration textarea').val();
    if (compilationIllustration !== project.property.compilationIllustration) {
        properties['property.compilationIllustration'] = compilationIllustration;
        project.property.compilationIllustration = compilationIllustration;
    }
    //系统选项
    if(optionsOprObj.needToSaveGeneralOpts()){
        let v1 = optionsOprObj.rationQuanACToBillsQuan.prop('checked'),
            v2 = optionsOprObj.rationQuanACToRationUnit.prop('checked');
        options.updateData = {
            rationQuanACToBillsQuan: v1,
            rationQuanACToRationUnit: v2
        };
    }

    if(calcOptions.updateChecking(properties)){
        reCalcRations = true;
    }

    // 人工系数
    if (labourCoeView.needSave()){
        let libID = $("#std_labour_coe_files").children("option:selected").val();
        let libName = $("#std_labour_coe_files").children("option:selected").text();

        labourCoes.updateData = {libID: libID, libName: libName, newItemArr: labourCoeView.needUpdateDatas};
        project.labourCoe.refreshData(labourCoes.updateData);  // 全编译所用到的人工系数来自project.labourCoe，所以必须先刷新project.labourCoe
        project.calcProgram.compileAllTemps();
        reCalcRations = true;
        reCalcBills = true;
    };
    // 重新计算树节点
    let changedNodes = [];
    if (reCalcRations)    // 定额动，全部计算。算完先不存储，和后面的数据一起提交，一次通讯。
        changedNodes = project.calcProgram.calcAllNodes(calcAllType.catAll)
    else if (reCalcBills)  // 清单动，可以只计算清单。
        changedNodes = project.calcProgram.calcAllNodes(calcAllType.catBills);
    if (changedNodes.length > 0) {
        for (let node of changedNodes){
            let data = calcTools.cutNodeForSave(node);
            if (node.sourceType == 'ration') rations.push(data)
            else if (node.sourceType == 'bills') bills.push(data);
        };
    };

    // for test.
/*    console.log(mixDatas);
    return; */
    function hasMixData() {
        return Object.keys(mixDatas.properties).length > 0 || mixDatas.options.updateData ||
            mixDatas.labourCoes.updateData || mixDatas.rations.length > 0 || mixDatas.bills.length > 0;
    }

    function needToReload(mixDatas){
        if(Object.keys(mixDatas.labourCoes).length > 0){
            return true;
        }
        if(Object.keys(mixDatas.properties).length > 0){
            if(mixDatas.properties.hasOwnProperty('property.billsCalcMode') ||
                mixDatas.properties.hasOwnProperty('property.zanguCalcMode') ||
                mixDatas.properties.hasOwnProperty('property.calcOptions')||
                mixDatas.properties.hasOwnProperty('property.billsQuantityDecimal')||
                mixDatas.properties.hasOwnProperty('property.decimal')||
                mixDatas.properties.hasOwnProperty('property.displaySetting')){
                return true;
            }
        }
        return false;
    }

    if(hasMixData()){
        CommonAjax.post('/pm/api/updateMixDatas', {user_id: userID, mixDataArr: mixDatas}, function (rstData) {
            //需要重载页面
            if(needToReload(mixDatas)){
                window.location.href = '/main?project=' + projectID;
            }
            else{
                if(mixDatas.properties.hasOwnProperty('property.maxPriceRate')){
                    projectObj.project.property.maxPriceRate = maxPriceRate;
                }
                if(mixDatas.properties.hasOwnProperty('property.minPriceRate')){
                    projectObj.project.property.minPriceRate = minPriceRate;
                }
                if(mixDatas.properties.hasOwnProperty('property.basicInformation')){
                    basicInfoView.orgDatas = basicInfoView.toViewDatas(mixDatas.properties['property.basicInformation']);
                }
                if(mixDatas.properties.hasOwnProperty('property.projectFeature')){
                    projFeatureView.orgDatas = projFeatureView.toViewDatas(mixDatas.properties['property.projectFeature']);
                }
                if(mixDatas.options && mixDatas.options.updateData){
                    let v1 = mixDatas.options.updateData['rationQuanACToBillsQuan'],
                        v2 = mixDatas.options.updateData['rationQuanACToRationUnit'];
                    optionsOprObj.updateOptions(optionsOprObj.options, {type: optionsOprObj.optionsTypes.GENERALOPTS, opt: 'rationQuanACToBillsQuan', value: v1});
                    optionsOprObj.updateOptions(optionsOprObj.options, {type: optionsOprObj.optionsTypes.GENERALOPTS, opt: 'rationQuanACToRationUnit', value: v2});
                }
            }
        });
    }
});

function testShow() {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, parent = selected.parent;
    var showinfo = "<label>确认要删除当前选中行吗？</label>";
    var showN = false;
    var cancelText = "否";
    if(selected.sourceType == project.Bills.getSourceType()&&selected.data.type==billType.FB&&selected.children.length>0){//选中的是分部，并且有子项
        if(isSingleSelect()||selectionChecking()){
            showinfo = "<label>是否删除其下的子项？</label><br><label>【是】则删除分部行及其下的所有子项，</label><br><label>【否】则仅删除当前分部行，子项保留，</label><br><label>【取消】则取消删除</label>";
            showN = true;
            cancelText = "取消";
        }
    }
    $('#delete_showinfo').html(showinfo);
    showN==true? $('#deleteN').show():$('#deleteN').hide();
    $('#deleteCancel').text(cancelText);

    function selectionChecking() {
        let selection = projectObj.mainSpread.getActiveSheet().getSelections()[0];
        let mainTreeMap = {};
        for(let i =0;i<selection.rowCount;i++){
            let tem_node = controller.tree.items[selection.row+i];
            if(i==0){//第一个直接添加;
                mainTreeMap[tem_node.getID()] = tem_node;
            }else {
                project.Bills.setNodeToMap(tem_node,mainTreeMap);
            }
        }
        let nodes = changeMapToArray(mainTreeMap);
        if(nodes.length==1){
            return true
        }
        return false;
    }
}

$('#delete_row').on('show.bs.modal', function (e) {//这里用show,在shown之前调用，页面不会出现按钮闪现的情况
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, parent = selected.parent;
    var showinfo = "<label>确认要删除当前选中行吗？</label>";
    var showN = false;
    var cancelText = "否";
    if(selected.sourceType == project.Bills.getSourceType()&&selected.data.type==billType.FB&&selected.children.length>0){//选中的是分部，并且有子项
        if(isSingleSelect()||selectionChecking()){
            showinfo = "<label>是否删除其下的子项？</label><br><label>【是】则删除分部行及其下的所有子项，</label><br><label>【否】则仅删除当前分部行，子项保留，</label><br><label>【取消】则取消删除</label>";
            showN = true;
            cancelText = "取消";
        }
    }else if(isSingleSelect()&&mbzm_obj.hasReferenceRation(selected)){//“有模板关联的定额”右键点击删除，弹窗提示“删除主子目时将删除对应的关联子目，是否继续？  是 否” (只有单选中一条定额并且是有模板关联的定额)
        showinfo = "<label>删除主子目时将删除对应的关联子目，是否继续？</label>";
    }
    $('#delete_showinfo').html(showinfo);
    showN==true? $('#deleteN').show():$('#deleteN').hide();
    $('#deleteCancel').text(cancelText);

    function selectionChecking() {
        let selection = projectObj.mainSpread.getActiveSheet().getSelections()[0];
        let mainTreeMap = {}, nodes = [];
        for(let i =0;i<selection.rowCount;i++){
            let tem_node = controller.tree.items[selection.row+i];
            if(i==0){//第一个直接添加;
                mainTreeMap[tem_node.getID()] = tem_node;
            }else {
                project.Bills.setNodeToMapAndArray(tem_node,mainTreeMap,nodes);
            }
        }
        if(nodes.length==1){
            return true
        }
        return false;
    }
});

function changeMapToArray(map) {
    let newArray = [];
    for(let key in map){
        newArray.push(map[key]);
    }
    return newArray;
}


$('#deleteY').click(function () { //正常删除，级联删除子项
    let project = projectObj.project;
    project.Bills.deleteSelectedNodes();
});

$('#deleteN').click(function () {//不删除子项
    let controller = projectObj.mainController, project = projectObj.project;
    let selected = controller.tree.selected, parent = selected.parent;
    if(selected){
        let preNode = selected.preSibling;
        let nextNode = selected.nextSibling;
        if(preNode){//有前兄弟
            if(preNode.children.length>0&&preNode.children[0].data.type != selected.children[0].data.type){//并且前兄弟子项和焦点行子项类别不同。
                alert("删除分部会导致分部和分项同级，不允许该操作！");
                return;
            }
        }else if(nextNode){
            if(nextNode.data.type != selected.children[0].data.type){
                alert("删除分部会导致分部和分项同级，不允许该操作！ ");
                return;
            }
        }
        project.Bills.singleDeleteBills(selected,controller);
    }
});

function isSingleSelect() {//是否选中造价书中的单行
    let selections = projectObj.mainSpread.getActiveSheet().getSelections();
    if (selections[0].rowCount == 1) {
        return true;
    }
    return false;
}
function ifCanDelete() {
    if (projectReadOnly) {
      return false;
    }
    let selections = projectObj.mainSpread.getActiveSheet().getSelections();
    let tree = projectObj.project.mainTree;
    let selected = projectObj.project.mainTree.selected;
    if(selections[0].rowCount==1){//选中单行
        return canDelete(selected);
    }else {
       return canDelete_m(selections[0]);
    }

    function canDelete(node,m_selection) {
        if (node) {
            if (node.sourceType === projectObj.project.Bills.getSourceType()) {
                if(node.data.type == billType.DXFY&&node.data.isAdd!=1){
                    return false;
                }
                if(projectObj.project.isBillsLocked()== true && projectObj.project.withinBillsLocked(node)){
                    return false;
                }
                if(projectObj.project.Bills.hasFlags(node)){
                    return false;
                }
            }
            if(m_selection!=true&&node.sourceType === projectObj.project.ration_glj.getSourceType()){//多选的时候不做这一项判断
                return false;
            }
            return true;
        } else {
            return false;
        }
    };

    function canDelete_m(selection) {
        for(let i =0;i<selection.rowCount;i++){
            if(tree.items[selection.row+i]==undefined||tree.items[selection.row+i]==null){
                return false;
            }
            if(i==0&&tree.items[selection.row].sourceType === projectObj.project.ration_glj.getSourceType()){
                return false
            }
            if(canDelete(tree.items[selection.row+i],true)==false){
                return false
            }
        }
        return true
    };
}

function canInsertRationNode(selected) {//判断是否能插入定额、量价、定额类型工料机, false 不能，true能
    if(!selected)
        return false;
    let project = projectObj.project;
    if(selected.sourceType == ModuleNames.bills && selected.data.type == billType.DXFY){
        return false
    }else if(!(project.Bills.isMeasure(selected)||project.Bills.isFBFX(selected))){
        return false
    }else if(selected.sourceType == ModuleNames.bills && selected.source.children.length > 0){
        return false
    }
    else {
        return true
    }
}

//导入类型（09表、广联达）
const uploadType = {general: 'general', lj: 'lj', gld: 'gld'};
let fileType = uploadType.lj;

$('#uploadLj').click(function () {
    $('#example-gld').hide();
    $('#example-general').show();
    fileType = uploadType.lj;
});
$('#uploadGld').click(function () {
    $('#example-general').hide();
    $('#example-gld').show();
    fileType = uploadType.gld;
});

let importJson = null;
//选择导入的excel文件
$('#customFile').change(function () {
   let file = $(this)[0];
   let excelFile = file.files[0];
    $('#uploadAlert').hide();
   if(excelFile) {
       let xlsReg = /xls$/g;
       if(excelFile.name && xlsReg.test(excelFile.name)){
           showUploadAlert(false, '请选择xlsx文件');
           $(this).val('');
           return;
       }
       $('.custom-file-label').text(`${file.files[0].name}`);
       $('#uploadAlert').hide();
       $.bootstrapLoading.start();
       $('#loadingPage').css('z-index', '2000');
       //前端解析excel数据
       if(importJson){
           importJson = null;
       }
       let excelIo = new GC.Spread.Excel.IO();
       let sDate = +new Date();
       excelIo.open(excelFile, function (json) {
           importJson = json;
           console.log(json);
           //读取各个表及表名
           importBills.setImportSheetsInfo(importJson.sheets);
           console.log(`解析Excel文件时间：${+new Date() - sDate}`);
           $.bootstrapLoading.end();
       }, function (e) {
           $.bootstrapLoading.end();
           alert(e.errorMessage);
       });
   }
});

//线上nginx请求体最大设置为100m
//从excel导入清单
$('#importConfirm').click(function () {
    let me = this;
    $(me).addClass('disabled');
    try{
        $.bootstrapLoading.start();
        $('#loadingPage').css('z-index', '2000');
        let formData = new FormData();
        let file = $('#customFile')[0];
        if(file.files.length <= 0){
            throw '未选择文件';
        }
        let projectID = scUrlUtil.GetQueryString('project');
        if(!projectID || projectID <= 0){
            throw '项目数据出错';
        }
        let sDate = +new Date();
        formData.append('projectID', projectID);
        //要去匹配的清单库（第一个）
        let matchBillLibId = projectObj.project.projectInfo.engineeringInfo.bill_lib.length > 0 ? projectObj.project.projectInfo.engineeringInfo.bill_lib[0].id : null;
        formData.append('billsLibId', matchBillLibId);
        //选择的表及导入位置
        let importSheetsInfo = importBills.getImportSheetsInfo();
        if(importSheetsInfo.length === 0){
            throw '请勾选要导入的表';
        }
        let importSheets = importBills.getImportSheets(importJson.sheets, importSheetsInfo, fileType);
        console.log(`importSheets`);
        console.log(importSheets);
        let invalidSheetsInfo = importSheets.invalidSheets.join('、');
        //获取同类表的有效数据
        let importBillsData = importBills.getImportData(importSheets.validSheets, projectID);
        if(!importBills.excelHasValidBills(importBillsData)){
            throw 'excel无有效数据'
        }
        let compressData = LZString.compressToUTF16(JSON.stringify(importBillsData));
        formData.append('compressData', compressData);
        let eDate = +new Date();
        console.log(`解析excel数据时间：${eDate - sDate}`);
        $.ajax({
            url: '/bills/import',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                if (response.err === 0) {
                    if(invalidSheetsInfo !== ''){
                        alert(`${invalidSheetsInfo}，导入失败。`);
                    }
                    // 成功则关闭窗体
                    $('#import').modal("hide");
                    //更新前端
                    doAfterImport(response.data);
                    if($.bootstrapLoading.isLoading()){
                        $.bootstrapLoading.end();
                    }
                } else {
                    const message = response.msg !== undefined ? response.msg : '上传失败!';
                    $.bootstrapLoading.end();
                    alert(message);
                }
                $(me).removeClass('disabled');
            },
            error: function(jqXHR){
                alert(`与服务器通信发生错误${jqXHR.status} ${jqXHR.statusText}`);
                $.bootstrapLoading.end();
                $(me).removeClass('disabled');
            }
        });
    }
    catch (err){
        console.log(err);
        showUploadAlert(false, err);
        $(me).removeClass('disabled');
        if($.bootstrapLoading.isLoading()){
            $.bootstrapLoading.end();
        }
    }
});

function showUploadAlert(success, msg){
    if(!success){
        $('#uploadAlert').removeClass('alert-success');
        $('#uploadAlert').addClass('alert-danger');
    }
    else{
        $('#uploadAlert').removeClass('alert-danger');
        $('#uploadAlert').addClass('alert-success');
    }
    $('#uploadAlert').text(msg);
    $('#uploadAlert').show();
}
//导入清单到一个固定行位置后，更新数据
function doAfterImportPosition(positionData){
    let nodes = projectObj.project.mainTree.nodes;
    let bills_datas = projectObj.project.Bills.datas;
    let ration_datas = projectObj.project.Ration.datas;
    let quantity_detail_datas = projectObj.project.quantity_detail.datas;
    let ration_glj_datas = projectObj.project.ration_glj.datas;
    let ration_coe_datas = projectObj.project.ration_coe.datas;
    let ration_install_datas = projectObj.project.ration_installation.datas;
    let delNodes = [];
    for(let billID of positionData.remove.bill){
        if(nodes['id_' + billID]){
            delNodes.push(nodes['id_' + billID]);
        }
        //清除清单数据
        _.remove(bills_datas, {ID: billID});
        //清除清单工程量明细数据
        _.remove(quantity_detail_datas, {billID: billID});
    }
    for(let rationID of positionData.remove.ration){
        //清除定额数据
        _.remove(ration_datas, {ID: rationID});
        //清除定额下的相关数据
        _.remove(ration_glj_datas, {rationID: rationID});
        _.remove(ration_coe_datas, {rationID: rationID});
        _.remove(ration_install_datas, {rationID: rationID});
        _.remove(quantity_detail_datas, {rationID: rationID});

    }
    //删除节点
    if(delNodes.length > 0){
        //通过固定清单获得删除节点的起始行索引
        let beginRow = null;
        if(positionData.fixedBill){
            let fixedNode = nodes['id_' + positionData.fixedBill.ID];
            if(fixedNode){
                beginRow = projectObj.project.mainTree.items.indexOf(fixedNode) + 1;
            }
        }
        //删除主树节点
        projectObj.mainController.m_delete(delNodes, beginRow);
        //删除清单树节点
        let delIdNodes = [];
        for(let delNode of delNodes){
            delIdNodes.push(delNode.source);
        }
        projectObj.project.Bills.tree.m_delete(delIdNodes);
    }
    if(positionData.insert.bill.length > 0){
        //设置flagsIndex
        for(let insertBill of positionData.insert.bill){
            insertBill.flagsIndex = {};
            if (insertBill.flags) {
                insertBill.flags.forEach(function (flag) {
                    insertBill.flagsIndex[flag.fieldName] = flag;
                });
            }
        }
        //插入清单节点
        projectObj.project.Bills.tree.insertByDatas(positionData.insert.bill);
        projectObj.project.Bills.datas.push(...positionData.insert.bill);
        //插入主树节点
        let newNodes = projectObj.project.mainTree.insertByDatas(positionData.insert.bill);
        for(let node of newNodes){
            node.source = projectObj.project.Bills.tree.nodes['id_' + node.getID()];
            node.data = node.source.data;
            node.sourceType = projectObj.project.Bills.getSourceType();
        }
        ProjectController.syncDisplayNewNodes(projectObj.mainController, newNodes);
    }
    if (positionData.insert.ration.length) {
        const rationNodes = [];
        positionData.insert.ration.forEach(ration => {
            projectObj.project.Ration.datas.push(ration);
            const rationNode = projectObj.project.mainTree.insert(ration.billsItemID, -1, ration.ID);
            rationNode.source = ration;
            rationNode.sourceType = projectObj.project.Ration.getSourceType();
            rationNode.data = ration;
            rationNodes.push(rationNode);
        });
        ProjectController.syncDisplayNewNodes(projectObj.mainController, rationNodes);
    }
}
//导入后更新操作
function doAfterImport(resData){
    if(resData && resData.length > 0){
        for(let positionData of resData){
            doAfterImportPosition(positionData);
        }
        //如果清单未锁定，导入后锁定清单
        /*if(!projectObj.project.projectInfo.property.lockBills){
            $("a[name='lockBills']").click();
        }*/
        $.bootstrapLoading.end();
        //重算
        projectObj.project.calcProgram.calcAllNodesAndSave(calcAllType.catAll, function () {
            projectObj.project.projectGLJ.loadData(function () {
                $.bootstrapLoading.end();
            });
        });
    }
}
//下载导入清单示例文件
$('#uploadExample-general').click(function () {
    window.location.href = `/bills/downloadExamp?type=${uploadType.general}`;
});
$('#uploadExample').click(function () {
    window.location.href = `/bills/downloadExamp?type=${fileType === uploadType.lj ? uploadType.lj : uploadType.gld}`;
});
$('#uploadExample-lj').click(function () {
    window.location.href = `/bills/downloadExamp?type=${uploadType.lj}`;
});
$('#uploadExample-gld').click(function () {
    window.location.href = `/bills/downloadExamp?type=${uploadType.gld}`;
});

$(function () {
    //清空导入清单选择文件
    $('#import').on('show.bs.modal', function(){
        $('#customFile').val('');
        $('#uploadAlert').hide();
        $('.custom-file-label').text(`请选择上传文件`);
    });

    $('#import').on('hidden.bs.modal', function () {
        //恢复选择表高度
        $('#uploadSheets').height('');
        $('#uploadSheets').hide();
        $('#uploadSheetsHead').hide();
    });

   /* $("#billsSpread").mouseover(function(){
        spreadAutoFocus(projectObj.mainSpread,subSpread);
    });

    $("#subSpread").mouseover(function(){
        spreadAutoFocus(subSpread,projectObj.mainSpread);
    });
*/



    $("#paste_confirm").click(function (){
        let selected = projectObj.project.mainTree.selected;
        let blockData = BlockController.getBlockData();
        let position = $("input[name='pastePositionRadio']:checked").val();
        BlockController.confirmPaste(blockData,selected,position);
        $("#pastePosition").modal("hide");

    });

    $("#div_createBlocks").on('show.bs.modal', function(){
        function getBlockCategoriesHtml(Categories) {
            let result = '';
            if (Categories.length <= 0) return result;

            for (let c of Categories){
                result += '<option value="'+ c.data.ID +'">'+ c.data.nodeName +'</option>';
            };
            return result;
        };

        let sHtml = getBlockCategoriesHtml(blockLibObj.getCategories());
        $("#select_block_category").html(sHtml);
        $("#select_block_category")[0].selectedIndex = 0;
        $('#ckb_block_exist_cover').prop("checked", false);
    });

    $("#div_cloneOptions").on('show.bs.modal', function(){
        let s = '';
        switch (blockLibObj.cloneType) {
            case 1:
                s = '一对一克隆';
                break;
            case 2:
                s = '一对多克隆';
                break;
            case 3:
                s = '多对多克隆';
                break;
        }
        s = `<span style='color:red;'>${s}</span>`;
        $('#clone_option_title').html(`快速组价 (${s})`);
        $('#clone_option_code').prop("checked", true);
        $('#clone_option_name').prop("checked", false);
        $('#clone_option_unit').prop("checked", true);
        $('#clone_option_quantity').prop("checked", true);
        $('#clone_option_cover').prop("checked", true);
    });

    $("#btn_block_createBlocks").click(async function () {
        if ($("#select_block_category")[0].options.length < 1) return;
        let cID = $("#select_block_category").val();
        let selected = projectObj.project.mainTree.selected;
        let cover = $('#ckb_block_exist_cover').prop("checked");
        async function createBlocks(aNode, categoryID){
            async function createBlock(node) {
                if (node.data.name == undefined || node.data.name == '') return;  // 清单名称为空，不生成块模板文件
                if (node.children.length == 0) return;
                // 封装成伟城的块文件格式，直接调用伟城接口（定额这里的业务太多太庞杂，不要再重做一遍，尽量共用，维护代价小）
                // 块文件要构建自己的树结构，所以也有自己的一部分数据。两种结构揉合在一起，显得有点杂乱，但利大于弊。
                let vBlock_WC = {
                    compilationID: projectObj.project.projectInfo.compilation,
                    firstNodeType: node.data.type,
                    isFBFX: projectObj.project.Bills.isFBFX(node),
                    copyTime: +new Date(),
                    datas: []
                };
                let ration_glj_Map = _.groupBy(projectObj.project.ration_glj.datas, 'rationID');
                vBlock_WC.datas.push(BlockController.getNodeDatas(node, ration_glj_Map));
                vBlock_WC = JSON.parse(JSON.stringify(vBlock_WC));
                const unitFee = (node.data.feesIndex && node.data.feesIndex.common) ? node.data.feesIndex.common.unitFee : 0;
                let fileName = node.data.code + ' ' + node.data.name + ' ' + node.data.unit + ' ' + unitFee;
                fileName = fileName.replace(/^\s+|\s+$/g, "");    // 只去两头空格

                let extN = blockLibObj.getSameNameNode(fileName);
                if (extN){
                    if (cover) blockLibObj.assignData(extN, vBlock_WC);
                }
                else
                    await blockLibObj.newNode(2, fileName, categoryID, vBlock_WC);
            };

            async function createRecursion(node){
                if (!node) return;

                if (calcTools.isLeafBill(node)) await createBlock(node);

                if (node.firstChild()) await createRecursion(node.firstChild());
                if (node.nextSibling) await createRecursion(node.nextSibling);
            };

            if (calcTools.isLeafBill(aNode))
               await createBlock(aNode)
            else
               await createRecursion(aNode.firstChild());
        };

        await createBlocks(selected, cID);
        blockLibObj.loadDetailDatas(blockLibObj.mainTree.selected);
        $("#div_createBlocks").modal("hide");
    });

    $("#btn_block_clone_ok").click(async function () {
        let projectNode = projectObj.project.mainTree.selected;
        let block = blockLibObj.mainTree.selected;
        let options = {};
        if ($('#clone_option_code').prop("checked")) options.checkCode = true;
        if ($('#clone_option_name').prop("checked")) options.checkName = true;
        if ($('#clone_option_unit').prop("checked")) options.checkUnit = true;
        if ($('#clone_option_zeroQuantity').prop("checked")) options.zeroQuantity = true;
        if ($('#clone_option_cover').prop("checked")) options.overwriteRations = true;

        let nodes = [];
        let calcNodes = [];
        switch (blockLibObj.cloneType) {
            case 1:
                nodes = await blockLibObj.oneToOneClone(projectNode, block, options);
                calcNodes = calcNodes.concat(nodes[1]);
                break;
            case 2:
                let bills = calcTools.getLeafBills(projectNode);
                for (let bill of bills){
                    calcTools.forceSelect(bill);
                    nodes = await blockLibObj.oneToOneClone(bill, block, options);
                    calcNodes = calcNodes.concat(nodes[1]);
                };
                break;
            case 3:
                let mtmBills = calcTools.getLeafBills(projectNode);
                let mtmBlocks = blockLibObj.mainTree.selected.children;
                for (let mtmBill of mtmBills){
                    for (let mtmBlock of mtmBlocks){
                        calcTools.forceSelect(mtmBill);
                        nodes = await blockLibObj.oneToOneClone(mtmBill, mtmBlock, options);
                        calcNodes = calcNodes.concat(nodes[1]);
                    };
                };
                break;
        }
        if(calcNodes.length > 0){
            // projectObj.project.calcProgram.calcNodesAndSave(calcNodes, function () {
            //     installationFeeObj.calcInstallationFee();
            // });

            projectObj.project.calcProgram.calcNodesAndSave(calcNodes, async function () {
                installationFeeObj.calcInstallationFee();
                await OVER_HEIGHT.reCalcOverHeightFee();
                await itemIncreaseFeeObj.calcItemIncreaseFeeByNodes(nodes[0]);
            });
        }
    });


    function spreadAutoFocus(spread,relateSpread) {
        if(relateSpread&&relateSpread.getActiveSheet().isEditing()){//关联的spread不在编辑状态的情况下，才自动获得焦点;
            return;
        }else {
            spread?spread.focus():'';
        }
    }
    //项目为只读
    if(projectReadOnly){
        disableTools();
    }
});

//项目只读，处理不可操作的工具栏
function disableTools(){
    //造价书按钮
    $('#insertRation').addClass('disabled');
    $('#delete').addClass('disabled');
    $('#upLevel').addClass('disabled');
    $('#downLevel').addClass('disabled');
    $('#upMove').addClass('disabled');
    $('#downMove').addClass('disabled');
    $('#ZLFB_btn').addClass('disabled');
    //$('#switchTznr').addClass('disabled');
    $('#uploadLj').addClass('disabled');
    $('#uploadGld').addClass('disabled');
    $('a[name="lockBills"]').addClass('disabled');
    //关于计算
    $('#poj-settings-4').find('input').prop('disabled', 'disabled');
    //小数位数
    $('#poj-settings-decimal').find('input').prop('disabled', 'disabled');
    // 清单限价
    $('.limit-price-input').prop('disabled', 'disabled');
    //人工单价调整
    $('#std_labour_coe_files').prop('disabled', 'disabled');
    //呈现选项
    $('#display-setting').find('input').prop('disabled', 'disabled');
    $('#recColSetting').remove();
    //建设项目-编制说明
    $('#compilationIllustrationP textarea').prop('readOnly', true);
    //单位工程-编制说明
    $('#compilationIllustration textarea').prop('readOnly', true);
    //项目属性恢复默认系统设置
    $('#property_default').addClass('disabled');
    //项目属性确定
    $('#property_ok').addClass('disabled');
    // 清单指引
    $('#guidanceInsertRation').addClass('disabled');
    //清单精灵
    $('#elfInsertRation').addClass('disabled');
    $('#elfInsertSingle').addClass('disabled');
    //模板子目：应用、下一条
    $('#apply_mbzm').addClass('disabled');
    $('#next_mbzm').addClass('disabled');
    //特征及内容
    $('#add-rule').find('select').prop('disabled', 'disabled');
    $('#use-to-current').addClass('disabled');
    $('#use-to-all').addClass('disabled');
    $('.bottom-tools').remove();
    //导入
    $('#importConfirm').addClass('disabled');
    //导出
    $('#export-confirm').addClass('disabled');
    $('#exportSpan .dropdown-item').addClass('disabled');
    //选项
    $('#generalOpts1').prop('disabled', 'disabled');
    $('#generalOpts2').prop('disabled', 'disabled');
    //补充库编辑器
    $('.compleRationLib').addClass('disabled');
    $('.compleGljLib').addClass('disabled')
    //库
    //$('#stdBillsGuidanceTab').addClass('disabled');
    $('#stdBillsTab').addClass('disabled');
    //$('#stdRationTab').addClass('disabled');
    $('#blockLibTab').addClass('disabled');
    // 组价模板分享
    $('#btn_block_share').prop('disabled', true);
    //人材机汇总,选择其他、另存使用
    $('a[data-target="#change-unitFile"]').remove();
    $('a[data-target="#unitFile-save-as"]').remove();
    //费率,选择其他、另存使用、重选标准、统一设置相同参数
    $('a[data-target="#change-lv"]').remove();
    $('a[data-target="#copy-lv"]').remove();
    $('#standardSelect').prop('disabled', 'disabled');
    $('#cascadeSet').prop('disabled', 'disabled');
    $('#changeConfirm').prop('disabled', 'disabled');
    //计算程序标准
    $('#calcProgramFileSelect').prop('disabled', 'disabled');
    //调价
    $('#calcPriceOption').prop('disabled', 'disabled');
    $('#gljPriceTenderCoe').prop('readOnly', true);
    $('#tenderGLJQuantity').prop('disabled', 'disabled');
    $('#tenderRationQuantity').prop('disabled', 'disabled');
    $('#cleanTender').prop('disabled', 'disabled');
    $('#calcTender').prop('disabled', 'disabled');
}
//根据触发改变计算基数、费率弹出框
function changeCalcBaseFeeRate(toggle) {
    if(toggle === 'calcBase'){
        $('#mixedHeader').hide();
        $('#normalHeader').show();
        $('#calcBaseFeeRate').find('.modal-title').text('计算基数选择').show();
        $('#calcBaseFeeRate').find('.modal-body').find('button:first').hide();
        $('#calcBaseFeeRate').find('.modal-body').find('ul:first').show();
        $('#calcBaseExp').remove();
        let $textarea = $('<textarea>').attr('id', 'calcBaseExp').prop('rows', 2).addClass('form-control').css('resize', 'none');
        $('#expArea').prepend($textarea);
    }
    else if(toggle === 'feeRate'){
        $('#mixedHeader').hide();
        $('#normalHeader').show();
        $('#calcBaseFeeRate').find('.modal-title').text('费率选择').show();
        $('#calcBaseFeeRate').find('.modal-body').find('button:first').hide();
        $('#calcBaseFeeRate').find('.modal-body').find('ul:first').hide();
    }
    else if(toggle === 'commonTotalFee') {
        $('#normalHeader').hide();
        $('#mixedHeader').show();
        $('#calcBaseFeeRate').find('.modal-body').find('button:first').show();
        $('#calcBaseFeeRate').find('.modal-body').find('ul:first').show();
        $('#calcBaseExp').remove();
        let $textarea = $('<textarea>').attr('id', 'calcBaseExp').prop('rows', 2).addClass('form-control').css('resize', 'none');
        $('#expArea').prepend($textarea);
    }
}
//综合合价弹出计算基数费率确认
$('#calcBaseFeeRateConf').click(function () {
    let toggle = $(this).attr('toggle');
    if(!toggle || toggle !== 'commonTotalFee'){
        return
    }
    let calcBaseValue = calcBaseView.getInputExpr() ? calcBaseView.getInputExpr() : '';
    let selected = projectObj.project.mainTree.selected;
    let needToSave = false,validateFeeRate=false,cusFeeRate = false;
    if($("input[name='editFeeRateOptions']:checked").val() == "0"){ //等于”0“ 是自定义输入,删除费率关联ID，直接取值
        let newVal = null;
        if($("#customFeeRate").val() != ""){
            newVal = number_util.checkNumberValue( $("#customFeeRate").val(),getDecimal("feeRate"));
            if(newVal == null) return
        }
        selected.data.feeRateID = null;
        selected.data.feeRate = newVal;
        selected.changed = true;
        needToSave = true;
        cusFeeRate = true;
    }else {
        validateFeeRate =  feeRateObject.checkSelectedFeeRate();
    }
    if(calcBaseValue !== selected.data.calcBase){
        needToSave = true;
        selected.data.userCalcBase = calcBaseValue;
        selected.data.lockUnitPrice = null;
        projectObj.project.calcBase.calculate(selected);
    }
    if(validateFeeRate){
        feeRateObject.submitFeeRateFromBill();
    } else {
        if(calcBaseValue === calcBaseValue){
            $('#calcBaseFeeRate').modal('hide');
        }
    }
    //删除清单基数，要清空单价
    if (projectObj.project.calcBase.success && calcBaseValue === '') {
        calcTools.setFieldValue(selected, 'feesIndex.common.unitFee', 0);
    }
    if(!projectObj.project.calcBase.success && cusFeeRate==false){
        return;
    } else if((!validateFeeRate || selected.data.feeRateID === parseInt(feeRateObject.feeRateSelection.ID)) && needToSave) {
        projectObj.project.calcProgram.calcAndSave(selected);
        $('#calcBaseFeeRate').modal('hide');
    }
});

$('#menu_calc_program_manage').click(function () {
    $('#tab_calc_program_manage').click();
});
$('#menu_index_info').click(function () {
    $('#tab_index').click();
});

// 快速定位
const FastLocateType = {
    SUB_ENGINERRING: 'subEnginerring',
    MEASURE: 'measure',
    OTHER: 'other',
};
const locateCache = {
    [FastLocateType.SUB_ENGINERRING]: null,
    [FastLocateType.MEASURE]: null,
    [FastLocateType.OTHER]: null,
};

// 变更焦点行时，将焦点节点存至对应部分的locateCache中，用于快速定位功能
function locateToCache(node) {
    if (!node) {
        return;
    }
    if (node.isBelongToFlags([fixedFlag.SUB_ENGINERRING])) {
        locateCache[FastLocateType.SUB_ENGINERRING] = node;
    } else if (node.isBelongToFlags([fixedFlag.MEASURE])) {
        locateCache[FastLocateType.MEASURE] = node;
    } else if (node.isBelongToFlags([fixedFlag.OTHER])) {
        locateCache[FastLocateType.OTHER] = node;
    }
}

// “分项”、“措施”、“其他”，用于快速定位至对应部分上次的焦点行
function fastLocate(type) {
    let locatedNode;
    if (type === FastLocateType.SUB_ENGINERRING) {
        locatedNode = locateCache[type] || projectObj.project.mainTree.roots.find(node => node.getFlag() === fixedFlag.SUB_ENGINERRING);
    } else if (type === FastLocateType.MEASURE) {
        locatedNode = locateCache[type] || projectObj.project.mainTree.roots.find(node => node.getFlag() === fixedFlag.MEASURE);
    } else {
        locatedNode = locateCache[type] || projectObj.project.mainTree.roots.find(node => node.getFlag() === fixedFlag.OTHER);
    }
    if (locatedNode && locatedNode !== projectObj.project.mainTree.selected) {
        const locateRow = locatedNode.serialNo();
        const sheet = projectObj.mainController.sheet;
        projectObj.loadFocusLocation(locateRow, sheet.getActiveColumnIndex());
    }
}

$('#locate-sub').click(() => {
    fastLocate(FastLocateType.SUB_ENGINERRING);
});
$('#locate-measure').click(() => {
    fastLocate(FastLocateType.MEASURE);
});
$('#locate-other').click(() => {
    fastLocate(FastLocateType.OTHER);
});

// 清单限价
$('.limit-price-input').bind('input', function () {
    const limitType = $(this).data('limit');
    const orgVal = limitType === 'max'
        ? (projectObj.project.property.maxPriceRate || 0)
        : (projectObj.project.property.minPriceRate || 0);
    try {
        const val = $(this).val();
        if (isNaN(val)) {
            throw '只能输入两位小数数值！';
        }
        const splits = val.split('.');
        const decimalDigits = splits[1] && splits[1].length || 0;
        if (decimalDigits > 2) {
            const roundVal = scMathUtil.roundForObj(val, 2);
            $(this).val(roundVal);
        }
    } catch (err) {
        alert(err);
        $(this).val(orgVal);
    }
});

//导出接口
ExportView.exportListener();
