let divideObj = {
  divideSetting:{//“类别”、“清单编号”、“名称”、“单位”、“工程量”、“单价”、“金额”、“预算价”、“取费类别”。
    header: [
      {headerName: "类别", headerWidth: 60, dataCode: "itemType", hAlign:'center', dataType: "String"},
      {headerName: "清单编号", headerWidth: 130, dataCode: "code", hAlign:'left', dataType: "String", formatter: "@"},
      {headerName: "名称", headerWidth: 250, dataCode: "name", dataType: "String",formatter: "@"},
      {headerName: "单位", headerWidth: 50, dataCode: "unit", hAlign:'center',dataType: "String",cellType:'comboBox',editable:true,options:['m', 'm2', 'm3', 'km', 't', 'kg', '台班', '工日', '昼夜', '元', '项', '处', '个', '件',
      '根', '组', '系统', '台', '套', '株', '丛', '缸', '支', '只', '块', '座', '对', '份', '樘', '攒', '榀']},
      {headerName: "工程量", headerWidth: 80, dataCode: "quantity", dataType: "Number",validator:"number",getText:"notZero"},
      {headerName: "单价", headerWidth: 80, dataCode: "marketPrice", dataType: "Number",validator:"number",getText:"notZero"},
      {headerName: "金额", headerWidth: 80, dataCode: "marketTotalFee", dataType: "Number",validator:"number",getText:"notZero"},
      {headerName: "预算价", headerWidth: 80, dataCode: "marketUnitFee", dataType: "Number",validator:"number",getText:"notZero"},
      {headerName: "取费类别", headerWidth: 60, dataCode: "programID", hAlign:'center', dataType: "String",cellType:'comboBox',editorValueType:true}
    ],
    view:{ 
      lockColumns: [0],
      rowHeaderWidth:25,
      colHeaderHeight:30
    },
    getText:{
      notZero:function (item,value) {
        return value == 0?"":value;
      }
    },
    treeCol:1
  },
  billsSelectedSetting:{
    header: [
      {headerName: "选择", headerWidth: 50, dataCode: "selected", hAlign:'left',cellType:'checkBox'},
      {headerName: "清单编号", headerWidth: 160, dataCode: "code", hAlign:'left', dataType: "String"},
      {headerName: "名称", headerWidth: 300, dataCode: "name", dataType: "String"},
      {headerName: "单位", headerWidth: 60, dataCode: "unit", hAlign:'center'},
      {headerName: "工程量", headerWidth: 80, dataCode: "quantity", dataType: "Number",validator:"number"},
      {headerName: "单价", headerWidth: 100, dataCode: "unitFee", dataType: "Number",validator:"number"},
      {headerName: "金额", headerWidth: 100, dataCode: "totalFee", dataType: "Number",validator:"number"},
      {headerName: "不可分摊", headerWidth: 80, dataCode: "unDivide", dataType: "Number",cellType:'checkBox'}
    ],
    view:{ 
      lockColumns: [0,1,2,3,4,5,6,7],
      colHeaderHeight:30
    },
    treeCol:1
  },
  execBillsSetting:{
    header: [
      {headerName: "清单编号", headerWidth: 180, dataCode: "code", hAlign:'left', dataType: "String"},
      {headerName: "名称", headerWidth: 260, dataCode: "name", dataType: "String"},
      {headerName: "分摊比例", headerWidth: 100, dataCode: "divideRate", dataType: "Number",validator:"number"}
    ],
    view:{ 
      lockColumns: [0,1],
      colHeaderHeight:30
    }
  },
  billsSetting:{
    header: [
      {headerName: "编号", headerWidth: 70, dataCode: "code", hAlign:'left', dataType: "String"},
      {headerName: "名称", headerWidth: 230, dataCode: "name", dataType: "String"},
      {headerName: "分摊比例", headerWidth: 70, dataCode: "divideRate", dataType: "Number",validator:"number"},
      {headerName: "分摊金额", headerWidth: 80, dataCode: "dividePrice", dataType: "Number",validator:"number"},
      {headerName: "原始金额", headerWidth: 80, dataCode: "originalPrice", dataType: "Number",validator:"number"},
      {headerName: "合计", headerWidth: 80, dataCode: "totalPrice", dataType: "Number",validator:"number"},
      {headerName: "金额", headerWidth: 80, dataCode: "price", dataType: "Number",validator:"number"}
    ],
    view:{ 
      lockColumns: [0,1,2,3,4,5,6],
      rowHeaderWidth:25,
      colHeaderHeight:30
    }
  },
  divideSpread:null,
  billsSpread:null,
  divideSubSpread:null,
  showDivideGljSubTab:false,
  initSpread:function(){
    this.initDivideSpread();
    this.initBillsSpread();
    this.initDivideSubSpread();
    if(!projectReadOnly){
      this.initDivideRightClick();
    }else {
      disableSpread(this.divideSpread);
      disableSpread(this.billsSpread);
      disableSpread(this.divideSubSpread);
    }
  },
  initExecSpread:function(){
    if(this.billsSelectedSpread){
      this.billsSelectedSpread.refresh();
      this.execBillsSpread.refresh();
      return;
    } 
    this.billsSelectedSpread = SheetDataHelper.createNewSpread($("#billSelectedSheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.billsSelectedSpread);
    this.billsSelectedSheet = this.billsSelectedSpread.getSheet(0);
    sheetCommonObj.initSheet(this.billsSelectedSheet, this.billsSelectedSetting);
    this.billsSelectedSpread.bind(GC.Spread.Sheets.Events.ButtonClicked, this.onbillsSelected);

    this.execBillsSpread = SheetDataHelper.createNewSpread($("#execBillSheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.execBillsSpread);
    this.execBillsSheet = this.execBillsSpread.getSheet(0);
    sheetCommonObj.initSheet(this.execBillsSheet, this.execBillsSetting);
    this.execBillsSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onExecBillsValueChange);
    this.execBillsSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onExecBillsRangeChanged); 

    SheetDataHelper.protectdSheet(this.billsSelectedSheet);
    SheetDataHelper.protectdSheet(this.execBillsSheet);
  },
  showDatas:function(){
    this.showDivideDatas();
    this.showSubDatas();
  },
  showSubDatas:function(){
    this.showBillsDatas();
    this.showRationGLJDatas();
    this.showCalcProgramDatas();
  },
  showExecDatas:function(init){
    this.showSelectedBillsDatas();
    this.showExecBillsDatas(init);
  },
  refreshViews:function(){
    if(!$('#divide_main').is(':visible')) return;
    if(this.divideSpread) this.divideSpread.refresh();
    if(this.billsSpread) this.billsSpread.refresh();
    if(this.divideSubSpread) this.divideSubSpread.refresh();
  },
  showDivideDatas:function(){
    if(!$('#divide_main_sheet').is(':visible')) return;
    this.divideDatas = getDivideDatas();
    this.divideSheet.setRowCount(this.divideDatas.length);
    let fheader= _.find(this.divideSetting.header,{'dataCode': "programID"})
    fheader.options = this.getProgramOptions();
    sheetCommonObj.showTreeData(this.divideSheet, this.divideSetting,this.divideDatas);

    function getDivideDatas(){
      let datas = [];
      let divideSetting =  projectObj.project.divide_setting.datas
      let parentMap={};

      //divideSetting.divideList = [{ID:"1",code:"1",ParentID:-1,collapsed:false},{ID:"2",code:"2",ParentID:"1",collapsed:false}]
      divideSetting.divideList = _.sortByAll(divideSetting.divideList,['seq'])
      for(let d of divideSetting.divideList){
        parentMap[d.ParentID]?parentMap[d.ParentID].push(d):parentMap[d.ParentID]=[d]
      }
      if(parentMap[-1]&&parentMap[-1].length>0){
        for(let r of parentMap[-1]){
          r.collapsed = false;
          setItemsPrice(r);
          datas.push(r)
          if(parentMap[r.ID] && parentMap[r.ID].length > 0){
            for(let c of parentMap[r.ID]){
              setItemsPrice(c);
              c.quantity = scMathUtil.roundForObj(c.quantity,getDecimal("ration.quantity")); 
              datas.push(c);
            }
          }
        }
      }
      return datas;
    }

    function setItemsPrice(item){
      if(item.fees){
        let pre = "bills";
        if(item.itemType == "定额") pre = "ration";
        let commonFee = _.find(item.fees,{"fieldName":"common"})
        if (commonFee){
          item.marketPrice =  scMathUtil.roundForObj(commonFee.unitFee,getDecimal(pre+".unitPrice"));
          item.marketTotalFee = scMathUtil.roundForObj(commonFee.totalFee,getDecimal(pre+".totalPrice"));
        }else{
          delete item.marketPrice; 
          delete item.marketTotalFee;
        }
          
      }
    }

  },


  showCalcProgramDatas:function(){
    if(!$('#divede_calc_nav').hasClass('active')) return;
    this.divideSubSpread.setActiveSheetIndex(1);
    let selected = divideObj.getSelectedItem();
    if(selected.itemType == "分摊项"){
      selected = this.calcBills(selected);
    }else{
      projectObj.project.calcProgram.innerCalcRation({data:selected, sourceType:"ration", calcType: 1, updateData:[]});
    }
    let datas = selected.calcTemplate ? selected.calcTemplate.calcItems : [];
    sheetCommonObj.initSheet(this.calcProgramSheet, calcProgramObj.setting, datas.length);
    sheetCommonObj.showData(this.calcProgramSheet, calcProgramObj.setting, datas);
    customRowHeader(this.calcProgramSheet, datas.length);
  },
  showExecBillsDatas:function(init=false){
    this.execBillsDatas = [];
    let parentMap = _.indexBy(this.selectedBillsDatas,"ParentID");
    let divideType = parseInt($("input[name='divide_type']:checked").val());
    let total = 0;
    let ctotal = 0;
    let concreteMap = {};
    let billsRationGLJMap = {};
    if(divideType == 1){//按混凝土计算
      billsRationGLJMap = _.groupBy(projectObj.project.ration_glj.datas,"billsItemID");
    }
    for(let b of this.selectedBillsDatas){
      if(b.selected == 1 && !parentMap[b.ID]){
        let newCode = this.getExeBillCode(b.ID);
        let e = {ID:b.ID,code:newCode,name:b.name,divideRate:0,totalFee:b.totalFee};
        if(b.totalFee != "") total = scMathUtil.roundForObj(total + parseFloat(b.totalFee),getDecimal("process"))
        if(divideType == 1 && billsRationGLJMap[b.ID]){
          let btotal = 0;
          for(let glj of billsRationGLJMap[b.ID]){
            //“混凝土”、“砂浆”、“配合比”。
            if(glj.type == gljType.CONCRETE || glj.type == gljType.MORTAR||glj.type == gljType.MIX_RATIO){
              let rNode = projectObj.project.mainTree.findNode(glj.rationID);
              let gquantity = gljUtil.getTotalQuantity(glj,rNode.data,getDecimal("ration.quantity"),getDecimal("glj.quantity"));
              btotal = scMathUtil.roundForObj(btotal + parseFloat(gquantity),getDecimal("process"));
            }
          }
          btotal = scMathUtil.roundForObj(btotal,getDecimal("glj.quantity"));
          ctotal = scMathUtil.roundForObj(ctotal + btotal,getDecimal("process"));
          concreteMap[b.ID] = btotal;
        }
        this.execBillsDatas.push(e);
      }
    }
    total = scMathUtil.roundForObj(total,getDecimal("bills.totalPrice"));
    for(let e of this.execBillsDatas){
      if(init == true){//如果是初始化打开页面，要读取已经保存的分摊比例
         //使用已保存的分摊信息
         let item = divideObj.getSelectedItem();
         let IDMap = {};
         if(item.bills) IDMap = _.indexBy(item.bills,"ID");
         if(IDMap[e.ID]){
          e.divideRate = scMathUtil.roundForObj(parseFloat(IDMap[e.ID].divideRate) * 100,3);
         } 
      }else if(divideType == 0){//按清单金额比例
        if(e.totalFee != "" && total!=0) {
          totalFee = scMathUtil.roundForObj(e.totalFee,getDecimal("bills.totalPrice"));
          e.divideRate = scMathUtil.roundForObj((totalFee/total) * 100,3);
        }
      }else if(divideType == 1){//按混凝土用量
         let cquantity = concreteMap[e.ID];
         if(cquantity && ctotal != 0) e.divideRate = scMathUtil.roundForObj((cquantity/ctotal) * 100,3);
      }
      //自定义的不用管
    }
    
    sheetCommonObj.showData(this.execBillsSheet, this.execBillsSetting,this.execBillsDatas);
    this.execBillsSheet.setRowCount(this.execBillsDatas.length);
  },

  getExeBillCode:function(ID){
    let bNode = projectObj.project.mainTree.findNode(ID);
    if(!bNode) return "";
    let nodes= [];
    getNodes(bNode);
    let newCode = "";
    for(let n of nodes){
      if(n.data.code && n.data.code !=""){
        if(newCode == ""){
          newCode = n.data.code;
        }else{
          let exp = new RegExp("^"+newCode);
          if(exp.test(n.data.code)){
            newCode = n.data.code
          }else{
            let mid = "-"
            if(newCode.substr(-1,1) == "-" ||n.data.code.substr(0,1)=="-")mid="";
            newCode = newCode+mid+n.data.code
          }
        }  
      }
    }
    return newCode;


    function getNodes (node){
      nodes.unshift(node);
      if(node.parent) getNodes(node.parent);
    }


  },
  showSelectedBillsDatas:function(datas){
    if(!datas)this.selectedBillsDatas = getSelectedBillsDatas();
    this.billsSelectedSheet.setRowCount(this.selectedBillsDatas.length);
    sheetCommonObj.showTreeData(this.billsSelectedSheet, this.billsSelectedSetting,this.selectedBillsDatas);

    function getSelectedBillsDatas(){
      let datas = [];
      let item = divideObj.getSelectedItem();
      let IDMap = {};
      if(item.bills) IDMap = _.indexBy(item.bills,"ID");
      for(let n of projectObj.project.mainTree.roots){
        getDatas(n)
      }
      return datas;
      function getDatas(node){
        if(node.sourceType == "ration") return;
        let d = node.data;
        let t = {
          selected:0,
          ID:d.ID,
          code:d.code,
          name:d.name,
          unit:d.unit,
          quantity:d.quantity,
          unitFee:d.feesIndex && d.feesIndex.common && d.feesIndex.common.unitFee > 0?d.feesIndex.common.unitFee:"",
          totalFee:d.feesIndex && d.feesIndex.common && d.feesIndex.common.totalFee>0?d.feesIndex.common.totalFee:"",
          ParentID:d.ParentID,
          unDivide:0,
          collapsed:false
        };
        if(IDMap[d.ID]) t.selected = 1;
        //有基数计算的，不可选择
        if(d.calcBase&&d.calcBase!="") t.unDivide = 1;
        //数量*单价的（判断金额列是否有值）,不可选择
        if(d.calcFlag == treeNodeCalcFlag.customUnitPrice && t.totalFee !="") t.unDivide = 1;
        //不属于100-700章的，不可选择
        if(!projectObj.project.Bills.isBelongOneToSeven(node)) t.unDivide = 1;
        datas.push(t);
        if(!node.children) return;
        for(let c of node.children){
          getDatas(c);
        }

      }

    }
  },
  showRationGLJDatas:function(){
    if(!$('#divide_glj_nav').hasClass('active')) return;
    this.divideSubSpread.setActiveSheetIndex(0);
    this.rationGLJDatas = getTreeRationGLJDatas();
    let rationGLJSheet = this.divideSubSpread.getSheet(0)
    rationGLJSheet.setRowCount(this.rationGLJDatas.length);
    sheetCommonObj.showTreeData(rationGLJSheet, gljCol.ration_glj_setting,this.rationGLJDatas);
    function getTreeRationGLJDatas(){
      let datas = [];
      let temDatas=[];//临时存放主工料机
      let selected = divideObj.getSelectedItem();
      let divideSetting =  projectObj.project.divide_setting.datas;
      let projectGLJ = projectObj.project.projectGLJ
      let projectGLJData = projectGLJ.datas;
      let projectGljs = projectGLJData.gljList;
      let mixRatioMap = projectGLJData.mixRatioMap;
      if(selected && selected.itemType=="定额"){
        for(r of divideSetting.ration_gljs){
            if(r.rationID == selected.ID){
              let newr = Object.assign(r);
              newr.ParentID = -1;
              temDatas.push(newr);
            }         
        }
        if(temDatas.length > 0){
          temDatas = gljUtil.sortRationGLJ(temDatas);
          let pgljMap = _.indexBy(projectGljs, 'id');
          for(let d of temDatas){
            let glj = pgljMap[d.projectGLJID];
            if(!glj) continue;
            if(projectGLJ.isEstimateType(d.type )) d.isEstimate = glj.is_evaluate;
            d.shortName=projectGLJ.getShortNameByID(d.type);
            d.isAdd = glj.unit_price.is_add;
            d=gljOprObj.setGLJPrice(d,glj,false);//设置工料机价格
            //计算工料机的总消耗量
            d.totalQuantity = gljUtil.getTotalQuantity(d,selected,getDecimal("ration.quantity"),getDecimal("glj.quantity"));
            datas.push(d);  
            let connect_index = gljOprObj.getIndex(glj, gljKeyArray);
            if(mixRatioMap[connect_index]){//有组成物
              let mList =  gljUtil.sortMixRatio(mixRatioMap[connect_index]);
              for(let m of  mList){
                let mIndex = gljOprObj.getIndex(m,gljKeyArray);
                var mpg = _.find(projectGljs, function (item) {
                    return gljOprObj.getIndex(item,gljKeyArray) == mIndex
                });
                if(!mpg) continue;
                let tem = {
                  ParentID:d.ID,
                  projectGLJID: mpg.id,
                  code: mpg.code,
                  name: mpg.name,
                  specs: mpg.specs,
                  unit: mpg.unit,
                  type:m.type,
                  shortName: projectGLJ.getShortNameByID(m.type),
                  consumption:m.consumption,
                  rationItemQuantity: scMathUtil.roundForObj(m.consumption, getDecimal("glj.quantity")),
                  isMixRatio: true,
                  isAdd: mpg.unit_price.is_add,
                  GLJID: mpg.glj_id
                };
                if(projectGLJ.isEstimateType(mpg.type)){
                    tem.isEstimate =  mpg.is_evaluate;
                }
                tem.totalQuantity = scMathUtil.roundToString(tem.rationItemQuantity * parseFloat(d.totalQuantity), getDecimal("glj.quantity"));
                gljOprObj.setGLJPrice(tem,mpg);
                datas.push(tem);
              }
            }
          }
        }      
      }
      return datas;
    }
  },
  getGLJListByRationID:function(rationID){
    let divideSetting =  projectObj.project.divide_setting.datas;
    let datas = [];
    for(r of divideSetting.ration_gljs){
      if(r.rationID==rationID ) datas.push(r);
    }
    return datas;
  },
  getRationGLJDatas : function (ration){//这里是给计算程序统一调用的方法，树结构不用这个方法了
    let datas = [];
    let selected = ration;
    let divideSetting =  projectObj.project.divide_setting.datas;
    if(selected && selected.itemType=="定额"){
      for(r of divideSetting.ration_gljs){
          if(r.rationID == selected.ID){
            let newr = Object.assign(r);
            newr.ParentID = -1;
            datas.push(newr);
          }         
      }
      gljOprObj.combineWithProjectGlj(datas,false,selected);
    }
    return datas;
  },
  getCoeList:function(){
    let selected = this.getSelectedItem();
    let divideSetting =  projectObj.project.divide_setting.datas;
    let coeList = [];
    if(selected.itemType == "定额"){
      let assList = selected&&selected.rationAssList ? selected.rationAssList : [];
      zmhs_obj.divide_assSheetData = assList;
      for(let c of divideSetting.ration_coes){
        if(c.rationID == selected.ID) coeList.push(c);
        _.remove(coeList,{"coeID":-1});
      }
      coeList = assList.concat(coeList)
    }
    return coeList;
  },
  getCusList:function(){
    let selected = this.getSelectedItem();
    let divideSetting =  projectObj.project.divide_setting.datas;
    let cusList = [];
    if(selected.itemType == "定额"){
      for(let c of divideSetting.ration_coes){
        if(c.rationID == selected.ID && c.coeID == -1){
          zmhs_obj.divide_cusSheetData = c;
          cusList = c.coes;
          break;
        } 
      }
    }
    return cusList;
  },
  updateActualValue:async function(assList,index,newVal,isAdjust = 1){
    let item = this.getSelectedItem();
    let newList = _.cloneDeep(assList);
    if(gljUtil.isDef(newVal))newList[index].actualValue=newVal;
    newList[index].isAdjust = isAdjust;
    let u = {ID:item.ID,type:'update',updateAss:true,doc:{rationAssList:newList}}
    await this.updateItem([u]);
    await this.calcDivideItem(item);
    zmhs_obj.showDatas();
  },
  getStableList:function(){
    return this.rationGLJDatas.filter(glj => !glj.isMixRatio && glj.rationProportion);
  },
  updateProportion:async function(datas){
    let updateDatas = [];
    let item = this.getSelectedItem();
    for(let d of datas){
      updateDatas.push({ID:d.ID,type:'update',rationID:item.ID,model:'ration_gljs',updateProportion:true,doc:{"adjustProportion":d.adjustProportion}});
    }
    await this.updateItem(updateDatas);
    await this.calcDivideItem(item);
    zmhs_obj.showDatas();
  },
  updateCoeAdjust:async function(data){
    console.log(data);
    let divideSetting =  projectObj.project.divide_setting.datas;
    data.divideID = divideSetting.ID;
    try {
      $.bootstrapLoading.start();
      let result = await ajaxPost("/divide/updateCoeAdjust",data)
      this.refreshDivideCaches(result.updateDatas);
      if(result.projectGLJList && result.projectGLJList.length > 0) projectObj.project.projectGLJ.loadNewProjectGLJToCaches(result.projectGLJList);   
      if(result.ration_gljs && result.ration_gljs.length > 0) divideSetting.ration_gljs = divideSetting.ration_gljs.concat(result.ration_gljs);
      if(result.delete && result.delete.length > 0){
        _.remove(result.ration_gljs,function(o){
          return _.includes(result.delete,o.ID)
        })
      }
    } catch (error) {
      console.log(error)
    }
    $.bootstrapLoading.end();
    await this.calcDivideItem(this.getSelectedItem());
    this.showDatas();
    zmhs_obj.showDatas();
  },

  getProgramOptions:function(){
    let names = projectObj.project.calcProgram.compiledTemplateNames;
    let map = projectObj.project.calcProgram.compiledTemplateMaps;
    let options = [];
    for(let n of names){
      options.push({text:n,value:map[n]});
    }
    return options;

  },
  divideEditChecking:function(row,col){//return false表示不能编辑
    let me = this;
    let data = me.divideDatas[row],setting = me.divideSetting;
    let dataCode = setting.header[col].dataCode;
    if(data){
      if(data.itemType == "分摊项"){
        //金额，预算价,取费类别不可编辑
        if(dataCode =="marketTotalFee" || dataCode =="marketUnitFee" || dataCode =="programID" ) return false;
        //有子项时，单价不可编辑
        if(dataCode =="marketPrice"&& _.find(me.divideDatas,{ParentID:data.ID})) return false;
      }
      if( data.itemType == "量价" && dataCode =="marketTotalFee") return false//量价：“金额”不可编辑。
      if(data.itemType == "定额"){ //定额：“单位”、“单价”、“金额”、“预算价”
        return !(dataCode == "unit"||dataCode == "marketUnitFee"||dataCode == "marketTotalFee"||dataCode == "marketPrice")
      } 
      return true
    }
    return false;  
  },

  rationGLJEditChecking:function(row,col){//return false表示不能编辑
    let me = this;
    let data = me.rationGLJDatas[row],setting = gljCol.ration_glj_setting;
    let dataCode = setting.header[col].dataCode;
    if(dataCode=="basePrice") return false;
    if(data.isMixRatio == true && dataCode=="customQuantity") return false;
    for(let r of me.rationGLJDatas){
      if(r.ParentID == data.ID) return false;
    }  
    return true;
  },

  calcExecBillsData:function(){
    let item = divideObj.getSelectedItem();
    for(let b of this.execBillsDatas){
      let bNode = projectObj.project.mainTree.findNode(b.ID);
      if (!bNode) continue;
      if(!b.divideRate) continue;
      b.dividePrice =0;
      b.originalPrice=0;
      b.totalPrice =0;
      b.price= b.price?b.price:0;
      b.divideRate = scMathUtil.roundForObj(b.divideRate * 0.01,3);
      b.dividePrice = scMathUtil.roundForObj(item.marketTotalFee * b.divideRate,getDecimal("bills.totalPrice"));  
      b.originalPrice = calcOriginalPrice(bNode);   
      b.totalPrice = scMathUtil.roundForObj(b.dividePrice + b.originalPrice,getDecimal("bills.totalPrice"));
    }

    function calcOriginalPrice(node){//计算原始金额，清单下的除分摊下的所有定额的值汇总
      let sum = 0; 
      if(node.children){
        for(let c of node.children){
          if(c.data.divideID && c.data.divideID!="") continue;
          if(c.data.feesIndex && c.data.feesIndex.common){
            let totalFee =  scMathUtil.roundForObj(c.data.feesIndex.common.totalFee,getDecimal("bills.totalPrice"))
            sum = scMathUtil.roundForObj(sum + totalFee,getDecimal("process")); 
          } 
        }
      }
      return scMathUtil.roundForObj(sum,getDecimal("bills.totalPrice")); 
    }

  },

  showBillsDatas:function(){
    if(!$('#divide_bills_sheet').is(':visible')) return;
    this.billsDatas = getBillsDatas();
    sheetCommonObj.showData(this.billsSheet, this.billsSetting,this.billsDatas);
    this.billsSheet.setRowCount(this.billsDatas.length);

    function getBillsDatas(){
      let datas = [];
      let item = divideObj.getSelectedItem();
      if(item.bills){
        for(let b of item.bills){
          if(b.divideRate > 0) datas.push(b);
        }
      }
      return datas;
    }
  },
  getSelectedItem:function(){
    let me = this,data=null;
    let sel = me.divideSheet.getSelections()[0];
    let srow = sel.row == -1||sel.row == ""?0:sel.row;
    if(me.divideDatas.length>srow){
        data = me.divideDatas[srow];
    }
    return data;
  },
  addNewItems:async function(itemType,type){
    let newItem = {
      ID:uuid.v1(),
      itemType:itemType,
      ParentID:-1
    };
    if(type) newItem.subType = type;
    let selected = this.getSelectedItem();
    if(itemType!="分摊项"){//当插入定额或者量价时：
      newItem.divideType = 0;
      newItem.ParentID = selected.itemType == "分摊项"?selected.ID:selected.ParentID;
      newItem.fees = [{fieldName:"common",tenderTotalFee:0,unitFee:0,totalFee:0,tenderUnitFee:0}];
    }
    if(itemType == "定额") newItem.type = rationType.ration;
    if(itemType == "量价"){
      newItem['programID'] = projectObj.project.calcProgram.compiledTemplateMaps["费率为0"];
      newItem.type = rationType.volumePrice;
    } 

    let [seq,datas] = this.getNewSeqs(selected,newItem);
    newItem.seq = seq;
    datas.push({type:"add",doc:newItem});
    await this.updateItem(datas);
    await this.calcDivideItem(newItem);
  },
  calcBills:function(bills,deleteMap){
    let divideSetting =  projectObj.project.divide_setting.datas;
    let subNodes = [];
    let item=null;
    for(let c of divideSetting.divideList){
      if(c.ParentID == bills.ID){
        if(deleteMap && deleteMap[c.ID]) continue;
        this.initFeeIndexs(c);
        subNodes.push({data:c, sourceType:"ration", calcType: 1, updateData:[]});
      } 
      if(c.ID == bills.ID) item = c;
    }
    this.initFeeIndexs(item);
    if(subNodes.length > 0||deleteMap){
      projectObj.project.calcProgram.innerCalcBill({data:item, sourceType:"bills", updateData:[],children:subNodes},3);
    }else if(subNodes.length == 0){
      item.calcFlag = 2;
      projectObj.project.calcProgram.innerCalcBillCustom({data:item, sourceType:"bills", updateData:[],children:[]},3);
    } 
    return item;
  },
  initFeeIndexs:function(item){
    item.feesIndex = {};
    if(item.fees){
      for(let f of item.fees){
        item.feesIndex[f.fieldName] = f;
      }
    }
  },
  deleteItem:async function(){
    let selected = this.getSelectedItem();
    let subItems = [];
    if(selected.itemType == "分摊项"){
      //检查是否执行了分摊，如果已经执行了，要取消分摊才能删除
      // todo
      for(let s of this.divideDatas){
        if(s.ParentID == selected.ID) subItems.push({type:"delete",ID:s.ID});
      }
    }else{
      let deleteMap = {};
      deleteMap[selected.ID] = true;
      let item = this.calcBills({ID:selected.ParentID},deleteMap);
      subItems.push({ID:item.ID,type:'update',doc:{fees:item.fees}});  
    }
    subItems.push({type:"delete",ID:selected.ID,itemType:selected.itemType});
    await this.updateItem(subItems);
    zmhs_obj.showDatas();
  },
  getNewSeqs:function(selected,newItem){
    let seq = 1,datas=[],refreshSeq = false;
    for(let d of this.divideDatas){
      if(d.ParentID == newItem.ParentID){
        if(refreshSeq == true){
          if(d.seq == seq || d.seq > seq) datas.push({ID:d.ID,type:'update',doc:{seq:d.seq+1}})
        }
        if(selected && d.ID == selected.ID){
          seq = d.seq + 1;
          refreshSeq = true;
        }
      }
    }
    return [seq,datas]
  },

  updateItem: async function(datas){
    let divideSetting =  projectObj.project.divide_setting.datas
    try {
      $.bootstrapLoading.start();
      let result = await ajaxPost("/divide/updateItem",{ID:divideSetting.ID,updateDatas:datas})
      this.refreshDivideCaches(result.updateDatas);
    } catch (error) {
      console.log(error)
    }
    $.bootstrapLoading.end();
    this.showDatas();
  },
  refreshDivideCaches:function(datas){
    let divideSetting =  projectObj.project.divide_setting.datas
    for(let d of datas){
      if(d.type == "add"){
        divideSetting.divideList.push(d.doc);
      }
      if(d.type == "delete"){
        _.remove(divideSetting.divideList,{'ID':d.ID});
        if(d.itemType =="定额"){
          _.remove(divideSetting.ration_gljs,{'rationID':d.ID});
          _.remove(divideSetting.ration_coes,{'rationID':d.ID});
        } 
      }
      if(d.type == "update"){
        let model = "divideList";
        if(d.model) model = d.model;
        let item = _.find(divideSetting[model],{'ID':d.ID});
        if(item) gljUtil.updateProperty(item,d.doc);
      }
    }
  },
  addDivideRation:async function(rationRepId,code){
    let selected = this.getSelectedItem();
    if(!selected) return;
    let divideSetting =  projectObj.project.divide_setting.datas
    let pEngineer = projectObj.project.projectInfo.property.projectEngineering;
    let libIDs = [rationRepId];
    let defaultLibID = rationLibObj.getDefaultStdRationLibID();
    let data = {userID:userID,defaultLibID:defaultLibID, rationRepIds: libIDs, code: code,quantityDecimal:getDecimal("ration.quantity"),projectID:projectObj.project.ID()};
    data.ParentID = selected.itemType == "分摊项"?selected.ID:selected.ParentID;
    let [seq,datas] = this.getNewSeqs(selected,data);
    data.type="add";
    data.seq = seq;
    data.divideID = divideSetting.ID;
    if(pEngineer) data.programID = pEngineer;
    data.divideDatas = datas;
    let sel = this.divideSheet.getSelections()[0];
    await this.updateDivideRation(data);
    this.divideSheet.setSelection(sel.row+1,sel.col,sel.rowCount,sel.colCount);
    this.showSubDatas();
    zmhs_obj.showDatas();
  },
  updateDivideRation:async function(data){
    let divideSetting =  projectObj.project.divide_setting.datas;
    let newRation = null;
    try {
      $.bootstrapLoading.start();
      let result = await ajaxPost("/ration/updateDivideRation",data)
      if(data.type=="add"){
        data.divideDatas.push({type:"add",doc:result.ration});
        this.refreshDivideCaches(data.divideDatas);
        newRation = result.ration;
        if(result.projectGLJList) projectObj.project.projectGLJ.loadNewProjectGLJToCaches(result.projectGLJList,true);   
        if(result.ration_gljs) divideSetting.ration_gljs = divideSetting.ration_gljs.concat(result.ration_gljs);
        if(result.ration_coes) divideSetting.ration_coes = divideSetting.ration_coes.concat(result.ration_coes);
      }else if(data.type == "update"){//这里只有替换定额用到
        newRation = result.ration;
        divideSetting.divideList.push(newRation);
        if(result.projectGLJList) projectObj.project.projectGLJ.loadNewProjectGLJToCaches(result.projectGLJList,true);   
        if(result.ration_gljs) divideSetting.ration_gljs = divideSetting.ration_gljs.concat(result.ration_gljs);
        if(result.ration_coes) divideSetting.ration_coes = divideSetting.ration_coes.concat(result.ration_coes);
        _.remove(divideSetting.divideList,{'ID':data.rationID});
        _.remove(divideSetting.ration_gljs,{'rationID':data.rationID});
        _.remove(divideSetting.ration_coes,{'rationID':data.rationID});
      }
      await this.calcDivideItem(newRation);   
    } catch (error) {
      console.log(error)
      this.showDatas();
    }
    $.bootstrapLoading.end();
  },
  calcDivideAfterGLJUpdate:async function(gljs){
    let divideSetting =  projectObj.project.divide_setting.datas
    let indexMap = {};
    let rationIDMap = {};
    let rations = [];
    for(let glj of gljs){
      let index = gljUtil.getIndex(glj);
      indexMap[index] = true;
    }
    for(let rg of divideSetting.ration_gljs){    
       if(indexMap[gljUtil.getIndex(rg)]){
         rationIDMap[rg.rationID] = true;
       }
    }
    if(_.isEmpty(rationIDMap)) return;
    for(let d of divideSetting.divideList){
      if(rationIDMap[d.ID]){
        rations.push(d)
      }
    }
    if(rations.length > 0){
      let updateDatas= this.getCalcDivideDatas(rations);
      updateDatas.length > 0?await this.updateItem(updateDatas):this.showDatas();
    }
  },

  calcDivideItem:async function(divide){
    let updateDatas= this.getCalcDivideDatas([divide]);
    updateDatas.length > 0?await this.updateItem(updateDatas):this.showDatas();
  },
  getCalcDivideDatas:function(divides){
    let updateDatas = [];
    let divideSetting =  projectObj.project.divide_setting.datas
    let parentMap={};
    let parents=[];
    for(let divide of divides){//先计算所有子项和传入的分摊项（与传入子项不关联，因为计算子项时会计算对应的分摊项）
      if(divide.itemType != "分摊项"){//不是分摊项，调用计算程序
        divide.fees=[];
        divide.feesIndex={};
        projectObj.project.calcProgram.innerCalcRation({data:divide, sourceType:"ration", calcType: 1, updateData:[]});
        if(divide.itemType == "定额"){
          updateDatas.push({ID:divide.ID,type:'update',doc:{fees:divide.fees}});  
        }else{
          updateDatas.push({ID:divide.ID,type:'update',doc:{fees:divide.fees,marketUnitFee:divide.marketUnitFee}});
        } 
        parentMap[divide.ParentID] = [];
      }else{
        divide = this.calcBills(divide);
        updateDatas.push({ID:divide.ID,type:'update',doc:{fees:divide.fees}});  
      }
    }
    for(let c of divideSetting.divideList){
      if(parentMap[c.ID]) parents.push(c);//把所有父节点挑出来
      if(parentMap[c.ParentID]){
        let t = c.ID != divide.ID?c:divide;
        this.initFeeIndexs(t);
        //生成并归类父节点对应的子节点（用于父节点的计算）
        parentMap[c.ParentID].push({data:t, sourceType:"ration", calcType: 1, updateData:[]});
      }
    }
    for(let p of parents){
      p.fees=[];
      p.feesIndex={};
      projectObj.project.calcProgram.innerCalcBill({data:p, sourceType:"bills", updateData:[],children:parentMap[p.ID]},3);
      updateDatas.push({ID:p.ID,type:'update',doc:{fees:p.fees}});  
    }  
    return updateDatas;
  },

  getTotolFee:function name(divide) {
    if(divide.itemType == "定额"){
      let comnonFee = _.find(divide.fees,{"fieldName":"common"})
      return comnonFee && comnonFee.totalFee ? comnonFee.totalFee:0;
    }else if(divide.itemType == "量价"){
      return divide.marketTotalFee;
    }
  },

  updateCustomerCoe:function(result){
    console.log(result);
  },
  initDivideSpread:function(){
    if(this.divideSpread) return;
    this.divideSpread = SheetDataHelper.createNewSpread($("#divide_main_sheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.divideSpread);
    this.divideSheet = this.divideSpread.getSheet(0);
    sheetCommonObj.initSheet(this.divideSheet, this.divideSetting, 2);
    this.divideSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onDivideEditStarting);
    this.divideSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onDivideValueChange);
    this.divideSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onDivideSelectionChange);  
    this.divideSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onDivideRangeChanged); 

    SheetDataHelper.protectdSheet(this.divideSheet);
  },
  onDivideEditStarting:function (sender, args) {
    let me = divideObj;
    let row = args.row;
    let col = args.col;
    if(me.divideEditChecking(row,col)==false){
        args.cancel = true;
    }
  },
  onRationGljEditStarting:function(sender,args){
    let me = divideObj;
    let row = args.row;
    let col = args.col;
    if(divideObj.rationGLJEditChecking(row,col)==false){
      args.cancel = true;
    }
  },
  onRationGLJRangeChanged:async function(e,args){
    for(let c of args.changedCells){
      let value=  args.sheet.getCell(c.row, c.col).text();
      if(divideObj.rationGLJEditChecking(c.row,c.col)==false){
        return divideObj.showRationGLJDatas();
      }
      divideObj.onRationGLJValueChange(e,{row:c.row,col:c.col,newValue:value,sheet:args.sheet});
    }
  },

  onExecBillsRangeChanged:async function(e,args){
    for(let c of args.changedCells){
      let value=  args.sheet.getCell(c.row, c.col).text();
      divideObj.onExecBillsValueChange(e,{row:c.row,col:c.col,newValue:value,sheet:args.sheet});
    }
  },

  onExecBillsValueChange:function(sender,info){
    let me = divideObj,row = info.row, col = info.col;
    let setting = me.execBillsSetting;
    let dataCode = setting.header[col].dataCode;
    let record = me.execBillsDatas[row];
    let value = info.newValue;
    if(value && !sheetCommonObj.checkData(col,setting,value)) {
      alert('输入的数据类型不对，请重新输入!');
      return info.sheet.setValue(row, col, record[dataCode], GC.Spread.Sheets.SheetArea.viewport);
    }
    record[dataCode] = scMathUtil.roundForObj(value,3);

  },
  onDivideRangeChanged:async function(e,args){
    for(let c of args.changedCells){
      if(divideObj.divideEditChecking(c.row,c.col)==false){
        return divideObj.showDivideDatas();
      }
      let value=  args.sheet.getCell(c.row, c.col).text();
      divideObj.onDivideValueChange(e,{row:c.row,col:c.col,newValue:value});
    }
  },

  onDivideValueChange:async function(sender,info){
    let me = divideObj,row = info.row, col = info.col;
    let setting = me.divideSetting;
    let dataCode = setting.header[col].dataCode;
    let record = me.divideDatas[row];
    let value = info.newValue;
    if(info.newValue === undefined ){
      return;
    }
    if(value && !sheetCommonObj.checkData(col,setting,value)) {
        alert('输入的数据类型不对，请重新输入!');
        return me.showDatas();
    }
    if(record.itemType=="定额" && dataCode == "code"){//替换定额
      await me.replaceDivideRation(value,record);
      return;
    }  
    await me.updateItem([me.getDivideUpdateData(record,dataCode,value)]);
    await me.calcDivideItem(record);
  },

  onRationGLJValueChange:async function(sender,info){
    let me = divideObj,row = info.row, col = info.col;
    let setting = gljCol.ration_glj_setting;
    let dataCode = setting.header[col].dataCode;
    let record = me.rationGLJDatas[row];
    let value = info.newValue;
    if(value && !sheetCommonObj.checkData(col,setting,value)) {
      alert('输入的数据类型不对，请重新输入!');
      return me.showRationGLJDatas();
    }
    if (dataCode == 'marketPrice' || dataCode == 'basePrice') {
      if(!value) value = 0;
      projectObj.project.projectGLJ.updatePriceFromRG(record, dataCode, value);
    }else if(dataCode=='customQuantity'){
      if(value) value = scMathUtil.roundForObj(value, getDecimal("glj.quantity"))
      let u= {ID:record.ID,type:'update',rationID:record.rationID,model:'ration_gljs',doc:{"customQuantity":value}}
      await me.updateItem([u]);
      await me.calcDivideItem(me.getSelectedItem());

    }
  },

  onbillsSelected:function(sender, args){
    let dataCode = divideObj.billsSelectedSetting.header[args.col].dataCode;
    if(dataCode != "selected") return;
    let checkboxValue = args.sheet.getCell(args.row, args.col).value();
    let newval = checkboxValue? 0:1;
    let data = divideObj.selectedBillsDatas[args.row];
    if(data.unDivide == 1) return;
    let parentMap = {};
    parentMap[data.ID]=true;
    data.selected=newval;
    for(let d of divideObj.selectedBillsDatas){
      if(parentMap[d.ParentID]){
        if(d.unDivide == 0) d.selected=newval;
        parentMap[d.ID] = true;
      }
    }
    divideObj.showSelectedBillsDatas(divideObj.selectedBillsDatas);
    divideObj.showExecBillsDatas();
  },

  replaceDivideRation:async function(code,record){
    let divideSetting =  projectObj.project.divide_setting.datas;
    let data = {ID:divideSetting.ID,type:"update",rationID:record.ID,code:code};
    let libIDs = rationLibObj.getStdRationLibIDs();
    let defaultLibID = rationLibObj.getDefaultStdRationLibID();
    let selectedLib =  sessionStorage.getItem("stdRationLib");
    selectedLib&&selectedLib!='undefined'?libIDs.unshift(selectedLib):libIDs.unshift(defaultLibID);
    data.userID = userID;
    data.defaultLibID = defaultLibID;
    data.rationRepIds = libIDs;
    data.quantityDecimal = getDecimal("ration.quantity");
    data.projectID = projectObj.project.ID();
    data.oldData = record;
    await this.updateDivideRation(data);
    zmhs_obj.showDatas();
  },


  onDivideSelectionChange:function(sender,args){
    let me = divideObj;
    let newSel = args.newSelections[0];
    let oldSel = args.oldSelections?args.oldSelections[0]:{};
    if(newSel.row != oldSel.row){
      me.initNavItem();
      me.showSubDatas();
      zmhs_obj.showDatas();
    }
    args.sheet.repaint();
  },
  getDivideUpdateData:function(recode,dataCode,value){
    let doc = {};
    if(recode.itemType == "分摊项"){
      if(dataCode == "quantity"){
        value = scMathUtil.roundForObj(value,3);
        let commonFee = _.find(recode.fees,{"fieldName":"common"})
        if (commonFee){
          let tu = scMathUtil.roundForObj(commonFee.unitFee&&commonFee.unitFee!=""?commonFee.unitFee:0,getDecimal("bills.unitPrice"))
          commonFee.totalFee = scMathUtil.roundForObj(value * tu,getDecimal("bills.totalPrice"));
          doc["fees"] = recode.fees;
        }
      }
      if(dataCode == "marketPrice"){
        value = scMathUtil.roundForObj(value,getDecimal("bills.unitPrice"));
        let commonFee = _.find(recode.fees,{"fieldName":"common"})
        if(!commonFee){
          commonFee = {fieldName: "common",tenderTotalFee: 0,tenderUnitFee: 0,totalFee: 0,unitFee: 0};
          recode.fees?recode.fees.push(commonFee):recode.fees=[commonFee];
        } 
        //let tu = scMathUtil.roundForObj(commonFee.unitFee&&commonFee.unitFee!=""?commonFee.unitFee:0,getDecimal("bills.unitPrice"))
        commonFee.unitFee = scMathUtil.roundForObj(value,getDecimal("bills.unitPrice"));
        doc["fees"] = recode.fees;

        return {ID:recode.ID,type:'update',doc:doc};
      }
      
    }
    if(recode.itemType =="定额"&& dataCode == 'quantity'){
      if(value){
          value = scMathUtil.roundForObj(parseFloat(value) / FilterNumberFromUnit(recode.unit),getDecimal("ration.quantity"));
      }else {
          value = 0;
      }
    }

    if(recode.itemType =="量价" && dataCode=="marketPrice") dataCode="marketUnitFee"
    doc[dataCode]=value;
    return {ID:recode.ID,type:'update',doc:doc}
  },
  initBillsSpread:function(){
    if(this.billsSpread) return;
    this.billsSpread = SheetDataHelper.createNewSpread($("#divide_bills_sheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.billsSpread);
    this.billsSheet = this.billsSpread.getSheet(0);
    sheetCommonObj.initSheet(this.billsSheet, this.billsSetting, 0);
    SheetDataHelper.protectdSheet(this.divideSheet);
  },
  initDivideSubSpread:function(){
    if(this.divideSubSpread) return;
    this.divideSubSpread = SheetDataHelper.createNewSpread($("#divide_subSpread")[0],2);
    sheetCommonObj.spreadDefaultStyle(this.divideSubSpread);
    this.divideSubSheet = this.divideSubSpread.getSheet(0);
    sheetCommonObj.initSheet(this.divideSubSheet, gljCol.ration_glj_setting, 0);
    this.divideSubSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onRationGljEditStarting);
    this.divideSubSheet.bind(GC.Spread.Sheets.Events.ValueChanged,this.onRationGLJValueChange);
    this.divideSubSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onRationGLJRangeChanged); 

    SheetDataHelper.protectdSheet(this.divideSubSheet);
    this.calcProgramSheet = this.divideSubSpread.getSheet(1);
    calcProgramObj.initSheet(this.calcProgramSheet);
  },
  initNavItem(){
    let selected = this.getSelectedItem();
    if(selected.itemType == "分摊项"){
      $("#divide_itemTextDiv").hide();
      $(`#divide_subSpread`).css('width', "100%");
    }else{
      $("#divide_itemTextDiv").show();
      if(this.showDivideGljSubTab == true){
        $("#divide_gljSubDiv").show();
        $("#divide_rgResize").show();
      } else {
          $("#divide_gljSubDiv").hide();
          $("#divide_rgResize").hide();
      }
      this.initItemWidth();
    }  
    this.divideSubSpread.refresh();
  },
  initItemWidth:function (){
    //总宽度
    let totalWidth = $('#divide_subItems').width();
    //人材机和项目特征文本比例
    const openWidth = 30;//打开项目特征工具条
    const tab_tem = (305+openWidth+10)/totalWidth;//tab显示框默认宽度:305(表格宽度) + 30（工具条宽度）+10(resize div 宽度)
    let //默认比例
        textPercent = tab_tem * 100 + '%',//'15%',
        rcjPercent = (1 - tab_tem)* 100 + '%';//85
    //文本没显示，则打开工具条固定30px转换百分比
    if (!this.showDivideGljSubTab) {
        textPercent = openWidth / totalWidth;
        rcjPercent = 1 - textPercent;
        textPercent = textPercent * 100 + '%';
        rcjPercent = rcjPercent * 100 + '%';
    }
    //设置特征及内容与排版规则的比例
    $('#divide_subSpread').css('width', rcjPercent);
    $('#divide_itemTextDiv').css('width', textPercent);
    //打开了项目特征，则继续加载人材机表和项目特征文本具体比例
    if (divideObj.showDivideGljSubTab === true) {
        let rg_sideResizeEles = this.getSubSideResize();
        SlideResize.loadHorizonWidth(rg_sideResizeEles.eleObj.module,
            [rg_sideResizeEles.eleObj.resize], [rg_sideResizeEles.eleObj.left, rg_sideResizeEles.eleObj.right]);
        $("#divide_gljSubDiv").width( $('#divide_itemTextDiv').width() - rg_sideResizeEles.eleObj.resize.width() - 30);

    }
  },
  initDivideGljSubTab:function(){
    if(this.showDivideGljSubTab == true){
      $("#divide_gljSubDiv").show();
      $("#divide_rgResize").show();
    } else {
        $("#divide_gljSubDiv").hide();
        $("#divide_rgResize").hide();
    }
    this.initItemWidth();
  },
  getSubSideResize: function () {
    let rg_sideResizeEles = {};
    rg_sideResizeEles.eleObj = {
        module: this.moduleName,
        resize: $('#divide_rgResize'),
        parent: $('#divide_subItems'),
        left: $('#divide_subSpread'),
        right: $('#divide_itemTextDiv')
    };
    rg_sideResizeEles.limit = {
        min: 100,
        max: `$('#divide_subItems').width()-100`
    };
    return rg_sideResizeEles;
  },
  initDivideRightClick:function(){
    //如果当前行是无组成物的“普通材料”、“绿化苗木”、“外购砼构件”、“商品混凝土”、“商品砂浆”，则右键“添加计算材料”按钮有效。
    let me = this;
    $.contextMenu({
        selector: '#divide_main_sheet',
        build: function ($trigger, e) {
            me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, me.divideSpread);
            return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
        },
        items: {
            "insertItem": {
                name: "插入分摊项",
                icon: 'fa-sign-in',
                disabled: function () { 
                  let selected = me.getSelectedItem();
                  if(selected && selected.itemType !="分摊项") return true;
                  return false;
                },
                callback: function (key, opt) {
                  me.addNewItems("分摊项");
                }
            },
            "insertRation": {
                name: "插入定额",
                icon: 'fa-sign-in',
                disabled: function () {
                  return me.rightClickTarget.row === undefined
                },
                callback: function (key, opt) {  
                  me.addNewItems("定额");
                }
            },
            "insertVolumePrice": {
                name: "插入量价",
                icon: 'fa-sign-in',
                disabled: function () {
                  return me.rightClickTarget.row === undefined;
                },
                items:{
                  insertLabour:{
                      name: "人工",
                      icon: 'fa-sign-in',
                      callback:function(key){
                        me.addNewItems("量价",1);
                      }
                  },
                  insertMaterial:{
                     name:"材料" ,
                      icon: 'fa-sign-in',
                      callback:function(key){
                        me.addNewItems("量价",201);
                      }
                  },
                  insertMachine:{
                      name:"机械" ,
                      icon: 'fa-sign-in',
                      callback:function(key){
                        me.addNewItems("量价",301);
                      }
                  }
                }
            },
            "removeItem": {
                name: "删除",
                icon: 'fa-trash-o',
                disabled: function () {
                    return  me.rightClickTarget.row === undefined;;
                },
                callback: function (key, opt) {  
                  me.deleteItem();
                }
            }
        }
    });
  },

  getDivideResizeEles:function () {
    let divideResizeEles = {};
    divideResizeEles.eleObj = {
        module: 'divide',
        resize: $('#divideResize'),
        top: $('#divide_top'),
        topSpread: $('#divide_main_sheet'),
        bottom: $('#divideBottom'),
        bottomSpread: [$('#divide_subSpread'),$('#divide_itemTextDiv'),$('#divide_gljSubDiv'),$('#divide_gljItemTab')]
    };

    divideResizeEles.limit = {
        min: 150,
        max: `$(window).height()-$('.header').height()-$('#divideToolsBar').height()-150-5`,//5: resize.height()
        notTopSpread: 0,
        notBottomSpread: 0,
        bottomNav:`$('#divideBottom ul').height()`,
        totalHeight: `$(window).height()-$('.header').height()-$('#divideToolsBar').height()-5`
    };
    return divideResizeEles;
  },
  calcDivideNodes : async function(item,bills,callback){
    if(!item.marketTotalFee) return;
    let changeNode=[];
    let datas = [];
    let usedIDMap={};
    for(let b of bills){
      let bNode = projectObj.project.mainTree.findNode(b.ID);
      if(!bNode) continue;
      let divideRate = scMathUtil.roundForObj(b.divideRate,3);
      let marketUnitFee = item.marketPrice?scMathUtil.roundForObj(item.marketPrice,getDecimal("bills.unitPrice")):0;
      let quantity = item.quantity?scMathUtil.roundForObj(item.quantity,3):0;
      quantity = scMathUtil.roundForObj(quantity*divideRate,getDecimal("ration.quantity"))//量价数量为分摊项的数量*分摊比例
      if(quantity > 0 && marketUnitFee > 0){
        let serialNo = 0;
        let preID = "";
        let divdeNode = null;
        for(let cNode of bNode.children ){
          if(cNode.data.divideID == item.ID){//说明已经存在了自动生成的量价，更新一下数据就行
            let doc = {};
            usedIDMap[cNode.data.ID] = true;
            divdeNode = cNode;
            if(cNode.data.name != item.name) doc.name = item.name;
            if(cNode.data.unit != item.unit) doc.unit = item.unit;
            if(cNode.data.quantity != quantity) doc.quantity = quantity;
            if(cNode.data.marketUnitFee != marketUnitFee) doc.marketUnitFee = marketUnitFee;
            if(!_.isEmpty(doc)){
              doc.ID = cNode.data.ID;
              datas.push({type:ModuleNames.ration,data:doc})
              break;
            }
          }
          preID = cNode.data.ID;
          serialNo = cNode.data.serialNo;
        }
        if(divdeNode == null){//说明需要新增
          let newID = uuid.v1() 
          let newData = projectObj.project.Ration.getTempRationData(newID, b.ID, serialNo+1, rationType.volumePrice);
          newData.name = item.name;
          newData.unit = item.unit;
          newData.quantity = quantity; 
          newData.marketUnitFee = marketUnitFee;
          newData.divideID = item.ID;
          datas.push({type:ModuleNames.ration,data:newData,preSiblingID:preID,action:"add",parentID:b.ID});
        }
      }
    }
    //删除之前生成的，但是这次执行时没有用的节点
    for(let r of projectObj.project.Ration.datas){
       if(r.divideID == item.ID){
         if(!usedIDMap[r.ID]){//没有用的删除
          datas.push({type:ModuleNames.ration,data:{ID:r.ID},action:"delete"});
          let pNode = projectObj.project.mainTree.findNode(r.billsItemID);
          if(pNode)changeNode.push(pNode);
         }
       }
    }
    if(datas.length == 0){//分摊的定额没有变，但是清单的金额可能变了，所以要更新
      reCalcAfterUpdateNodes(bills);
      return callback();
    }  
    //刷新缓存和树节点的插入删除
    let nodes = await projectObj.project.syncUpdateNodesAndRefresh(datas);
    //重新计算
    cbTools.refreshFormulaNodes();
    projectObj.project.calcProgram.calcNodesAndSave(changeNode.concat(nodes),function(){
      reCalcAfterUpdateNodes(bills);
      callback();
    });
    function reCalcAfterUpdateNodes(bills){
      //反算分摊右边表中的金额
      for(let b of bills){
        let bNode = projectObj.project.mainTree.findNode(b.ID);
        if(bNode.data.feesIndex&&bNode.data.feesIndex.common){
          let totalFee = scMathUtil.roundForObj(bNode.data.feesIndex.common.totalFee,getDecimal("bills.totalPrice"));
          b.price = totalFee;   
        }
      } 
    }


  },
  cancelDivide:async function(divideID){//如果不传ID，相当于取消所有
     let changeNode=[],datas=[],itemDatas=[];
     let divideSetting =  projectObj.project.divide_setting.datas
     for(let d of divideSetting.divideList){
        if(d.itemType == "分摊项"){
          if(divideID && d.ID != divideID) continue;
          if(d.bills && d.bills.length > 0){
            itemDatas.push({ID:d.ID,type:'update',doc:{bills:[],divideType:0}});
          }
       }
      }
      if(itemDatas.length > 0) await this.updateItem(itemDatas);

     for(let r of projectObj.project.Ration.datas){
      if(!r.divideID || r.divideID=="") continue;
      if(divideID && r.divideID != divideID)  continue;
      datas.push({type:ModuleNames.ration,data:{ID:r.ID},action:"delete"});
      let pNode = projectObj.project.mainTree.findNode(r.billsItemID);
      if(pNode)changeNode.push(pNode);
    }
    if(datas.length == 0) return;
  //刷新缓存和树节点的插入删除
    let nodes = await projectObj.project.syncUpdateNodesAndRefresh(datas);
    //重新计算
    cbTools.refreshFormulaNodes();
    projectObj.project.calcProgram.calcNodesAndSave(changeNode.concat(nodes));
  }
}



