/**
 * Created by zhang on 2018/1/30.
 */
let installationFeeObj={
    rationInstallSheet:null,
    rationInstallData:[],
    rationInstallSetting:{
        header: [
            {headerName: "按统一设置", headerWidth: 80, dataCode: "unifiedSetting", dataType: "String",cellType: "checkBox"},
            {headerName: "费用项", headerWidth: 160, dataCode: "itemName", dataType: "String"},
            {headerName: "费用规则", headerWidth: 300, dataCode: "ruleId", hAlign: "left", dataType: "String",getText:'forRule'},
            {headerName: "编码", headerWidth: 70, dataCode: "code", hAlign: "left", dataType: "String"},
            {headerName: "基数", headerWidth: 150, dataCode: "base", hAlign: "left", dataType: "String",cellType:'comboBox',options:installSectionBase},
            {headerName: "费率（%）", headerWidth: 70, dataCode: "feeRate", hAlign: "right", dataType: "String"},
            {headerName: "人工（%）", headerWidth: 70, dataCode: "labour", hAlign: "right", dataType: "String"},
            {headerName: "材料（%）", headerWidth: 70, dataCode: "material", hAlign: "right", dataType: "String"},
            {headerName: "机械（%）", headerWidth: 70, dataCode: "machine", hAlign: "right", dataType: "String"},
            {headerName: "费用类型", headerWidth: 100, dataCode: "feeType", hAlign: "center", dataType: "String",cellType:'comboBox',options:installFeeType},
            {headerName: "记取位置", headerWidth: 200, dataCode: "position", hAlign: "left", dataType: "String",cellType:'selectButton',getText:'forPosition'}
        ],
        view: {
            lockColumns: [0,1,3,4,5,6,7,8,9,10]
        },
        getText:{
            forPosition:function (item,val) {//记取位置转换
               return installationFeeObj.getDisplayText(item);
            },
            forRule:function (item,val) {//
                let install_fee = projectObj.project.installation_fee;
                let impactRules =install_fee.getFeeRuleBySection({libID:item.libID,ID:item.sectionId});
                if(_.find(impactRules,{ID:val})){
                    return val;
                }else {
                    let feeRule = projectObj.project.installation_fee.getFeeRuleByID(item.libID,val);
                    if(feeRule){
                        return feeRule.rule;
                    }
                }
                return val;
            }
        }
    },
    feeItemSpread:null,
    feeItemSheet:null,
    feeItemData:null,
    feeItemSetting:{
        header: [
            {headerName: "计取", headerWidth: 50, dataCode: "isCal", dataType: "String",cellType: "checkBox"},
            {headerName: "费用项", headerWidth: 300, dataCode: "feeItem", hAlign: "left", dataType: "String"},
            {headerName: "费用类型", headerWidth: 100, dataCode: "feeType", hAlign: "center", dataType: "String",cellType:'comboBox',options:installFeeType},
            {headerName: "记取位置", headerWidth: 180, dataCode: "displayPosition", hAlign: "left", dataType: "String",cellType:'selectButton'}
        ],
        view: {
            lockColumns: [0,1]
        }
    },
    feeDetailSpread:null,
    feeDetailSheet:null,
    feeDetailData:null,
    feeDetailSetting: {
        header: [
            {headerName: "分册章节", headerWidth: 150, dataCode: "name", dataType: "String"},
            {headerName: "费用规则", headerWidth: 220, dataCode: "rule", hAlign: "left", dataType: "String",getText:'forRule'},
            {headerName: "编码", headerWidth: 70, dataCode: "code", hAlign: "left", dataType: "String"},
            {headerName: "基数", headerWidth: 80, dataCode: "base", hAlign: "left", dataType: "String",cellType:'comboBox',options:installSectionBase},
            {headerName: "费率（%）", headerWidth: 75, dataCode: "feeRate", hAlign: "right", dataType: "String"},
            {headerName: "人工（%）", headerWidth: 75, dataCode: "labour", hAlign: "right", dataType: "String"},
            {headerName: "材料（%）", headerWidth: 75, dataCode: "material", hAlign: "right", dataType: "String"},
            {headerName: "机械（%）", headerWidth: 75, dataCode: "machine", hAlign: "right", dataType: "String"},
            {headerName: "记取位置", headerWidth: 180, dataCode: "position", hAlign: "left", dataType: "String",cellType:'selectButton'}
        ],
        view: {
            lockColumns: [0, 2]
        },
        autoFit:true,
        getText:{
            forRule:function (item,val) {
                if(item.feeRuleId&&item.feeRuleId!=""){
                    let subRule = _.find(item.impactRules,{'ID':item.feeRuleId});
                    if(!subRule){
                        val = item.ruleName;
                    }
                }
                return val;
            }
        }
    },
    positionSpread:null,
    positionSheet:null,
    positionData:null,
    moreFeeRuleSpread:null,
    moreFeeRuleSheet:null,
    moreFeeRuleData:null,
    moreFeeRuleSetting:{
        header: [
            {headerName: "编码", headerWidth: 70, dataCode: "code", hAlign: "left", dataType: "String"},
            {headerName: "费用规则", headerWidth: 320, dataCode: "rule", hAlign: "left", dataType: "String"},
            {headerName: "基数", headerWidth: 140, dataCode: "base", hAlign: "center", dataType: "String"},
            {headerName: "费率（%）", headerWidth: 80, dataCode: "feeRate", hAlign: "right", dataType: "String"},
            {headerName: "人工（%）", headerWidth: 80, dataCode: "labour", hAlign: "right", dataType: "String"},
            {headerName: "材料（%）", headerWidth: 80, dataCode: "material", hAlign: "right", dataType: "String"},
            {headerName: "机械（%）", headerWidth: 80, dataCode: "machine", hAlign: "right", dataType: "String"}
        ],
        view: {
            lockColumns: [0,1,2,3,4,5,6]
        }
    },
    modifyFeeRuleSpread:null,
    modifyFeeRuleSheet:null,
    modifyFeeRuleData:null,
    modifyFeeRuleSetting:{
        header: [
            {headerName: "编码", headerWidth: 70, dataCode: "code", hAlign: "left", dataType: "String"},
            {headerName: "费用规则", headerWidth: 220, dataCode: "rule", hAlign: "left", dataType: "String"},
            {headerName: "基数", headerWidth: 80, dataCode: "base", hAlign: "left", dataType: "String",cellType:'comboBox',options:installSectionBase},
            {headerName: "费率（%）", headerWidth: 80, dataCode: "feeRate", hAlign: "right", dataType: "String"},
            {headerName: "其中人工（%）", headerWidth: 100, dataCode: "labour", hAlign: "right", dataType: "String"},
            {headerName: "其中材料（%）", headerWidth: 100, dataCode: "material", hAlign: "right", dataType: "String"},
            {headerName: "其中机械（%）", headerWidth: 100, dataCode: "machine", hAlign: "right", dataType: "String"},
            {headerName: "记取位置", headerWidth: 100, dataCode: "position", hAlign: "left", dataType: "String",cellType:'selectButton',getText:'forPosition'}
        ],
        view: {
            lockColumns: [0, 1]
        },
        getText:{
            forPosition:function (item,val) {//记取位置转换
                return installationFeeObj.getDisplayText(item);
            }
        },
        autoFit:true
    },
    modifyEditedObj:null,
    selectionTree:null,
    selectionTreeController:null,
    positionSetting:{
        "emptyRows":0,
        "headRows":1,
        "headRowHeight":[30],
        "defaultRowHeight": 21,
        "treeCol": 0,
        "cols":[
            {
                "width":250,
                "readOnly": true,
                "head":{
                    "titleNames":["编码"],
                    "spanCols":[1],
                    "spanRows":[1],
                    "vAlign":[1],
                    "hAlign":[1],
                    "font":["Arial"]
                },
                "data":{
                    "field":"code",
                    "vAlign":1,
                    "hAlign":0,
                    "font":"Arial"
                }
             },
            {
                "width":100,
                "readOnly": true,
                "head":{
                    "titleNames":["类别"],
                    "spanCols":[1],
                    "spanRows":[1],
                    "vAlign":[1],
                    "hAlign":[1],
                    "font":["Arial"]
                },
                "data":{
                    "field":"type",
                    "vAlign":1,
                    "hAlign":1,
                    "font":"Arial"
                }
            },
            {
                "width":250,
                "readOnly": true,
                "head":{
                    "titleNames":["名称"],
                    "spanCols":[1],
                    "spanRows":[1],
                    "vAlign":[1],
                    "hAlign":[1],
                    "font":["Arial"]
                },
                "data":{
                    "field":"name",
                    "vAlign":0,
                    "hAlign":0,
                    "font":"Arial"
                }
            },
            {
                "width":100,
                "readOnly": true,
                "head":{
                    "titleNames":["具体位置"],
                    "spanCols":[1],
                    "spanRows":[1],
                    "vAlign":[1],
                    "hAlign":[1],
                    "font":["Arial"]
                },
                "data":{
                    "field":"selected",
                    "vAlign":1,
                    "hAlign":1,
                    "font":"Arial",
                    "cellType":function (node) {
                        if(node.data.canSelect == true){
                            return new GC.Spread.Sheets.CellTypes.CheckBox();
                        }
                    }
                }
            }
        ]
    },
    positionData:null,
    positionSelectedObject:null,
    L_M_M:null,
    showCalcInstallSettingDiv:function () {
        $("#calc_installation_fee").modal({show:true});
    },
    engineeringTypeChecking:function () {
        if(projectObj.project.isInstall()) $('#AZZJF_div').show();//如果是安装工程，则显示
    },
    initInstallationFeeSpread:function(){
        //初始化费用项表格
      this.feeItemSpread = SheetDataHelper.createNewSpread($("#feeItemSheet")[0]);
      sheetCommonObj.spreadDefaultStyle(this.feeItemSpread);
      this.feeItemSheet = this.feeItemSpread.getSheet(0);
      this.initSheet(this.feeItemSheet,this.feeItemSetting);
      this.feeItemSheet.name('feeItemSheet');

      this.feeItemSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onFeeItemSelectionChange);
      this.feeItemSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onSelectButtonClick);
      this.showFeeItemData();

      //初始化章节项表格
       this.feeDetailSpread = SheetDataHelper.createNewSpread($("#feeDetailSheet")[0]);
       sheetCommonObj.spreadDefaultStyle(this.feeDetailSpread);
       this.feeDetailSheet = this.feeDetailSpread.getSheet(0);
       this.initSheet(this.feeDetailSheet,this.feeDetailSetting);
       this.feeDetailSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onFeeDetailSelectionChange);
       this.feeDetailSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onDetailRangeChanged);
       this.feeDetailSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onSelectButtonClick);
       this.feeDetailSheet.name('feeDetailSheet');
       this.feeDetailSheet.setRowCount(0);
    },
    onFeeItemSelectionChange:function (e, info) {
        let me = installationFeeObj;
        let newSelections = info.newSelections;
        let row = newSelections[0].row;
        let selected = me.feeItemData[row];
        let canChange = me.detailResultCheck(info);
        if(canChange == false){
            let os = info.oldSelections[0];
            setTimeout(function () {//这里是因为费用项名字的单元格是自定义的树结构，点击这一列单元格切换行时，如果不设置延时的话，selectionChange事件会触发两次
                info.sheet.setSelection(os.row,os.col,os.rowCount,os.colCount);
            },200);
        }else {
            if(selected&&selected.libID){//说明是选中了费用项
                me.positionButtonChecking(row,selected);
                me.showFeeDetailData(selected.libID,selected.ID);
            }else {
                me.showFeeDetailData();
            }
        }
        me.feeItemSheet.repaint();
    },
    onFeeDetailSelectionChange:function (e,info) {
        console.log('detail selection change');
        let me = installationFeeObj;
        if(me.detailReloadSelection){
            info.sheet.setSelection(me.detailReloadSelection.row,me.detailReloadSelection.col,1,1);
            me.detailReloadSelection=null;
        }else {
            let canChange = me.detailResultCheck(info);
            if(canChange == false){
                let os = info.oldSelections[0];
                info.sheet.setSelection(os.row,os.col,os.rowCount,os.colCount);
            }
        }
        me.feeDetailSheet.repaint();
    },
    positionButtonChecking:function (row,recode) {//按钮有效性检查
        if(recode.feeType){
            installationFeeObj.feeItemSheet.getCell(row,3).locked(recode.feeType=='子目费用');
        }
    },
    onSelectButtonClick:function (e,info) {
        let sheet = info.sheet, row = info.row, col = info.col;
        let cellType = sheet.getCellType(row, col);
        if(cellType instanceof GC.Spread.Sheets.CellTypes.Button){
            installationFeeObj.onPositionButtonClick(e,info);
        }else {
            installationFeeObj.onCalcCheckBoxClick(e,info);
        }
    },
    onPositionButtonClick : function(e,info){//选取位置按钮
        $('#calc_position_from').val(info.sheetName);
        $('#calc_position').modal({show:true});
    },
    onModifyFeeRuleEditStarting:function (e,args) {
        let me = installationFeeObj;
        let rowData = me.modifyFeeRuleData[args.row];
        if(me.modifyFeeRuleSetting.header[args.col].dataCode=='feeRate'&&installSectionBase.indexOf(rowData.base)===0){//当基数是分别按人材机乘系数时，费率列只读
            args.cancel = true;
        }
    },
    onCalcCheckBoxClick: function(e,info){
        let me = installationFeeObj;
        var checkboxValue = info.sheet.getCell(info.row, info.col).value();
        var newval = 0;
        if (checkboxValue) {
            newval = 0;
            info.sheet.getCell(info.row, info.col).value(newval);
        } else {
            newval = 1;
            info.sheet.getCell(info.row, info.col).value(newval);
        }
        info.newValue = newval;
        me.onFeeItemValueChange(e,info);
    },
    refreshView:function () {
        if(this.feeItemSpread == null){
            this.initInstallationFeeSpread();
        }else {
            this.feeItemSpread.refresh();
            this.feeDetailSpread.refresh();
            let sel_f = this.feeItemSheet.getSelections()[0];
            let sel_d = this.feeDetailSheet.getSelections()[0];
            this.showFeeItemData();
            this.feeItemSheet.setSelection(sel_f.row ==-1?0:sel_f.row,sel_f.col,sel_f.rowCount,sel_f.colCount);
            let oldData = sel_f.row<this.feeItemData.length?this.feeItemData[sel_f.row]:null;
            if(oldData){
                this.showFeeDetailData(oldData.libID,oldData.ID);
            }else {
                this.showFeeDetailData();
            }
            this.feeDetailSheet.setSelection(sel_d.row ==-1?0:sel_d.row,sel_d.col,sel_d.rowCount,sel_d.colCount);
        }

    },
    showFeeItemData:function () {
        this.feeItemData = this.getFeeItemData(projectObj.project.installation_fee.datas);
        this.feeItemSheet.setRowCount(0);
        this.feeItemSheet.getRange(-1, 1, -1, 1).cellType(gljOprObj.getTreeNodeCellType(this.feeItemData));
        sheetCommonObj.showData(this.feeItemSheet, this.feeItemSetting, this.feeItemData);
        this.feeItemSheet.setRowCount(this.feeItemData.length);
        for(let i =0 ;i < this.feeItemData.length;i++){
            let data = this.feeItemData[i];
            if(data.hasOwnProperty('subList')){//根节点不可编辑
                this.feeItemSheet.getRange(i,-1, 1, -1, GC.Spread.Sheets.SheetArea.viewport).locked(true);//this.feeItemSheet.getCell(i, 2).locked(true);
                this.feeItemSheet.getRange(i,2,1,2).cellType(new GC.Spread.Sheets.CellTypes.Text());//费用类型、记取位置两列替换成普通的单元格;
            }
            this.positionButtonChecking(i,data);
        }

    },
    showFeeDetailData:function (libID,feeItemId) {
        this.feeDetailSheet.setRowCount(0);
        if(libID&&feeItemId){
            this.feeDetailData = this.getFeeDetailData(libID,feeItemId);
        }else {
            this.feeDetailData = []
        }
        sheetCommonObj.showData(this.feeDetailSheet, this.feeDetailSetting, this.feeDetailData);
        this.feeDetailSheet.setRowCount(this.feeDetailData.length);
        if(this.feeDetailData.length>0){
            this.feeDetailSheet.suspendPaint();
            this.feeDetailSheet.suspendEvent();
            this.feeDetailSheet.getRange(0, -1, this.feeDetailData.length, -1, GC.Spread.Sheets.SheetArea.viewport).wordWrap(true);
            let feeItem = this.feeItemData[this.feeItemSheet.getSelections()[0].row];
            for(let i =0;i<this.feeDetailData.length;i++){
                this.feeDetailSheet.autoFitRow(i);
                this.setComboRuleCell(i,1,this.feeDetailData[i],this.feeDetailSheet);//设置费用规则下拉选项
                this.lockDetailSheet(i,this.feeDetailData[i],feeItem);
            }
            this.feeDetailSheet.resumeEvent();
            this.feeDetailSheet.resumePaint();
        }
    },
    showMoreFeeRule:function () {
        this.moreFeeRuleData = this.getMoreFeeRuleData();
        this.moreFeeRuleSheet.setRowCount(0);
        sheetCommonObj.showData(this.moreFeeRuleSheet, this.moreFeeRuleSetting, this.moreFeeRuleData);
        this.moreFeeRuleSheet.setRowCount(this.moreFeeRuleData.length);
        this.moreFeeRuleSheet.clearSelection();
    },
    showModifyFeeRule:function () {
        let riselection = this.rationInstallSheet.getSelections()[0];
        let ration_install = this.rationInstallData[riselection.row];
        let feeRule =  _.cloneDeep(projectObj.project.installation_fee.getFeeRuleByID(ration_install.libID,ration_install.ruleId));//不改变原有对象
        feeRule.libID = ration_install.libID;
        feeRule.feeType = ration_install.feeType;
        this.modifyFeeRuleData = [feeRule];
        this.modifyFeeRuleSheet.setRowCount(0);
        sheetCommonObj.showData(this.modifyFeeRuleSheet, this.modifyFeeRuleSetting, this.modifyFeeRuleData);
        this.modifyFeeRuleSheet.setRowCount(this.modifyFeeRuleData.length);
        let positionCol = _.findIndex(this.modifyFeeRuleSetting.header,{ 'dataCode': "position"});
        this.modifyFeeRuleSheet.getRange(-1,positionCol, -1, 1, GC.Spread.Sheets.SheetArea.viewport).locked(ration_install.feeType=='子目费用');//设置选取位置列只读
    },
    showRationInstallationData:function (node) {
        var installationList = [];
        var ration_installation = projectObj.project.ration_installation;
        var ration = node.data;
        if (ration_installation.datas && ration_installation.datas.length > 0) {
            for(let i =0; i < ration_installation.datas.length;i++){
                let ri = ration_installation.datas[i];
                if(ration.projectID == ri.projectID && ration.ID == ri.rationID){
                   let tem_ri =  _.cloneDeep(ri);
                   this.getRIShowData(tem_ri.ruleId,tem_ri,tem_ri);
                   installationList.push(tem_ri);
                }
            }
        }
        this.rationInstallData = installationList;
        this.rationInstallSheet.setRowCount(0);
        sheetCommonObj.showData(this.rationInstallSheet, this.rationInstallSetting,this.rationInstallData);
        if(this.rationInstallData.length>0){
            this.rationInstallSheet.suspendPaint();
            this.rationInstallSheet.suspendEvent();
            for(let i = 0;i< this.rationInstallData.length;i++){
                let impactRules = projectObj.project.installation_fee.getFeeRuleBySection({libID:this.rationInstallData[i].libID,ID:this.rationInstallData[i].sectionId});
                this.setComboRuleCell(i,2,{impactRules:impactRules},this.rationInstallSheet);//设置费用规则下拉选项
            }
            this.rationInstallSheet.resumeEvent();
            this.rationInstallSheet.resumePaint();
        }
    },
    refreshRationInstallationRow:function (row) {
        let ri = this.rationInstallData[row];
        let tem_ri = _.cloneDeep(projectObj.project.ration_installation.getByID(ri.ID));
        this.rationInstallData[row] = this.getRIShowData(tem_ri.ruleId,tem_ri,tem_ri);
        sheetCommonObj.showRowData(this.rationInstallSheet, this.rationInstallSetting,row,this.rationInstallData);
    },
    refreshFeeDetailRow:function (row) {
        let detail = this.feeDetailData[row];
        let section = projectObj.project.installation_fee.getInstallSectionByID(detail.libID,detail.ID);
        this.feeDetailData[row] = this.getDetailRowDataBySection(section,detail.libID);
        sheetCommonObj.showRowData(this.feeDetailSheet, this.feeDetailSetting,row,this.feeDetailData);
        let feeItem = projectObj.project.installation_fee.getFeeItemByID(detail.libID,detail.feeItemId);
        this.lockDetailSheet(row,this.feeDetailData[row],feeItem);
    },
    lockDetailSheet:function(row,detail,feeItem){
        if(detail.feeRuleId){//选中了规则项
            for(let col=0;col<this.feeDetailSetting.header.length;col++) {
                let header = this.feeDetailSetting.header[col];
                if(header.dataCode=='feeRate'){
                    let baseIndex = installSectionBase.indexOf(detail.base);
                    this.feeDetailSheet.getCell(row,col).locked(baseIndex<1);//当基数是“人材机乘系数”时，“费率(%)”列只读。
                }
                if(header.dataCode=='position'){
                    this.feeDetailSheet.getCell(row,col).locked(feeItem.feeType=='子目费用');
                }
            }
        }else {//没有规则项则相关的单元格都锁定
            this.feeDetailSheet.getRange(row, 3, 1, this.feeDetailSetting.header.length-3, GC.Spread.Sheets.SheetArea.viewport).locked(true);
        }
    },
    setComboRuleCell:function(row,col,detail,sheet){
        let options=[{text:"无",value:""}];
        for(let ir of detail.impactRules){
            options.push({text:ir.rule,value:ir.ID});
        }
        options.push({text:"更多",value:'more'});
        let dynamicCombo = sheetCommonObj.getDynamicCombo();//new GC.Spread.Sheets.CellTypes.ComboBox();
        dynamicCombo.items(options);
        dynamicCombo.editorValueType(GC.Spread.Sheets.CellTypes.EditorValueType.value);
        sheet.setCellType(row, col, dynamicCombo, GC.Spread.Sheets.SheetArea.viewport);
    },
    getFeeItemData:function (datas) {
        let feeItemShowArray = [];
        for(let d of datas){
            let tem_Lib = {
                feeItem:d.libName,
                subList:d.installFeeItem,
                collapsed:false
            };
            feeItemShowArray.push(tem_Lib);
            if(d.installFeeItem && d.installFeeItem.length > 0){
                for(let t_if of d.installFeeItem){
                    t_if.installFeeID = d.ID;
                    t_if.libID = d.libID;
                    t_if.isMixRatio = true;
                    t_if.displayPosition = this.getDisplayText(t_if);
                    feeItemShowArray.push(t_if);
                }
            }
        }
        return feeItemShowArray;
    },
    getDisplayText:function (item) {
        if(item.billID&&item.billID!=''){
            let node = projectObj.project.mainTree.getNodeByID(item.billID);
            if(node){
                let code = node.data.code?node.data.code:"";
                let name = node.data.name?node.data.name:"";
                return code +" "+name;
            }
        }
        return  item.position;
    },
    getFeeDetailData : function(libID,feeItemId){
        let me = installationFeeObj;
        let feeDetailArr = [];
        let installSections =projectObj.project.installation_fee.getInstallSectionsByfeeItemID(libID,feeItemId);
        for(let is of installSections){
            let tem_detail = me.getDetailRowDataBySection(is,libID);
            feeDetailArr.push(tem_detail);
        }
        return feeDetailArr;
    },
    getMoreFeeRuleData:function () {
        let me = installationFeeObj;
        let feeItem = null;
        let from = $("#more_from").val();
        if(from =='feeDetail'){//在计取安装费那里点击更多
            let fee_select = me.feeItemSheet.getSelections()[0];
            feeItem = me.feeItemData[fee_select.row];
        }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
            let ri_select = me.rationInstallSheet.getSelections()[0];
            let ri = me.rationInstallData[ri_select.row];
            feeItem = {ID:ri.feeItemId,libID:ri.libID};
        }
        let feeRules =  projectObj.project.installation_fee.getFeeRuleByFeeItem(feeItem);
        return feeRules;
    },

    getDetailRowDataBySection(is,libID){
        let me = this;
        let tem_detail = {
            ID:is.ID,
            feeItemId:is.feeItemId,
            name:is.name,
            feeRuleId:is.feeRuleId,
            libID:libID,
            rule:is.feeRuleId,
        };
        if(is.feeRuleId){
            let feeRule = projectObj.project.installation_fee.getFeeRuleByID(libID,is.feeRuleId);
            if(feeRule){
                tem_detail.code = feeRule.code;
                tem_detail.base = feeRule.base;
                tem_detail.feeRate = feeRule.feeRate;
                tem_detail.labour = feeRule.labour;
                tem_detail.material = feeRule.material;
                tem_detail.machine = feeRule.machine;
                tem_detail.position = me.getDisplayText(feeRule);
                tem_detail.billID = feeRule.billID;
                tem_detail.ruleName = feeRule.rule;
            }
        }
        tem_detail.impactRules = projectObj.project.installation_fee.getFeeRuleBySection(tem_detail);
        return tem_detail;
    },
    initSheet: function (sheet,setting) {
        var me = this;
        sheetCommonObj.initSheet(sheet, setting, 30);
        sheet.bind(GC.Spread.Sheets.Events.ValueChanged, me.onSheetValueChange);
    },
    initPositionSpread:function () {
        this.positionSpread = SheetDataHelper.createNewSpread($('#positionSpread')[0]);
        sheetCommonObj.spreadDefaultStyle(this.positionSpread);
        this.selectionTree = idTree.createNew({id: 'ID', pid: 'ParentID', nid: 'NextSiblingID', rootId: -1, autoUpdate: false});
        this.selectionTreeController = TREE_SHEET_CONTROLLER.createNew(this.selectionTree, this.positionSpread.getActiveSheet(), this.positionSetting);
        this.positionSheet = this.positionSpread.getActiveSheet();
        this.positionSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onPositionCheckBoxClick);
    },
    initMoreFeeRuleSpread:function () {
        this.moreFeeRuleSpread = SheetDataHelper.createNewSpread($("#moreFeeRuleSpread")[0]);
        sheetCommonObj.spreadDefaultStyle(this.moreFeeRuleSpread);
        this.moreFeeRuleSheet = this.moreFeeRuleSpread.getSheet(0);
        this.initSheet(this.moreFeeRuleSheet,this.moreFeeRuleSetting);
        this.moreFeeRuleSheet.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onFeeRuleDoubleClick);
        this.moreFeeRuleSheet.selectionUnit(1);//0 cell,1 row,2 col;
        this.moreFeeRuleSheet.name('moreFeeRuleSheet');
    },
    initModifyFeeRuleSpread:function () {
        let me = this;
        me.modifyFeeRuleSpread = SheetDataHelper.createNewSpread($("#modifyFeeRuleSpread")[0]);
        sheetCommonObj.spreadDefaultStyle(me.modifyFeeRuleSpread);
        me.modifyFeeRuleSheet = me.modifyFeeRuleSpread.getSheet(0);
        me.initSheet(me.modifyFeeRuleSheet, me.modifyFeeRuleSetting);
        this.modifyFeeRuleSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onPositionButtonClick);
        me.modifyFeeRuleSheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onModifyFeeRuleEditStarting);
        this.modifyFeeRuleSheet.name('modifyFeeRuleSheet');
    },
    rationInstSheeteditChecking: function (sender, args) {
        if(args.row>=installationFeeObj.rationInstallData.length){
            args.cancel = true;
        }
    },
    initRationInstallSheet:function (sheet) {
        let me = this;
        this.rationInstallSheet = sheet;
        this.initSheet( this.rationInstallSheet,this.rationInstallSetting);
        sheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onRationSheetSelectionChange);
        sheet.bind(GC.Spread.Sheets.Events.EditStarting, this.rationInstSheeteditChecking);
        this.rationInstallSheet.name("rationInstallSheet");
    },
    onRationSheetSelectionChange: function (sender, args) {
        let me = installationFeeObj;
        let row = args.newSelections[0].row;
        let col = args.newSelections[0].col;
        let dataCode = me.rationInstallSetting.header[col].dataCode;
        if(row<me.rationInstallData.length&&dataCode=='position'){
            let locked = false;
            if(me.rationInstallData[row].feeType=='子目费用'){
                locked = true;
            }else if(me.rationInstallData[row].unifiedSetting==1){
                locked = true;
            }else if(!me.rationInstallData[row].ruleId||me.rationInstallData[row].ruleId==''){
                locked = true;
            }
            installationFeeObj.rationInstallSheet.getCell(row,col).locked(locked);
        }
        me.rationInstallSheet.repaint();
    },
    onFeeRuleDoubleClick:function (e,info) {
        let from = $("#more_from").val();
        if(info.row!=undefined||info!=null){
            if(from =='feeDetail'){
                installationFeeObj.updateFeeRuleToSection(info.row);
            }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
                installationFeeObj.updateFeeRuleToRInstall(info.row);
            }
        }else {
            return;
        }
        $('#more_feeRule').modal('hide');
    },
    onPositionCheckBoxClick:function (e,args) {
        let me = installationFeeObj;
        var checkboxValue = args.sheet.getCell(args.row, args.col).value();
        var newval = 0;
        if (checkboxValue) {
            newval = 0;
            args.sheet.getCell(args.row, args.col).value(newval);
        } else {
            newval = 1;
            args.sheet.getCell(args.row, args.col).value(newval);
        }
        if(me.positionSelectedObject==null){//如果之前没选中任何一条记录，则记住选中位置
            me.positionSelectedObject ={
               row : args.row,
               col: args.col,
               recode:me.positionData[args.row]
           }
        }else {
            if(me.positionData[args.row].ID == me.positionSelectedObject.recode.ID){//行相同的时候有两种情况，一种是没有做过滤的情况，行相等就说明是要去掉选中记录。
                // 另外一种有可能是过滤后刚好和初始的选中位置显示的时候相等，这里其实是不同的记录，所以行相等的时候用ID判断是不是来的记录才准确
                    me.positionSelectedObject = null;  //如果是在已选中的记录中再点一次选中复框，则去掉选中记录
            }else {//切换选中记录
                //去掉之前选中位置的打勾 - 要先查找原先的位置，因为过滤功能的原因，有可能选中的与当前的行数已经不一样了
                let oldIndex = _.findIndex(me.positionData,{'ID':me.positionSelectedObject.recode.ID});
                if(oldIndex != -1){
                    args.sheet.getCell(oldIndex, me.positionSelectedObject.col).value(0);
                }
                me.positionSelectedObject ={
                    row : args.row,
                    col: args.col,
                    recode:me.positionData[args.row]
                }
            }
        }

    },
    loadSelectionNodes : function () {
        this.positionData =this.getBillDataForSelect();
        this.selectionTree.loadDatas(this.positionData);
        this.selectionTreeController.showTreeData();
    },
    filterSelectionNodes:function () {
        let keyword = $('#filterKeyword').val();
        let resultData =[], newTreeIDs=[], newDatas = [];
        let allPositionData = this.getBillDataForSelect();
        if(keyword&&keyword!=""){//按关键字过滤出结果
            resultData = _.filter(allPositionData,function (item) {
                if(item.canSelect == true){
                    if(item.code.indexOf(keyword)!=-1||item.name.indexOf(keyword)!=-1){
                        return true;
                    }
                }
            });
        }
        for(let tem of resultData){//取出所有父节点ID
            let temNode = projectObj.project.mainTree.getNodeByID(tem.ID);
            if(temNode){
                getParentIDs(temNode,newTreeIDs);
            }
        }
        if(newTreeIDs.length > 0){//生成过滤后的记录
            for(let p_tem of allPositionData){
                if(_.includes(newTreeIDs,p_tem.ID)){
                    newDatas.push(p_tem);
                }
            }
        }
        this.positionData = newDatas;
        this.selectionTree.loadDatas(this.positionData);
        this.selectionTreeController.showTreeData();

        function getParentIDs(temNode,idArrays) {
            idArrays.push(temNode.data.ID);
            if(temNode.parent!=null){
                getParentIDs(temNode.parent,idArrays);
            }
        }
    },
    getBillDataForSelect:function () {//这里有五个地方共用
        let controller = projectObj.mainController, project = projectObj.project;
        let from = $('#calc_position_from').val();
        let rootNode = null,allNodes = [],datas = [],billID = null,selectedItem=null;
        if(from=="rationInstallSheet"){
            let riSelection = this.rationInstallSheet.getSelections()[0];
            selectedItem = this.rationInstallData[riSelection.row];
            billID = selectedItem.billID;
        }else if(from=="modifyFeeRuleSheet"){
            let riSelection = this.modifyFeeRuleSheet.getSelections()[0];
            selectedItem = this.modifyFeeRuleData[riSelection.row];
            billID = selectedItem.billID;
        }else if(from == "ration_template"){
            let temSelection = mbzm_obj.sheet.getSelections()[0];
            selectedItem = _.cloneDeep(mbzm_obj.datas[temSelection.row]);
            if($('#createLocation').val() == 1) {//措施项目下
                billID = selectedItem.billID;
                selectedItem.feeType='措施费用'
            } else {//分部分项下
                billID = selectedItem.fxID;
                selectedItem.feeType='分项费用'
            }
        } else {
            let selection = this.feeItemSheet.getSelections()[0];
            selectedItem = this.feeItemData[selection.row];
            if(from =="feeItemSheet"){
                if(selectedItem.billID){
                    billID = selectedItem.billID;
                }
            }else if(from =="feeDetailSheet") {
                let detailSelection = this.feeDetailSheet.getSelections()[0];
                let detail = this.feeDetailData[detailSelection.row];
                if(detail.billID){
                    billID = detail.billID;
                }
            }
        }
        if(selectedItem.feeType=='措施费用'){
            rootNode = project.Bills.getMeasureNode(controller);
        }else if(selectedItem.feeType=='分项费用'){
            rootNode = project.Bills.getFBFXNode(controller);
        }
        if(rootNode){
            allNodes.push(rootNode);
            controller.tree.getAllSubNode(rootNode.source,allNodes);
        }

        for(let n of allNodes){
            let temData = {
                ID:n.data.ID,
                NextSiblingID:n.data.NextSiblingID,
                ParentID:n.data.ParentID,
                type : billText[n.data.type],
                code : n.data.code,
                name : n.data.name
            };
            //project.mainTree.selected.data.calcBase&&project.mainTree.selected.data.calcBase!=""
            if(n.data.type == billType.FX||n.data.type == billType.BX){//分项/补项才能选
                temData.canSelect = true;
            }else if(n.data.type == billType.BILL){//如果是清单类型，则是叶子节点并且没有使用基数计算的清单
                if (n.children.length==0&&!(n.data.calcBase&&n.data.calcBase!="")){
                    temData.canSelect = true;
                }
            }
            if(billID&&n.data.ID == billID){
                temData.selected = 1;
                this.positionSelectedObject ={
                    row : datas.length,
                    col: 3,
                    recode:temData
                }
            }
            datas.push(temData);
        }
        return datas;
    },
    selectPositionConfirm:function () {
        let pobj = this.positionSelectedObject;
        let from = $('#calc_position_from').val();
        if(pobj){
            if(from=='feeItemSheet'){
                this.updateFeeItemPosition(pobj.recode);
            }else if(from=='feeDetailSheet'){
                this.updateFeeRulePosition(pobj.recode);
            }else if(from=='rationInstallSheet'){
                this.updateRationInstallPosition(pobj.recode);
            }else if(from =='modifyFeeRuleSheet'){
                this.updateModifyFeeRulePosition(pobj.recode);
            }else if(from == "ration_template"){
                mbzm_obj.updatePosition(pobj.recode);
            }
        }
        $("#calc_position").modal('hide');
    },
    confirmFeeRuleModify:function () {
        let me = this,installation_fee = projectObj.project.installation_fee;
        let modifyRule = me.modifyFeeRuleData[0];
        let updateMap = null;
        console.log(me.modifyEditedObj);
        if(me.modifyEditedObj==null){
            $("#modify_feeRule").modal('hide');
            return;
        }
        let feeRule = installation_fee.getFeeRuleByID(modifyRule.libID,modifyRule.ID);
        if(feeRule){
            for(let mkey in me.modifyEditedObj){
                if(me.modifyEditedObj[mkey]!=feeRule[mkey]){//说明是值发生了改变
                    updateMap==null?updateMap={}:"";
                    updateMap[mkey] =me.modifyEditedObj[mkey];
                }
            }
            if(updateMap){//如果有需要更新的属性
                if(modifyRule.base&&installSectionBase.indexOf(modifyRule.base)>0){
                    let temLabour = modifyRule.labour?modifyRule.labour:0;
                    let temMaterial = modifyRule.material?modifyRule.material:0;
                    let temMachine = modifyRule.machine?modifyRule.machine:0;
                    let sum = temLabour+temMaterial+temMachine;//三项的和要等于100
                    if(sum!=100){
                       alert("人工、材料、机械的和应等于100，请重新输入。");
                       return;
                    }
                }
                $("#modify_feeRule").modal('hide');
                installation_fee.updateFeeRule(updateMap,modifyRule.libID,modifyRule.ID,function () {
                    me.refreshRationInstallationRow(me.rationInstallSheet.getSelections()[0].row);
                    installation_fee.calcInstallationFee(function (isChange,rations) {
                        if(isChange){
                            projectObj.project.calcProgram.calcNodesAndSave(rations);
                        }
                    });
                });
            }else {
                $("#modify_feeRule").modal('hide');
            }
        }
    },
    updateModifyFeeRulePosition:function (recode) {
        let me = this;
        let riselection = me.modifyFeeRuleSheet.getSelections()[0];
        let modifyFee = me.modifyFeeRuleData[riselection.row];
        let positionCol = _.findIndex(me.modifyFeeRuleSetting.header,{ 'dataCode': "position"});
        if(modifyFee.billID == recode.ID){//和原来的位置没变
            return
        }
        if(me.modifyEditedObj==null){//初始化
            me.modifyEditedObj={};
        }
        me.modifyEditedObj.position = recode.code;
        me.modifyEditedObj.billID = recode.ID;
        modifyFee.position = recode.code;
        modifyFee.billID = recode.ID;
        me.modifyFeeRuleSheet.setValue(riselection.row,positionCol,me.getDisplayText(modifyFee));
        console.log(me.modifyEditedObj);
    },
    updateRationInstallPosition:function(recode){
        let me = this, installation_fee = projectObj.project.installation_fee;
        let riselection = me.rationInstallSheet.getSelections()[0];
        let rationInstall = me.rationInstallData[riselection.row];
        if(rationInstall.billID == recode.ID){//和原来的位置没变
            return;
        }
        installation_fee.updateFeeRule({position:recode.code,billID:recode.ID},rationInstall.libID,rationInstall.ruleId,function (){
            me.refreshRationInstallationRow(riselection.row);
            installation_fee.calcInstallationFee(function (isChange,rations) {
                if(isChange){
                    projectObj.project.calcProgram.calcNodesAndSave(rations);
                }
            });
        });
    },
    updateFeeRulePosition:function (recode) {
        let me = this;
        let itemSelection  = this.feeItemSheet.getSelections()[0];
        let feeItem = this.feeItemData[itemSelection.row];
        let detailSelection = this.feeDetailSheet.getSelections()[0];
        let detail = this.feeDetailData[detailSelection.row];
        if(detail.billID ==recode.ID ){//和原来的位置没变
            return;
        }
        projectObj.project.installation_fee.updateFeeRule({position:recode.code,billID:recode.ID},feeItem.libID,detail.feeRuleId,function (isFeeItemUpdate){
            if(isFeeItemUpdate){
                feeItem.position ="";
                feeItem.billID = "";
                feeItem.displayPosition = "";
                me.feeItemSheet.getCell(itemSelection.row, 3).value(feeItem.displayPosition);
            }
            me.showFeeDetailData(feeItem.libID,feeItem.ID);
        });
    },
    updateFeeRuleToSection:function (row) {
        let me = this, installation_fee=projectObj.project.installation_fee;
        let feeRule = me.moreFeeRuleData[row];
        let detailSelection = me.feeDetailSheet.getSelections()[0];
        let detail = this.feeDetailData[detailSelection.row];
        let rationInstallations = [];
        let updateData = installation_fee.getSectionUpdateData(detail.libID,detail.ID,{"feeRuleId":feeRule.ID});
        installation_fee.getRIUpdateDataBySectionUpdate(detail.ID,feeRule.ID,rationInstallations);//生成受影响的定额安装增加费并加入到数组中
        $.bootstrapLoading.start();
        installation_fee.submitInstallationUpdate(updateData,rationInstallations,function (data) {
            let section = installation_fee.getInstallSectionByID(detail.libID,detail.ID);
            section.feeRuleId = feeRule.ID;
            me.refreshFeeDetailRow(detailSelection.row);
            $.bootstrapLoading.end();
        });
    },
    updateFeeRuleToRInstall:function (row) {
        let me = this;
        let feeRule = me.moreFeeRuleData[row];
        let ri_row = me.rationInstallSheet.getSelections()[0].row;
        let raInstallation = me.rationInstallData[ri_row];
        if(feeRule.ID ==raInstallation.ruleId ){
            me.refreshRationInstallationRow(ri_row);
            return;
        }
        let updateData = {
            ID:raInstallation.ID,
            projectID:raInstallation.projectID,
            ruleId:feeRule.ID,
            unifiedSetting:0
        };
        projectObj.project.ration_installation.update(updateData,function (data) {
            me.refreshRationInstallationRow(ri_row);
            projectObj.project.installation_fee.calcInstallationFee(function () {
                projectObj.project.calcProgram.calcAllNodesAndSave();
            });
        });
    },
    updateFeeItemPosition:function(recode){
        let me = this;
        let selection = this.feeItemSheet.getSelections()[0];
        let feeItem = this.feeItemData[selection.row];
        if(feeItem.billID ==recode.ID ){//和原来的位置没变
            return;
        }
        let updateData =  projectObj.project.installation_fee.getFeeItemUpdateData(feeItem.libID,feeItem.ID,{ position: recode.code, billID:recode.ID});
        let [dataArray,impacRules] = me.getFeeRuleUpdateDataByFeeItem(feeItem,recode);
        dataArray.push(updateData);
        $.bootstrapLoading.start();
        projectObj.project.installation_fee.submitInstallationUpdate(dataArray,null,function (data) {
            //更新缓存
            feeItem.position =recode.code;
            feeItem.billID = recode.ID;
            feeItem.displayPosition = me.getDisplayText(feeItem);
            me.feeItemSheet.getCell(selection.row, selection.col).value(feeItem.displayPosition);
            for(let ir of impacRules){
                ir.position = recode.code;
                ir.billID  = recode.ID;
            }
            me.showFeeDetailData(feeItem.libID,feeItem.ID);
            $.bootstrapLoading.end();
        });
    },
    getFeeRuleUpdateDataByFeeItem : function (feeItem,recode) {
        let dataArray = [];
        let impacRules = projectObj.project.installation_fee.getFeeRuleByFeeItem(feeItem);
        for(let ir of impacRules){
            if(ir.position !=recode.code || ir.billID != recode.ID){
                let tem_data = {
                    ID:feeItem.installFeeID,
                    itemID:ir.ID,
                    type:'feeRule',
                    doc:{position: recode.code, billID:recode.ID}
                };
                dataArray.push(tem_data);
            }
        }
        return [dataArray,impacRules]
    },
    onSheetValueChange:function (e,info) {
        if(info.sheetName=='feeItemSheet'){
            installationFeeObj.onFeeItemValueChange(e,info);
        }
        if(info.sheetName == 'feeDetailSheet'){
            installationFeeObj.onFeeDetailValueChange(e,info);
        }
        if(info.sheetName == 'rationInstallSheet'){
            installationFeeObj.onRationInstallValueChange(e,info);
        }
        if(info.sheetName == 'modifyFeeRuleSheet'){
            installationFeeObj.modifyFeeRuleValueChange(e,info);
        }
    },
    onFeeItemValueChange:function (e,info) {
        let me = installationFeeObj;
        let feeItem = this.feeItemData[info.row];
        let header = this.feeItemSetting.header[info.col];
        let doc={},cleanPosition = false;
        doc[header.dataCode] = info.newValue;
        if(header.dataCode=='feeType'&&info.newValue == '子目费用'){
            doc.position = '';
            doc.billID = '';
            cleanPosition = true;
        }
        projectObj.project.installation_fee.updateFeeItem(doc,feeItem.libID,feeItem.ID,cleanPosition,function () {
            me.feeItemSheet.getCell(info.row, info.col).value(info.newValue);
            me.positionButtonChecking(info.row,feeItem);
            if(cleanPosition==true){
                me.feeItemSheet.getCell(info.row, info.col+1).value("");
                me.showFeeDetailData(feeItem.libID,feeItem.ID);
            }
        });
    },
    cleanPositionIfNeed:function (settingVal) {
         let me = this;
         let updateData = [];
         let installation_fee = projectObj.project.installation_fee;
         if(settingVal == 1){//分项费用选为“每个分部单独计取”时，分项费用类型的记取位置应自动清空。
              for(let item of me.feeItemData){
                  if(item.feeType == '分项费用'){
                      if((item.position&&item.position!='')||(item.billID&&item.billID!='')){
                          updateData.push(installation_fee.getFeeItemUpdateData(item.libID,item.ID,{position:'', billID:''}));
                      }
                      let [dataArray,impacRules] = me.getFeeRuleUpdateDataByFeeItem(item,{code: "",ID:''});
                      dataArray.length >0? updateData = updateData.concat(dataArray):'';
                  }
              }
         }
        console.log(updateData);
         if(updateData.length > 0){
             installation_fee.updateInstallation(updateData,function () {
                 me.refreshView();
             })
         }

    },
    onRationInstallValueChange:function (e,info) {
        let me = installationFeeObj;
        let installation_fee = projectObj.project.installation_fee
        if(info.newValue==info.oldValue){
            return;
        }
        let raInstallation = me.rationInstallData[info.row];
        let fieldID =  me.rationInstallSetting.header[info.col].dataCode;
        let updateData = {
            projectID:raInstallation.projectID,
            ID:  raInstallation.ID
        };
        if(fieldID=='ruleId'){//选择新的规则项
            if(info.newValue=="more"){//选择的是更多
                $("#more_from").val("rationInstallation");
                $("#more_feeRule").modal({show:true});
                return;
            }
            if(info.newValue == null){
                me.refreshRationInstallationRow(info.row);
            }else if(info.newValue == raInstallation.rule){
                return;
            }else {
                updateData.unifiedSetting = 0;//切换费用规则时去掉统一设置勾选。
            }
        }
        if(fieldID=='unifiedSetting'){//勾选统一设置
            updateData.ruleId = '';
            let feeItem =  installation_fee.getFeeItemByID(raInstallation.libID,raInstallation.feeItemId);
            let section = installation_fee.getInstallSectionByID(raInstallation.libID,raInstallation.sectionId);
            if(section&&feeItem&&feeItem.isCal == 1){
                updateData.ruleId = section.feeRuleId;
            }
        }
        updateData[fieldID] = info.newValue;
        projectObj.project.ration_installation.update(updateData,function (data) {
            me.refreshRationInstallationRow(info.row);
            installation_fee.calcInstallationFee(function () {
                projectObj.project.calcProgram.calcAllNodesAndSave();
            });
        });
    },
    modifyFeeRuleValueChange:function (e,info) {
        let me = installationFeeObj;
        let fieldID = me.modifyFeeRuleSetting.header[info.col].dataCode;
        let value = info.newValue;
        if(me.modifyEditedObj==null){//初始化
            me.modifyEditedObj={};
        }
        if(fieldID=="position"){//改变选取位置时不触发
            return;
        }
        if(fieldID == 'base'){//修改基数
            if(installSectionBase.indexOf(info.newValue)===0){//如果选择的是“人材机乘系数”时，清空“费率(%)”列的值
                me.modifyEditedObj.feeRate = null;
                let feeRateCol = _.findIndex(me.modifyFeeRuleSetting.header,{ 'dataCode': "feeRate"});
                me.modifyFeeRuleSheet.setValue(info.row, feeRateCol, null);
            }
        }else if(fieldID=="feeRate"||fieldID=='machine'||fieldID=='material'||fieldID=="labour"){
            if(value != null){
                if(number_util.isNumber(value)){
                    value = scMathUtil.roundForObj(info.newValue,getDecimal("feeRate"));
                    me.modifyFeeRuleSheet.setValue(info.row, info.col, value);
                }else {
                    alert('当前输入的数据类型不正确，请重新输入。');
                    me.modifyFeeRuleSheet.setValue(info.row, info.col, info.oldValue);
                    return;
                }
            }
        }
        me.modifyEditedObj[fieldID] = value;
        me.modifyFeeRuleData[info.row][fieldID] = value;
        console.log(me.modifyEditedObj);
    },
    onFeeDetailValueChange:function (e,info) {
        if(info.newValue==info.oldValue){
            return;
        }
        let me = installationFeeObj;
        let install_fee = projectObj.project.installation_fee;
        let feeDetail = this.feeDetailData[info.row];
        let header = this.feeDetailSetting.header[info.col];
        let fieldID = header.dataCode;
        let updateData = null;
        let rationInstallations=null;
        if(fieldID == 'rule'){//选择新的规则项
            if(info.newValue=="more"){//选择的是更多
                $("#more_from").val("feeDetail");
                $("#more_feeRule").modal({show:true});
                return;
            }
            if(info.newValue == null){
                me.refreshFeeDetailRow(info.row);
            }else if(info.newValue == feeDetail.ruleName){
                return;
            }else {
                rationInstallations=[];
                updateData = install_fee.getSectionUpdateData(feeDetail.libID,feeDetail.ID,{"feeRuleId":info.newValue});
                install_fee.getRIUpdateDataBySectionUpdate(feeDetail.ID,info.newValue,rationInstallations);//生成受影响的定额安装增加费并加入到数组中
            }

        }else if(fieldID == 'base'){
            if(info.newValue == null){//如果基数为空，重新刷新显示
                me.refreshFeeDetailRow(info.row);
            }else {
                let doc ={base:info.newValue};
                if(installSectionBase.indexOf(info.newValue)===0){//如果选择的是“人材机乘系数”时，清空“费率(%)”列的值
                    doc.feeRate = null;
                }
                updateData = install_fee.getFeeRuleUpdateData(feeDetail.libID,feeDetail.feeRuleId,doc);
            }

        }else {
            if(info.newValue != null){
                if(number_util.isNumber(info.newValue)){
                    info.newValue = scMathUtil.roundForObj(info.newValue,getDecimal("feeRate"));
                }else {
                    alert('当前输入的数据类型不正确，请重新输入。');
                    me.showFeeDetailData(feeDetail.libID,feeDetail.feeItemId);
                    me.detailReloadSelection={row:info.row,col:info.col};
                    return;
                }
            }
            let doc = {};
            doc[fieldID] = info.newValue;
            feeDetail[fieldID] = info.newValue;
            updateData =  install_fee.getFeeRuleUpdateData(feeDetail.libID,feeDetail.feeRuleId,doc);
        }
        install_fee.submitInstallationUpdate(updateData,rationInstallations,function (data) {
            if(updateData){
                if(updateData.type=="installSection"){
                    let section = install_fee.getInstallSectionByID(feeDetail.libID,feeDetail.ID);
                    section.feeRuleId = info.newValue;
                }
                if(updateData.type=="feeRule"){
                    let feeRule = install_fee.getFeeRuleByID(feeDetail.libID,feeDetail.feeRuleId);
                    let updateDoc = updateData.doc;
                    for(let key in updateDoc){
                        feeRule[key] = updateDoc[key];
                    }
                }
              me.refreshFeeDetailRow(info.row);
            }
        });
    },
    onDetailRangeChanged:function (e,info) {
        let me = installationFeeObj;
        if (info.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            let header = me.feeDetailSetting.header[info.col];
            info.oldValue = me.feeDetailData[info.row][header.dataCode];
            info.newValue = null;
           me.onFeeDetailValueChange(e,info);
        }
    },
    detailResultCheck:function (info) {
        let me = installationFeeObj;
        let canChange = true;
        let os = null;
        if(info.oldSelections==undefined||info.newSelections[0].row == info.oldSelections[0].row){//没有换行
            return canChange;
        }
        if(info.sheetName=='feeDetailSheet'){
            os = info.oldSelections[0];
        }
        if(info.sheetName=='feeItemSheet'){
            os = me.feeDetailSheet.getSelections()[0];
        }
        if(this.feeDetailData&&this.feeDetailData.length>0&&this.feeDetailData[os.row]){
            let detail = this.feeDetailData[os.row];
            if(detail.base&&installSectionBase.indexOf(detail.base)>0){
                let temLabour = detail.labour?detail.labour:0;
                let temMaterial = detail.material?detail.material:0;
                let temMachine = detail.machine?detail.machine:0;
                let sum = temLabour+temMaterial+temMachine;//三项的和要等于100
                if(sum!=100){
                    setTimeout(function () {//这里须用延时执行的办法，不然的弹窗确认窗口会和spreadjs 的事件有冲突
                        alert("人工、材料、机械的和应等于100，请重新输入。");
                    }, 200);
                    canChange = false;
                }
            }
        }
        return canChange;
    },
    getRIShowData : function (ruleID,rationInstallation,data) {
        if(ruleID==''){//选择的是无
            data.code = '';
            data.rule = '';
            data.base = '';
            data.feeRate = '';
            data.labour = '';
            data.material = '';
            data.machine = '';
            data.position = '';
            data.billID = '';
        }
        let feeRule = projectObj.project.installation_fee.getFeeRuleByID(rationInstallation.libID,ruleID);
        if(feeRule){
            data.code = feeRule.code;
            data.rule = feeRule.rule;
            data.base = feeRule.base;
            data.feeRate = feeRule.feeRate;
            data.labour = feeRule.labour;
            data.material = feeRule.material;
            data.machine = feeRule.machine;
            data.position = feeRule.position;
            data.billID = feeRule.billID;
        }
        let feeItem = projectObj.project.installation_fee.getFeeItemByID(rationInstallation.libID,rationInstallation.feeItemId);
        if(feeItem){
            data.feeType = feeItem.feeType;
        }
        return data;
    },
    calcInstallationFee:function(callback){//计算安装增加费
        let engineering = projectObj.project.projectInfo.property.engineering;
        let installSetting = projectObj.project.projectInfo.property.installSetting;
        let install_fee = projectObj.project.installation_fee;
        let autoCreate = false;
        if(!projectObj.project.isInstall()){//如果不是安装工程，则不用计算
            return;
        }
        //可执行检查
        let install_datas = install_fee.datas;
        for(let d of install_datas){
            for(let item of d.installFeeItem){
                if(item.isCal == 1){ //勾选了记取的费用项
                    let positionCheck = false;//是否做记取位置检查的开关
                    if(item.feeType=='措施费用'){//如果是措施费用，检查是否选取了记取位置或者清单编码是否存在
                        positionCheck = true;
                    }else if(item.feeType=='分项费用'&&(installSetting==undefined||installSetting=="0")){//当费用项是分项费用时，且选择了“整个项目统一计取”
                        positionCheck = true;
                    }
                    if(positionCheck == true){
                        let sections = install_fee.getInstallSectionsByfeeItemID(d.libID,item.ID);
                        for(let s of sections){
                            if(s.feeRuleId&&s.feeRuleId!=""){//有选中规则项
                                let feeRule = install_fee.getFeeRuleByID(d.libID,s.feeRuleId);
                                if(feeRule){
                                    if((!feeRule.billID||feeRule.billID=="")&&(!feeRule.position||feeRule.position=="")){//清单ID和position都为空的时候
                                         alert("计取位置不能为空！");
                                         return
                                    }
                                    if (autoCreate == false){//不自动生成的时候才做检查
                                        if(feeRule.billID && feeRule.billID != ""){//先检查清单ID
                                            let node = projectObj.project.mainTree.getNodeByID(feeRule.billID);
                                            if(!node){
                                                let c = confirm("所选清单没有找到，需要自动生成吗?");
                                                if(c){
                                                    autoCreate = true;
                                                }else {
                                                    return;
                                                }
                                            }
                                        }else if(feeRule.position && feeRule.position != ""){//再检查code
                                            let bill = projectObj.project.Bills.getBillByCode(feeRule.position);
                                            if(!bill){
                                                let c = confirm("所选清单没有找到，需要自动生成吗?");
                                                if(c){
                                                    autoCreate = true;
                                                }else {
                                                    return;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $('#calc_installation_fee').modal('hide');
        install_fee.calcInstallationFee(function (isChange,rations) {
            if(isChange){
                projectObj.project.calcProgram.calcNodesAndSave(rations);
            }
            installationFeeObj.showRationInstallationData(projectObj.project.mainTree.selected);
            if(callback){
                callback();
            }
        });
    },
    initSettingRadio:function () {
        let installSetting = projectObj.project.projectInfo.property.installSetting;
        //radio 值设置
        if(installSetting==undefined||installSetting=="0"){
            $("#all_project_calc").prop("checked",true);
            $("#FB_calc").prop("checked",false);
        }else {
            $("#all_project_calc").prop("checked",false);
            $("#FB_calc").prop("checked",true);
        }
    },
    applyRuleTo:function(level,row){//level:FX/FB/PJ
        let selectRecord = this.rationInstallData[row];
        let ration_installation = projectObj.project.ration_installation;
        let rationID = selectRecord.rationID;
        let condition = {'libID':selectRecord.libID,'feeItemId':selectRecord.feeItemId,'sectionId':selectRecord.sectionId};
        let rationList = [];
        let rationNode = projectObj.project.mainTree.getNodeByID(rationID);
        if(!rationNode){
            return;
        }
        if(level == 'FX'){//应用到分项
            let children = rationNode.parent.children;//兄弟节点
            for(let c of children){
                if(c.data.type == rationType.ration){
                    rationList.push(c.data.ID);
                }
            }
            condition.rationID = rationList;
        }else if(level == 'FB'){//应用到分部
            let FBNode = rationNode.parent.parent;//分部节点
            let rationNodeList =  projectObj.project.mainTree.getLeavesNodes(FBNode);
            for(let r of rationNodeList){
                if(r.data.type == rationType.ration){
                    rationList.push(r.data.ID);
                }
            }
            condition.rationID = rationList;
        }
        //应用到项目的时候就不用加入rationList做判断
        let riList = ration_installation.getDataByConditions(condition);
        let IDList = _.map(riList,'ID');
        ration_installation.applyRuleByIDs(selectRecord.projectID,IDList,selectRecord.ruleId,function () {
            //计算安装增加费
            projectObj.project.installation_fee.calcInstallationFee(function (isChange,rations) {
                if(isChange){
                    projectObj.project.calcProgram.calcNodesAndSave(rations);
                }
            });
        })
    },
};


$(function () {
    $('#calc_installation_fee').on('shown.bs.modal',function () {
        installationFeeObj.refreshView();
        //radio 值设置
        installationFeeObj.initSettingRadio();

    });
    $('#calc_position').on('shown.bs.modal',function () {
        installationFeeObj.positionSelectedObject = null;
        if (installationFeeObj.positionSpread) {
            installationFeeObj.positionSpread.refresh();
        }else {
            installationFeeObj.initPositionSpread();
        }
        installationFeeObj.loadSelectionNodes();
    });
    $('#more_feeRule').on('shown.bs.modal',function () {
        if(installationFeeObj.moreFeeRuleSpread == null){//初始化显示
            installationFeeObj.initMoreFeeRuleSpread();
        }
        installationFeeObj.showMoreFeeRule();
    });

    $('#modify_feeRule').on('shown.bs.modal',function () {
        installationFeeObj.modifyEditedObj=null;//清空已编辑信息
        if(installationFeeObj.modifyFeeRuleSpread == null){//修改规则表格初始化
            installationFeeObj.initModifyFeeRuleSpread();
        }
        installationFeeObj.showModifyFeeRule();
    });

    $('#positionSheetFilter').click(function (){
        installationFeeObj.positionSelectedObject = null;//清空选中记录
        installationFeeObj.filterSelectionNodes();
    });

    $('#cancelFilter').click(function (){
        installationFeeObj.positionSelectedObject = null;//清空选中记录
        installationFeeObj.loadSelectionNodes();
    });
    $('#select_position_confirm').click(function (){
        installationFeeObj.selectPositionConfirm();
    });
    $('#modify_feeRule_confirm').click(function (){
        installationFeeObj.confirmFeeRuleModify();
    });
    $('#calc_installation_fee_confirm').click(function (){
        let me = installationFeeObj;
        let info = {
            sheetName:'feeDetailSheet',
            newSelections:[{row:-1}],
            oldSelections: me.feeDetailSheet.getSelections()
        };
        let canChange = me.detailResultCheck(info);
        if(canChange==false){
            return;
        }
        me.calcInstallationFee(function () {
            gljOprObj.refreshView();
        });
    });
    $('#btn_reset_to_default').click(function (){
        let ifModel =  projectObj.project.installation_fee;
        hintBox.infoBox('操作确认', '确定恢复系统默认值吗？', 2, function () {
            ifModel.resetToDefault(function () {
                installationFeeObj.showFeeItemData();
                installationFeeObj.showFeeDetailData();
            });
            ifModel.updateInstallSetting("0",function () {
                installationFeeObj.initSettingRadio();
            });
        }, function () {

        },['确定','取消'],false);
    });

    $("input[name='install_setting_radios']").each(function(){
        $(this).click(function(){
            var settingVal = $(this).val();
            let installSetting = projectObj.project.projectInfo.property.installSetting;
            if(installSetting==settingVal){
                return;
            }
            projectObj.project.installation_fee.updateInstallSetting(settingVal);
            installationFeeObj.cleanPositionIfNeed(settingVal);
        });
    });


    $('#calc_installation_fee_close').click(function (){
        let me = installationFeeObj;
        let info = {
            sheetName:'feeDetailSheet',
            newSelections:[{row:-1}],
            oldSelections: me.feeDetailSheet.getSelections()
        }
        let canChange = me.detailResultCheck(info);
        if(canChange==false){
            return;
        }
        me.calcInstallationFee();
    });

    $('#more_feeRule_confirm').click(function (){
        let me = installationFeeObj;
        let selections = me.moreFeeRuleSheet.getSelections();
        let from = $("#more_from").val();
        $('#more_feeRule').modal('hide');
        if(selections.length>0){
            if(from =='feeDetail'){
                me.updateFeeRuleToSection(selections[0].row);
            }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
                me.updateFeeRuleToRInstall(selections[0].row);
            }
        }else {
            if(from =='feeDetail') {//在计取安装费那里点击更多
                me.refreshFeeDetailRow(me.feeDetailSheet.getSelections()[0].row);
            }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
                me.refreshRationInstallationRow(me.rationInstallSheet.getSelections()[0].row);
            }
        }
    });
    $('#more_feeRule_concel').click(function () {
        let me = installationFeeObj;
        let from = $("#more_from").val();
        if(from =='feeDetail'){//在计取安装费那里点击更多
            me.refreshFeeDetailRow(me.feeDetailSheet.getSelections()[0].row);
        }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
            me.refreshRationInstallationRow(me.rationInstallSheet.getSelections()[0].row);
        }
    });

    $('#more_feeRule_close').click(function () {
        let me = installationFeeObj;
        let from = $("#more_from").val();
        if(from =='feeDetail') {//在计取安装费那里点击更多
            me.refreshFeeDetailRow(me.feeDetailSheet.getSelections()[0].row);
        }else if(from == 'rationInstallation'){//在定额安装增加费那里点击更多
            me.refreshRationInstallationRow(me.rationInstallSheet.getSelections()[0].row);
        }
    });
});