function loadDivideHeight(){
  if(!$('#divide_main').is(':visible')) return;
  let me = divideObj;
  let divideResizeEles = me.getDivideResizeEles();
  SlideResize.loadVerticalHeight(divideResizeEles.eleObj.module, divideResizeEles.eleObj, divideResizeEles.limit, function () {
      me.refreshViews();
      zmhs_obj.refresh();
  });
  
  SlideResize.verticalSlide(divideResizeEles.eleObj, divideResizeEles.limit, function(){
    me.refreshViews();
    zmhs_obj.refresh();
  });
  if($('#divide_de').is(':visible')) showDivideSide($($("#divide_stdRationTab").attr('relaPanel')), true, $("#divide_stdRationTab").attr('id'));
}

$('#tab_divide').on('shown.bs.tab', function (e) {
  sessionStorage.setItem('mainTab', '#tab_divide');
  $('#divide_bills_sheet').width($('#divide_bills_div').width()-$('#divideMiddleResize').width());
  loadDivideHeight();
  divideObj.initSpread();
  divideObj.showDatas();
  divideObj.initNavItem();

})

$('.divide-nav-link').bind('click', function () {//$('.side-tabs ul li a').bind   2018-11-23  使用更多标签，所以不能这样绑定事件了
    if(projectReadOnly) return;
    var tab = $(this), tabPanel = $(tab.attr('relaPanel'));
    if(tab.hasClass('disabled')){
        return;
    }
    let setActiveTab = tab;
    if (!(setActiveTab.hasClass('active')&&tabPanel.is(":visible"))) {
        $('.divide_side-tabs ul li a').removeClass('active');
        setActiveTab.addClass('active');
        showDivideSide(tabPanel, true, tab.attr('id'));
    } else {
        setActiveTab.removeClass('active');
        showDivideSide(tabPanel, false, tab.attr('id'));
    }
    divideObj.refreshViews();  
    
});


//定额库上下拖动
let dividRationLibResizeEles = {};
dividRationLibResizeEles.eleObj = {
    module: 'divide_de',
    resize: $('#divide_deResize'),
    top: $('#divide_deTopDiv'),
    topSpread: $('#divide_stdRationChapter'),
    bottom: $('#divide_deBottomDiv'),
    bottomSpread: $('#divide_stdSectionRations')
};
dividRationLibResizeEles.limit = {
    min: 150,
    max: `$(window).height()-$('.header').height()-$('.toolsbar').height()-$('#deToolsBar').height()-150-5`,//5: resize.height()
    notTopSpread: 0,
    notBottomSpread: 0,
    totalHeight: `$(window).height()-$('.header').height()-$('.toolsbar').height()-$('#divide_deToolsBar').height()-5`
};

function getDivideSideResizeEles(){
  let divideSideResizeEles = {};
  divideSideResizeEles.eleObj = {
      module: 'divideRationLibTab',
      resize: $('#divideSideResize'),
      parent: $('#divideRow'),
      left: $('#divide_main'),
      right: $('#divide_side')
  };
  divideSideResizeEles.limit = {
      min: 150,
      max: `$('#divideRow').width()-150`
  };
  return divideSideResizeEles;
}

let dSideResizeEles =  getDivideSideResizeEles();
//水平拖动
SlideResize.horizontalSlide(dSideResizeEles.eleObj, dSideResizeEles.limit, function(){
  SlideResize.loadVerticalHeight(dividRationLibResizeEles.eleObj.module, dividRationLibResizeEles.eleObj, dividRationLibResizeEles.limit, function () {
    if(rationLibObj.divide_rationChapterSpread) rationLibObj.divide_rationChapterSpread.refresh();
    if(rationLibObj.divide_sectionRationsSpread) rationLibObj.divide_sectionRationsSpread.refresh();
  });
  divideObj.refreshViews();  
});

function getDivideLeftAndRightReside(){
  return {
    eleObj:{
      module: 'divideLeftRight',
      resize: $('#divideMiddleResize'),
      parent: $('#divide_top'),
      left: $('#divide_main_sheet'),
      right: $('#divide_bills_div')
    },
    limit:{
      min: 150,
      max: `$('#divide_top').width()-150`
    }
  }
}

//分摊左和右表水平拖动
let divideLeftAndRight = getDivideLeftAndRightReside();
SlideResize.horizontalSlide(divideLeftAndRight.eleObj, divideLeftAndRight.limit, function(){
  if(divideObj.divideSpread) divideObj.divideSpread.refresh();
  if(divideObj.billsSpread) divideObj.billsSpread.refresh();
});


function showDivideSide(tabPanel, show, id){
  let divideSideResizeEles = getDivideSideResizeEles();
  divideSideResizeEles.eleObj.module = id;
  if (show) {
      //刚打开各库时的默认比例
      divideSideResizeEles.eleObj.left.css('width', '66.666667%');
      divideSideResizeEles.eleObj.right.css('width', '33.333333%');
      SlideResize.setResizeWidth(divideSideResizeEles.eleObj.resize);
      $('.divide_side .tab-pane').hide();
      tabPanel.show();//locateTab要等div显示后才执行刷新操作
      //加载打开的库与主界面的宽度比
      SlideResize.loadHorizonWidth(id, [divideSideResizeEles.eleObj.resize], [divideSideResizeEles.eleObj.left, divideSideResizeEles.eleObj.right], function(){      
        if (id === 'divide_stdRationTab') {//加载定额库内部上下高度
            SlideResize.loadVerticalHeight(dividRationLibResizeEles.eleObj.module, dividRationLibResizeEles.eleObj, dividRationLibResizeEles.limit, function () {
              if(rationLibObj.divide_rationChapterSpread) rationLibObj.divide_rationChapterSpread.refresh();
              if(rationLibObj.divide_sectionRationsSpread) rationLibObj.divide_sectionRationsSpread.refresh();
            });
          } 
      });
      let divideLeftAndRight = getDivideLeftAndRightReside();
      SlideResize.loadHorizonWidth(id, [divideLeftAndRight.eleObj.resize], [divideLeftAndRight.eleObj.left, divideLeftAndRight.eleObj.right], function(){      
        if(divideObj.divideSpread) divideObj.divideSpread.refresh();
        if(divideObj.billsSpread) divideObj.billsSpread.refresh();
      });
  } else {
      divideSideResizeEles.eleObj.left.css('width', '100%');
      divideSideResizeEles.eleObj.right.css('width', '0%');
      tabPanel.hide();
  }
}

$('#divide_stdRationTab').bind('click', function () {
  if(projectReadOnly) return;
  var select = $('#divide_stdRationLibSelect');
  rationLibObj.checkSpread('divide');
  if (select[0].options.length === 0) {
      rationLibObj.loadStdRationLibs('divide');
      //rationLibObj.loadStdRationContextMenu();
  }; 
  divideObj.initNavItem();
});



$('#divide_stdRationLibSelect').change(function () {
  var select = $(this);
  if (this.children.length !== 0) {
      let rationLibId = select.val();
      sessionStorage.setItem('divide_stdRationLib', rationLibId);
      sessionStorage.removeItem('divide_stdRationLibExpState');
      rationLibObj.loadStdRation(rationLibId,'divide');
  }
});

$('.divide_gljSubTab ul li a').bind('click',function () {
  if(this.hash =="#divide_rnc-close"){
    $("#divide_zmhs_nav").hide();
    $("#divide_zmhs_toogle").show();
    closeTab(this);
    divideObj.showDivideGljSubTab = false;
  }else{
    divideObj.showDivideGljSubTab = true;
  }
  divideObj.initDivideGljSubTab();
  if(divideObj.divideSubSpread) divideObj.divideSubSpread.refresh();
});

$('.divide_gljSubTab ul li a').on('shown.bs.tab', function () {
  if(this.hash == "#divide_rnc-zm"){
      zmhs_obj.initCoeSpread();
  }else if(this.hash == "#divide_rnc-fz"){
      zmhs_obj.initAssSpread();
  }else if(this.hash == "#divide_rnc-cus"){
      zmhs_obj.initCusSpread();
  }else if(this.hash == "#divide_rnc-stable"){
      zmhs_obj.initStableSpread();
  } 
  zmhs_obj.refresh();
  zmhs_obj.showDatas();
});

$('#divide_zmhs_toogle').bind('click',function (){
  $("#divide_zmhs_nav").show();
  if(divideObj.showDivideGljSubTab == false){
      $("#divide_hs-nav").click();
  }
   $("#divide_zmhs_toogle").hide();
});

$('#exec_divide_btn').bind('click',function (){
   if(projectReadOnly) return;
   let selected = divideObj.getSelectedItem();
   if(selected.itemType !="分摊项") return;
   $("#exec_divide_label").html(`${selected.name}<br>分摊到：`)
   $("#exec_divide_div").modal('show');
});

$('#cancel_divide_btn').bind('click',function (){
  if(projectReadOnly) return;
  let selected = divideObj.getSelectedItem();
  if(selected.itemType !="分摊项") return;
  divideObj.cancelDivide(selected.ID);
});

$('#cancel_all_divide_btn').bind('click',function (){
  if(projectReadOnly) return;
  divideObj.cancelDivide();
});

$('#divideBottom ul li a').on('shown.bs.tab',function () {
  divideObj.showRationGLJDatas();
  divideObj.showCalcProgramDatas();
});

$('#exec_divide_div').on('shown.bs.modal',function () {
  divideObj.initExecSpread();
  divideObj.showExecDatas(true);
  let selected = divideObj.getSelectedItem();
  let divideType = selected.divideType?selected.divideType:0;
  for(let radio of $(".divide_type")){
    $(radio).prop('checked', divideType == $(radio).val());
  }
  divideObj.selectedRadio=divideType;
});

$("#divide_confirm").bind('click',async function (){
  let divideType = parseInt($("input[name='divide_type']:checked").val());
  let item = divideObj.getSelectedItem();
  divideObj.calcExecBillsData();
  await divideObj.calcDivideNodes(item,divideObj.execBillsDatas,async function(){
    let updateData = {ID:item.ID,type:'update',doc:{bills:divideObj.execBillsDatas,divideType:divideType}}
    await divideObj.updateItem([updateData]);
    divideObj.showDatas();
  });
});


$("input[name='divide_type']").each(function(){
  $(this).click(function(){
      if(divideObj.selectedRadio == $(this).val()) return;
      if($(this).val() == 2)  return;
      divideObj.selectedRadio = $(this).val();
      divideObj.showExecBillsDatas();
  });
});