/**
 * Created by zhang on 2019/3/11.
 */
materialCalcObj = {
    moduleName:'materalCal',
    materialSpread:null,
    materialSheet:null,
    materialDatas:[],
    materialSetting:{
        header:[
            {headerName: "编号", headerWidth: 70, dataCode: "code", dataType: "String"},
            {headerName: "名称", headerWidth: 105, dataCode: "name", dataType: "String"},
            {headerName: "预算价", headerWidth: 60, dataCode: "marketPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "供应地点", headerWidth: 75, dataCode: "supplyLocation", hAlign: "left", dataType: "String"},
            {headerName: "原价", headerWidth: 60, dataCode: "originalPrice", hAlign: "right", dataType: "String"},
            {headerName: "单位运费", headerWidth: 60, dataCode: "unitFreight", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:'glj.unitPrice'
            {headerName: "单位毛重（吨）", headerWidth: 65, dataCode: "grossWeightCoe_n", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:"glj.unitPrice"
            {headerName: "装卸总次数", headerWidth: 53, dataCode: "totalLoadingTimes", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:"glj.unitPrice"
            {headerName: "每增加一次装卸损耗率", headerWidth: 80, dataCode: "handlingLossRate_n", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "场外运输损耗率", headerWidth: 60, dataCode: "offSiteTransportLossRate_n", hAlign: "right", dataType: "Number"},//,decimalField:"glj.unitPrice"
            {headerName: "场外运输损耗", headerWidth: 60, dataCode: "offSiteTransportLoss", hAlign: "right", dataType: "Number"},//,decimalField:"glj.unitPrice"
            {headerName: "采购及保管费率", headerWidth: 60, dataCode: "purchaseStorageRate_n", hAlign: "right", dataType: "Number"},//,decimalField:"glj.unitPrice"
            {headerName: "采购及保管费", headerWidth: 60, dataCode: "purchaseStorage", hAlign: "right", dataType: "Number"},//,decimalField:"glj.unitPrice"
            {headerName: "包装品回收价值", headerWidth: 60, dataCode: "packageRecoverValue", hAlign: "right", dataType: "Number"}//,decimalField:"glj.unitPrice"
        ],
        view: {
            lockColumns: ["code","name","marketPrice",'offSiteTransportLoss','purchaseStorage'],
            rowHeaderWidth:25,
            colHeaderHeight:36
        }
    },
    freightSpread:null,
    freightSheet:null,
    freightDatas:[],
    conveyanceOptions:["自办运输","汽车","火车","船舶","马车","手推车","拖拉机"],
    userFreightList:[],
    freightSetting:{
        header:[
            {headerName: "起讫地点", headerWidth: 85, dataCode: "start", dataType: "String"},
            {headerName: "运输工具", headerWidth: 65, dataCode: "conveyance", dataType: "String"},
            {headerName: "材料类型", headerWidth: 65, dataCode: "materialType", visible: false,dataType: "String",cellType:"comboBox",options:["","地方材料","外购材料","沥青、燃料等"]},
            {headerName: "单位运价", headerWidth: 65, dataCode: "unitFreight", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "km运距", headerWidth: 55, dataCode: "kmDistance", hAlign: "right", dataType: "String",validator:"number"},
            {headerName: "装卸费\n单价", headerWidth: 53, dataCode: "unitLoadingFee", hAlign: "right", dataType: "String",validator:"number"},
            {headerName: "装卸\n次数", headerWidth: 41, dataCode: "loadingTimes", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:'glj.unitPrice'
            {headerName: "其它\n费用", headerWidth: 41, dataCode: "otherFee", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:"glj.unitPrice"
            {headerName: "运价增\n加率(%)", headerWidth: 55, dataCode: "freightIncreaseRate", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:"glj.unitPrice"
            {headerName: "加权\n系数", headerWidth: 41, dataCode: "weightCoe", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "计算式", headerWidth: 170, dataCode: "exp", hAlign: "left", dataType: "String",getText:'forExp'},//,decimalField:"glj.unitPrice"
            {headerName: "计算方式", headerWidth: 80, dataCode: "calcType",visible: false, dataType: "String",cellType:"comboBox",options:["全国","内蒙古"]}
        ],
        view: {
            lockColumns: ["exp"],
            rowHeaderWidth:25,
            colHeaderHeight:36
        },
         getText:{
          forExp:function (item) {
             return _.isEmpty(item.exp)?materialCalcObj.getFreightEXP(item):item.exp;
          }
      }

    },
    priceSpread:null,
    priceSheet:null,
    priceDatas:[],
    priceSetting:{
        header:[
            {headerName: "供应地点", headerWidth: 80, dataCode: "supplyLocation", dataType: "String"},
            {headerName: "供应价", headerWidth: 70, dataCode: "supplyPrice", hAlign: "right", dataType: "Number",validator:"number"},
            {headerName: "加权系数", headerWidth: 80, dataCode: "coe", hAlign: "right", dataType: "Number",validator:"number"},//,decimalField:'glj.unitPrice'
        ],
        view: {
            lockColumns: [],
            rowHeaderWidth:25,
            colHeaderHeight:36
        }
    },
    freightRationSpread:null,
    freightRationSheet:null,
    freightRations:[],
    priceRations:[],
    priceRationSpread:null,
    priceRationSheet:null,
    rationSetting:{
        header:[
            {headerName: "编号", headerWidth: 80, dataCode: "code", dataType: "String",formatter: "@"},
            {headerName: "名称", headerWidth: 160, dataCode: "name", dataType: "String"},
            {headerName: "单位", headerWidth: 100, dataCode: "unit", dataType: "String"},
            {headerName: "数量", headerWidth: 100, dataCode: "quantity", dataType: "String",hAlign: "right",validator:"number"},
            {headerName: "高原取费类别", headerWidth: 100, dataCode: "feeType", dataType: "String",visible: false,cellType:"comboBox",options:[],maxDropDownItems:5}
        ],
        view: {
            lockColumns: ["unit"],
            rowHeaderWidth:25,
            colHeaderHeight:36
        }

    },
    initMaterialSpread:function () {
        this.materialSpread = SheetDataHelper.createNewSpread($("#materialCalcSheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.materialSpread);
        this.materialSheet = this.materialSpread.getSheet(0);
        sheetCommonObj.initSheet(this.materialSheet, this.materialSetting, 30);
        this.materialSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onMaterialValueChange);
        this.materialSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onMaterialSelectionChange);
        this.materialSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onMaterialEditStarting);
        this.materialSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onMaterialRangeChange);
        this.materialSheet.name('material_calc');
        if(projectReadOnly){
            disableSpread(this.materialSpread);
        }else {
            this.initRightClick("materialCalcSheet",this.materialSpread)
        }
    },
    initFreightSpread:async function(){
        this.freightSpread = SheetDataHelper.createNewSpread($("#freightSheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.freightSpread);
        this.freightSheet = this.freightSpread.getSheet(0);
        sheetCommonObj.initSheet(this.freightSheet, this.freightSetting, 30);
        this.freightSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onFreightValueChange);
        this.freightSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onFreightSelectionChange);
        this.freightSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onFreightEditStarting);
        this.freightSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onFreightPriceRangeChange);
        this.freightSheet.name('freight_calc');
        if(projectReadOnly){
            disableSpread(this.freightSpread);
        }else {
            this.initRightClick("freightSheet",this.freightSpread)
        }
        this.userFreightList = await projectObj.project.projectGLJ.getUserFreights();
    },
    initFreightRationSpread:function () {
        this.freightRationSpread = SheetDataHelper.createNewSpread($("#freight_ration_sheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.freightRationSpread);
        this.freightRationSheet = this.freightRationSpread.getSheet(0);
        sheetCommonObj.initSheet(this.freightRationSheet, this.rationSetting, 30);
        this.freightRationSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onFreightRationValueChange);
        this.freightRationSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onRationSelectionChange);
        this.freightRationSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onFreightRationEditStarting);
        this.freightRationSheet.name('freight_ration');
        if(projectReadOnly){
            disableSpread(this.freightRationSpread);
        }else {
            this.initRightClick("freight_ration_sheet",this.freightRationSpread);
        }
    },
    initPriceRationSpread:function () {
        this.priceRationSpread = SheetDataHelper.createNewSpread($("#price_ration_sheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.priceRationSpread);
        this.priceRationSheet = this.priceRationSpread.getSheet(0);
        sheetCommonObj.initSheet(this.priceRationSheet, this.rationSetting, 30);
        this.priceRationSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onPriceRationValueChange);
        this.priceRationSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onRationSelectionChange);
        this.priceRationSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onPriceRationEditStarting);

        this.priceRationSheet.name('price_ration');
        if(projectReadOnly){
            disableSpread(this.priceRationSpread);
        }else {
            this.initRightClick("price_ration_sheet",this.priceRationSpread);
        }
    },
    initPriceSpread:async function(){
        this.priceSpread = SheetDataHelper.createNewSpread($("#priceSheet")[0]);
        sheetCommonObj.spreadDefaultStyle(this.priceSpread);
        this.priceSheet = this.priceSpread.getSheet(0);
        sheetCommonObj.initSheet(this.priceSheet, this.priceSetting, 30);
        this.priceSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onFreightPriceRangeChange);
        this.priceSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onPriceValueChange);
        this.priceSheet.bind(GC.Spread.Sheets.Events.SelectionChanged,this.onPriceSelectionChange);
        this.priceSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onPriceEditStarting);
        this.priceSheet.name('price_calc');
        if(projectReadOnly){
            disableSpread(this.priceSpread);
        }else {
            this.initRightClick("priceSheet",this.priceSpread)
        }
    },
    showFreightDatas:function () {
        if(!$('#freightSheet').is(':visible')) return;
        let sel = this.freightSheet.getSelections()[0];
        let oldData = sel.row<this.freightDatas.length?this.freightDatas[sel.row]:"";
        this.freightSheet.setRowCount(0);
        this.freightDatas = this.getFreightDatas();
        sheetCommonObj.showData(this.freightSheet, this.freightSetting,this.freightDatas);
        this.freightSheet.setRowCount(this.freightDatas.length+20);
        let convCol = _.findIndex(this.freightSetting.header,{'dataCode':'conveyance'});
        sheetCommonObj.setComboBox(-1,convCol,this.freightSheet,this.conveyanceOptions,false);
        let startCol = _.findIndex(this.freightSetting.header,{'dataCode':'start'});
        let startOptions = this.getUserFreightOptions();
        sheetCommonObj.setComboBox(-1,startCol,this.freightSheet,startOptions,false,true,5);
        sel.row =  oldData?_.findIndex(this.freightDatas,{'ID':oldData.ID}):sel.row ;
        this.freightSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
        this.refreshRationView();
    },
    getUserFreightOptions :function () {
        let options = [];
        for(let uf of this.userFreightList){
            options.push(uf.freight.start);
        }
        return options;
    },
    showFreightRationDatas:function (freight) {
        let sel = this.freightRationSheet.getSelections()[0];
        let oldData = sel.row<this.freightRations.length?this.freightRations[sel.row]:"";
        this.freightRationSheet.setRowCount(0);
        this.freightRations = freight.rations?freight.rations:[];
        sheetCommonObj.showData(this.freightRationSheet, this.rationSetting,this.freightRations);
        this.freightRationSheet.setRowCount(this.freightRations+20);
        sel.row =  oldData?_.findIndex(this.freightRations,{'ID':oldData.ID}):sel.row ;
        this.freightRationSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
        this.refreshAssView();
    },
    showPriceRationDatas:function () {
        let price = this.getSelectedPrice();
        let sel = this.priceRationSheet.getSelections()[0];
        let oldData = sel.row<this.priceRations.length?this.priceRations[sel.row]:"";
        this.priceRationSheet.setRowCount(0);
        this.priceRations = price&&price.rations?price.rations:[];
        sheetCommonObj.showData(this.priceRationSheet, this.rationSetting,this.priceRations);
        this.priceRationSheet.setRowCount(this.priceRations+20);
        sel.row =  oldData?_.findIndex(this.priceRations,{'ID':oldData.ID}):sel.row ;
        this.priceRationSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
        this.refreshAssView();
    },
    showMaterialCalcDatas:function(){
        let sel = this.materialSheet.getSelections()[0];
        let oldData = sel.row<this.materialDatas.length?this.materialDatas[sel.row]:"";
        this.materialSheet.setRowCount(0);
        this.materialDatas = this.getMaterialCalcDatas();
        sheetCommonObj.showData(this.materialSheet, this.materialSetting,this.materialDatas);
        this.materialSheet.setRowCount(this.materialDatas.length);
        let pglj = projectGljObject.getProjectGLJSelected()
        sel.row = pglj?_.findIndex(this.materialDatas,{'id':pglj.id}):-1;
        if(sel.row == -1) sel.row = oldData?_.findIndex(this.materialDatas,{'id':oldData.id}):-1;
      
        this.materialSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
        this.materialSheet.showRow(sel.row==-1?0:sel.row, GC.Spread.Sheets.VerticalPosition.center);
    },
    showPriceDatas:function () {
        if(!$('#priceSheet').is(':visible')) return;
        let sel = this.priceSheet.getSelections()[0];
        let oldData = sel.row<this.priceDatas.length?this.priceDatas[sel.row]:"";
        this.priceSheet.setRowCount(0);
        this.priceDatas = this.getPriceDatas();
        sheetCommonObj.showData(this.priceSheet, this.priceSetting,this.priceDatas);
        this.priceSheet.setRowCount(this.priceDatas.length+20);
        sel.row =  oldData?_.findIndex(this.priceDatas,{'ID':oldData.ID}):sel.row ;
        this.priceSheet.setSelection(sel.row==-1?0:sel.row,sel.col,sel.rowCount,sel.colCount);
        this.showPriceRationDatas();
    },
    showDatas:async function(){
        if(!$('#materialCalcSheet').is(':visible')) return;
        if(!this.materialSpread) this.initMaterialSpread();
        if(!this.freightSpread)await this.initFreightSpread();
        if(!this.priceSpread) this.initPriceSpread();
        if(!this.freightRationSpread) this.initFreightRationSpread();
        if(!this.priceRationSpread) this.initPriceRationSpread();
        let h =_.find(this.rationSetting.header,{"dataCode":"feeType"});
        if(h)  h.options = projectObj.project.calcProgram.compiledTemplateNames;
        this.showMaterialCalcDatas();
        this.showFreightDatas();
        this.showPriceDatas();
        // 先试试看注释有没有bug  projectGljObject.refreshSubViews();
    },
    getMaterialSelected:function () {
        let sel = this.materialSheet.getSelections()[0];
        if(sel.row != -1 && this.materialDatas.length>sel.row){
            return this.materialDatas[sel.row]
        }
        return null;
    },

    getPriceDatas:function () {
        let list =  projectObj.project.projectGLJ.datas.originalList;
        let material = this.getMaterialSelected();
        return material?_.filter(list,{"connect_key":gljUtil.getIndex(material)}):[];
    },
    getFreightDatas:function () {
        let list =  projectObj.project.projectGLJ.datas.freightList;
        let material = this.getMaterialSelected();
        return material?_.filter(list,{"connect_key":gljUtil.getIndex(material)}):[];
    },
    getMaterialCalcDatas:function () {
        let gljList = projectObj.project.projectGLJ.datas.gljList;
        let datas = [];
        for(let g of gljList){
            if(g.quantity !== 0 && g.quantity !== '0' && g.unit_price.calcMaterial == 1){
                let data = {
                    id:g.id,
                    code:g.code,
                    name:g.name,
                    type:g.type,
                    unit:g.unit,
                    specs:g.specs,
                    unit_price:{id:g.unit_price.id,type:g.type,unit_price_file_id:g.unit_price.unit_price_file_id},//type用来排序
                    supplyLocation:g.unit_price.supplyLocation,
                    originalPrice:g.unit_price.originalPrice?g.unit_price.originalPrice:0,
                    unitFreight:g.unit_price.unitFreight?g.unit_price.unitFreight:0,
                   // unitWeight:g.unit_price.unitWeight?g.unit_price.unitWeight:0,
                    totalLoadingTimes:g.unit_price.totalLoadingTimes?g.unit_price.totalLoadingTimes:0,
                    handlingLossRate_n:g.unit_price.handlingLossRate_n?g.unit_price.handlingLossRate_n:0,
                    offSiteTransportLossRate_n:g.unit_price.offSiteTransportLossRate_n?g.unit_price.offSiteTransportLossRate_n:0,
                    offSiteTransportLoss:g.unit_price.offSiteTransportLoss?g.unit_price.offSiteTransportLoss:0,
                    purchaseStorageRate_n:g.unit_price.purchaseStorageRate_n?g.unit_price.purchaseStorageRate_n:0,
                    purchaseStorage:g.unit_price.purchaseStorage?g.unit_price.purchaseStorage:0,
                    grossWeightCoe_n:g.unit_price.grossWeightCoe_n?g.unit_price.grossWeightCoe_n:0,
                    packageRecoverValue:g.unit_price.packageRecoverValue?g.unit_price.packageRecoverValue:0
                };
                gljOprObj.setGLJPrice(data,g);
                datas.push(data);
            }
        }
        return gljUtil.sortProjectGLJ(datas);
    },
    onMaterialSelectionChange:function(sender,args){
        let me = materialCalcObj;
        let newSel = args.newSelections[0];
        let oldSel = args.oldSelections?args.oldSelections[0]:{};
        if(newSel.row != oldSel.row){
            me.showPriceDatas();
            me.showFreightDatas();
            projectGljObject.setSelectionWhenMaterialChange(me.getMaterialSelected())
        }
    },
    onFreightSelectionChange:function (sender,args) {
        materialCalcObj.refreshRationView();
        args.sheet.repaint();
    },
    onRationSelectionChange:function(sender,args){
        materialCalcObj.refreshAssView(args);
        args.sheet.repaint();
    },
    onPriceSelectionChange:function (sender,args) {
        materialCalcObj.showPriceRationDatas();
    },
    onPriceEditStarting:function (sender,args) {
        let me = materialCalcObj;
        if(!me.getMaterialSelected()){
            args.cancel = true;
        }else {
            let price = me.priceDatas[args.row];
            let dataCode = me.priceSetting.header[args.col].dataCode;
            if(dataCode == "supplyPrice"){
                if(price.rations && price.rations.length > 0) args.cancel = true;
            }
        }
    },
    onFreightEditStarting:function(sender,args){
        let me = materialCalcObj;
        if(!me.getMaterialSelected()){
            args.cancel = true;
        }else {
            let freigth = me.freightDatas[args.row];
            let dataCode = me.freightSetting.header[args.col].dataCode;
            if(dataCode=="materialType"){
                if(!freigth){
                    args.cancel = true;
                }else if(freigth.conveyance !="汽车"){//只有在汽车的情况下，材料类型列才能编辑
                    args.cancel = true;
                }
            }
            if(freigth){
                if(dataCode == "kmDistance" || dataCode=="unitLoadingFee" || dataCode =="loadingTimes" || dataCode == "freightIncreaseRate"){
                    if(freigth.conveyance == "自办运输") args.cancel = true;
                }
                if(dataCode == "unitFreight"){
                    if(freigth.rations && freigth.rations.length > 0) args.cancel = true;
                    if(gljUtil.isDef(freigth.materialType) && freigth.materialType != "") args.cancel = true;//当材料类型有值时，说明是内蒙古计算，运费是通过运距算出来的，不能编辑
                }
            }
        }
    },
    onFreightRationEditStarting:function (sender,args) {
        materialCalcObj.onRationEditStarting(sender,args,"freight");
    },
    onPriceRationEditStarting:function (sender,args) {
       materialCalcObj.onRationEditStarting(sender,args,"price");
    },
    onRationEditStarting:function(sender,args,type){
        let me = materialCalcObj;
        let dataCode = me.rationSetting.header[args.col].dataCode;
        let datas = type == "freight"?me.freightRations:me.priceRations;
        if(type ==  'price' && !gljUtil.isDef(me.getSelectedPrice()))   args.cancel = true;//没有选中原价，不可编辑
        if(args.row > datas.length){
            args.cancel = true;
        }else if(args.row == datas.length && dataCode != "code"){
            args.cancel = true;
        }
    },
    onMaterialEditStarting:function (sender,args) {
        let me = materialCalcObj;
        let dataCode = me.materialSetting.header[args.col].dataCode;
        if(dataCode == "supplyLocation" ||dataCode == "originalPrice"){//原价计算表有数据时只读，
            args.cancel = me.getPriceDatas().length > 0;
        }
        if(dataCode == "unitFreight"){//当运费计算表有数据时，则只读
            args.cancel = me.getFreightDatas().length > 0;
        }
    },

    onMaterialValueChange:function (sender,args) {
        let me = materialCalcObj;
        let dataMap = {};
        dataMap[args.row]={};
        dataMap[args.row][args.col] = args.newValue;
        me.updateMaterialCalcs(dataMap);
    },
    updateMaterialCalcs:function(dataMap){
        let me = materialCalcObj;
        let updateDatas = [];
        for(let row in dataMap) {
          let t = dataMap[row];
          let doc = {};
          let recode = me.materialDatas[row];
          for (let col in t) {
            let value = t[col];
            let dataCode = me.materialSetting.header[col].dataCode;
            if (value&&!sheetCommonObj.checkData(col,me.materialSetting,value)) {
                alert('输入的数据类型不对，请重新输入!');
                return me.showDatas();
            }
            if(dataCode != 'supplyLocation'){
               let decimal = getDecimal("glj.unitPrice");
               if(dataCode == "grossWeightCoe_n")  decimal = 6;
                value = value?scMathUtil.roundForObj(value,decimal)+'':'0'//4舍五入加默认为0
            }
            if(recode[dataCode] == value) continue;
            doc[dataCode] = value;
          }
          if (!_.isEmpty(doc)) updateDatas.push({id:recode.id,doc:doc});
        }
        if(updateDatas.length > 0) projectObj.project.projectGLJ.updateMaterialCalc(updateDatas);
    },
    getDefualtCalcType:function () {
      return "全国";
    },

    getNewFreightData:function (material) {
         let newData = {
             ID: uuid.v1(),
             start:"",//起讫地点
             conveyance:"汽车",//运输工具
             unitFreight:'0',//单位运价
             kmDistance:'0',//km运距
             unitLoadingFee:'0',//装卸费单价
             loadingTimes:'0',//装卸次数
             otherFee:'0',//其它费用
             freightIncreaseRate:'0',//运价增加率
             weightCoe:'1',//加权系数
             connect_key:gljUtil.getIndex(material),
             materialType:"",
             unit_price_file_id:material.unit_price.unit_price_file_id
         };
        return newData;
    },
    getFreightEXP:function(obj,doc,needUpdate){
      let item = _.clone(obj);
      if(doc) gljUtil.setProperty(item,doc);
      let material = materialCalcObj.getMaterialSelected();
      if(gljUtil.isDef(item.materialType)&&item.materialType != ""){
        let uString = materialCalcObj.getNeiMengUnitFreightString(item.kmDistance,item.materialType);
        return `((${uString}x(1+${item.freightIncreaseRate}%)+${item.unitLoadingFee}x${item.loadingTimes})/1.09+${item.otherFee})x${material.grossWeightCoe_n}x${item.weightCoe}`;
      }
      //(单位运价×(1+运距增加率%)+装卸费单价×装卸次数+其它费用)×单位毛重×加权系数
      if(item.conveyance == "自办运输"){
        let t = projectObj.project.projectGLJ.calcEachFreightOrPrice(item,"freight",{},needUpdate);
        return t.doc.exp;
      }

      //(单位运价×km运距×(1+运距增加率%)+装卸费单价×装卸次数+其它费用)×单位毛重×加权系数
      return `(${item.unitFreight}x${item.kmDistance}x(1+${item.freightIncreaseRate}%)+${item.unitLoadingFee}x${item.loadingTimes}+${item.otherFee})x${material.grossWeightCoe_n}x${item.weightCoe}`;
    },
    getSavedFreight:function (start,material) {
        let t = null;
        for(let f of this.userFreightList){
            if(f.freight.start == start){
                t = newDatas(f.freight,material);
                break;
            }
        }
        return t;
        function newDatas(freight,material) {
            let doc = {};
            for(let key in freight){
                doc[key] = freight[key];
                if(key == "ID") doc[key] = uuid.v1();
                if(key == "connect_key") doc[key] = gljUtil.getIndex(material);
                if(key == "unit_price_file_id") doc[key] = material.unit_price.unit_price_file_id;
            }
            delete doc._id;
            return doc;
        }
    },
    checkSavedFreight:function (start) {
        let t = null;
        for(let f of this.userFreightList){
            if(f.freight.start == start){
                t = f;
                break;
            }
        }
        return t;
    },
    onMaterialRangeChange:function(sender,args){
      let me = materialCalcObj;
      let dataMap={};
      for(let c of args.changedCells){
        let info = {row:c.row,col:c.col,cancel:false};
        me.onMaterialEditStarting(sender,info);
        if(info.cancel) return me.showDatas();
        let value=  args.sheet.getCell(c.row, c.col).text();
        if(dataMap[c.row]){
            dataMap[c.row][c.col]=value;
        }else{
            dataMap[c.row] ={};
            dataMap[c.row][c.col] = value;
        }
      }
      me.updateMaterialCalcs(dataMap);
    },
    onFreightPriceRangeChange:function (sender,args) {
        let me = materialCalcObj;
        let dataMap={};
        let sheetName = args.sheet.name();
        for(let c of args.changedCells){
            let info = {row:c.row,col:c.col,cancel:false};
            sheetName == 'price_calc'?me.onPriceEditStarting(sender,info): me.onFreightEditStarting(sender,info);
            if(info.cancel) return me.showDatas();
            let value=  args.sheet.getCell(c.row, c.col).text();
            if(dataMap[c.row]){
                dataMap[c.row][c.col]=value;
            }else{
                dataMap[c.row] ={};
                dataMap[c.row][c.col] = value;
            }
        }
        sheetName == 'price_calc'?me.addOrUpdatePriceCalc(dataMap):me.addOrUpdateFreightCalc(dataMap);
    },
    onFreightValueChange:function (sender,args) {
        let me = materialCalcObj;
        let dataMap = {};
        dataMap[args.row]={};
        dataMap[args.row][args.col] = args.newValue;
        me.addOrUpdateFreightCalc(dataMap);
    },
    addOrUpdateFreightCalc:function (dataMap) {//{2:{col:value}}
        let me = materialCalcObj;
        let material = me.getMaterialSelected();
        let addDatas=[],updateDatas=[];
        for(let row in dataMap) {
            let t = dataMap[row];
            let newData = {};
            let doc = {};
            let recode = me.freightDatas[row];
            for (let col in t) {
                let value = t[col];
                let dataCode = me.freightSetting.header[col].dataCode;
                if (value && !sheetCommonObj.checkData(col, me.freightSetting, value)) {
                    alert('输入的数据类型不对，请重新输入!');
                    return me.showDatas();
                }
                if (dataCode != 'start' && dataCode != 'conveyance' && dataCode != 'calcType' && dataCode != 'materialType') {
                    value = value ? scMathUtil.roundForObj(value, getDecimal("glj.unitPrice")) + '' : '0'//4舍五入加默认为0
                }
                if (parseInt(row) >= me.freightDatas.length) {//新增
                    let tempFreight = null;
                    if (dataCode == "start") {
                        tempFreight = me.getSavedFreight(value, material);
                    }
                    if (tempFreight) {
                        newData = tempFreight;
                    } else {
                        if(_.isEmpty(newData)) newData = me.getNewFreightData(material);
                        newData[dataCode] = value;
                        newData.exp = this.getFreightEXP(newData);
                    }
                } else {//修改
                    if (recode[dataCode] == value) continue;
                    doc[dataCode] = value;
                    if (dataCode == "conveyance") {//如果运输方式从自办运输切换成其它的东西时，要把底下挂的定额和定额工料机都清空
                      if (recode[dataCode] == "自办运输") {//没改之前的值
                          doc["rations"] = [];
                          doc["ration_gljs"] = [];
                      }
                      if (value == "自办运输") {//当运输工具下拉选择“自办运输”时，“Km运距”、“装卸费单价”、“装卸次数”、“运价增加率（％）”列数据归0，且灰选不可编辑
                          doc["kmDistance"] = '0';
                          doc["unitLoadingFee"] = '0';
                          doc["loadingTimes"] = '0';
                          doc["freightIncreaseRate"] = '0';
                      }
                      if (recode[dataCode] == "汽车") doc["materialType"] = "";//当运输方式从汽车切换成其它方式时，清空材料类型
                    }

                    if (dataCode == "materialType" && value != "") doc["unitFreight"] = me.calcNeiMengUnitFreight(recode.kmDistance, value);
                    if (dataCode == "kmDistance" && gljUtil.isDef(recode.materialType) && recode.materialType != "") doc["unitFreight"] = me.calcNeiMengUnitFreight(value, recode.materialType);
                    if (dataCode == "start") {
                        let t_f = me.getSavedFreight(value, material);
                        if (t_f) doc = t_f;
                    }
                    doc.exp = this.getFreightEXP(recode,doc,true);                            
                }
            }
            if (!_.isEmpty(newData)) addDatas.push(newData);
            if (!_.isEmpty(doc)) updateDatas.push({ID:recode.ID,doc:doc});
        }
        if(addDatas.length > 0 && updateDatas.length > 0) {
            alert("不能同时增加和更新操作");
            return me.showDatas();
        }
        if(addDatas.length > 0)  projectObj.project.projectGLJ.addFreightCalc(addDatas,material.id);
        if(updateDatas.length > 0)  projectObj.project.projectGLJ.updateFreightCalc(updateDatas,material.id);


    },
    calcNeiMengUnitFreight:function (tkmDistance,tmaterialType) {
        if(!tkmDistance||tkmDistance == '0') return "0";
        let decimal = getDecimal("glj.unitPrice");
        tkmDistance =  scMathUtil.roundForObj(tkmDistance,decimal);
        return scMathUtil.roundForObj(this.calNeiMengTotalFreight(tkmDistance,tmaterialType)/tkmDistance,decimal);
    },
    calNeiMengTotalFreight:function (kmDistance,materialType) {
        if(!kmDistance||kmDistance == '0') return 0;
        let decimal = getDecimal("glj.unitPrice");
        let baseMap = {"地方材料":6,"外购材料":13,"沥青、燃料等":19};//"地方材料","外购材料","沥青、燃料等"
        let baseFreight = baseMap[materialType];
        kmDistance =  scMathUtil.roundForObj(kmDistance,decimal);
        //用截取的方式，一段段取值
        let less = kmDistance - 5;//kmDistance <= 5 这段
        if(less <= 0) return baseFreight ;  //kmDistance <= 5 的时候直接取baseFreight

        //5< kmDistance <= 15  每增运1km 则增加0.6
        less = less - 10;
        if(less <=0)  return scMathUtil.roundForObj(baseFreight + scMathUtil.roundForObj((less + 10) * 0.6,6),decimal);//baseFreight + (less + 10) * 0.6;
        baseFreight = baseFreight + 10 * 0.6; //累加5到15这一段的运费;

        //15< kmDistance <= 100  每增运1km 则增加0.45
        less = less - 85;
        if(less <=0) return scMathUtil.roundForObj(baseFreight + scMathUtil.roundForObj((less + 85)*0.45,6),decimal);//baseFreight + (less + 85)*0.45;
        baseFreight = scMathUtil.roundForObj(baseFreight + scMathUtil.roundForObj(85*0.45,6),6) ;  //累加15到100这一段的运费;
        return scMathUtil.roundForObj(baseFreight + scMathUtil.roundForObj(less * 0.35,6),decimal); // >100 的所有部分每增运1km 则增加0.35  baseFreight + less * 0.35
    },

    getNeiMengUnitFreightString:function (kmDistance,materialType) {
        if(!kmDistance||kmDistance == '0') return "0";
        let decimal = getDecimal("glj.unitPrice");
        let baseMap = {"地方材料":6,"外购材料":13,"沥青、燃料等":19};//"地方材料","外购材料","沥青、燃料等"
        let baseFreight = baseMap[materialType];
        kmDistance =  scMathUtil.roundForObj(kmDistance,decimal);
        let resultString = baseFreight+"";
        //用截取的方式，一段段取值
        let less = kmDistance - 5;//kmDistance <= 5 这段
        if(less <= 0) return resultString ; //kmDistance <= 5 的时候直接取baseFreight

        //5< kmDistance <= 15  每增运1km 则增加0.6
        less = less - 10;
        if(less <=0)  return `(${resultString}+0.6x${less + 10})`;//baseFreight + (less + 10) * 0.6;
        resultString =  `${resultString}+0.6x10`;
        //15< kmDistance <= 100  每增运1km 则增加0.45
        less = less - 85;
        if(less <=0) return `(${resultString}+0.45x${less + 85})`; //baseFreight + (less + 85)*0.45;
        resultString = `${resultString}+0.45x85`;
        return `(${resultString}+0.35x${less})`;// >100 的所有部分每增运1km 则增加0.35  baseFreight + less * 0.35
    },

    onFreightRationValueChange:function (sender,args) {
        materialCalcObj.onRationValueChange(sender,args,"freight");
    },
    onPriceRationValueChange:function (sender,args) {
        materialCalcObj.onRationValueChange(sender,args,"price");
    },
    onRationValueChange:function (sender,args,type) {
        let me = materialCalcObj;
        let dataCode = me.rationSetting.header[args.col].dataCode;
        let value = args.newValue;
        let parent = type == "freight"? me.getSelectedFreight():me.getSelectedPrice();
        let dataList = type == "freight"?me.freightRations:me.priceRations;
        if(dataCode == "code" && args.row >= dataList.length) {//新增
            if(parent) projectObj.project.projectGLJ.addMaterialRation(value,type,parent.ID,parent.connect_key);
        }else { //修改
            let ration = dataList[args.row];
            if (value&&!sheetCommonObj.checkData(args.col,me.rationSetting,value)) {
                alert('输入的数据类型不对，请重新输入!');
                return   type == "freight"?me.showFreightRationDatas(parent):me.showPriceRationDatas();
            }
            if(dataCode == 'quantity'){
                if(value){
                    value = scMathUtil.roundForObj(parseFloat(value) / FilterNumberFromUnit(ration.unit),getDecimal("ration.quantity"))+"";
                }else {
                    value = "0";
                }
            }
            let datas = {parentID:parent.ID,rationID:ration.ID,type:type,actionType:"update",field:dataCode,value:value};
            if(dataCode == "code"){ //这时是替换，替换比较麻烦
                datas.code = value;
                datas.row = args.row;
                let libIDs = rationLibObj.getStdRationLibIDs();
                let defaultLibID = rationLibObj.getDefaultStdRationLibID();
                let selectedLib =  sessionStorage.getItem("stdRationLib");
                selectedLib&&selectedLib!='undefined'?libIDs.unshift(selectedLib):libIDs.unshift(defaultLibID);
                datas.userID = userID;
                datas.defaultLibID = defaultLibID;
                datas.rationRepIds = libIDs;
                datas.quantityDecimal = getDecimal("ration.quantity");
                datas.connect_key =  parent.connect_key;
                datas.projectID = projectObj.project.ID();
                datas.rations = parent.rations;
                datas.ration_gljs = parent.ration_gljs;
            }
            projectObj.project.projectGLJ.updateMaterialRation(datas);
        }

    },
    addOrUpdatePriceCalc:function (dataMap) {
        let me = materialCalcObj;
        let material = me.getMaterialSelected();
        let addDatas=[],updateDatas=[];
        for(let row in dataMap) {
            let t = dataMap[row];
            let doc = {};
            let recode = me.priceDatas[row];
            let newData = {};
            for (let col in t) {
                let value = t[col];
                let dataCode =  me.priceSetting.header[col].dataCode;;
                if (value && !sheetCommonObj.checkData(col, me.priceSetting, value)) {
                    alert('输入的数据类型不对，请重新输入!');
                    return me.showDatas();
                }
                if(dataCode == 'coe'||dataCode == 'supplyPrice'){
                    let decimal = dataCode == 'supplyPrice'?getDecimal("glj.unitPriceHasMix"):getDecimal("glj.unitPrice");
                    value = value?scMathUtil.roundForObj(value,decimal)+'':'0'//4舍五入加默认为0
                }
                if(parseInt(row) >= me.priceDatas.length){//新增
                    if(_.isEmpty(newData)) newData = me.getNewPriceData(material);
                    newData[dataCode] = value;
                }else {//修改
                    if(recode[dataCode] == value) continue;
                    doc[dataCode] = value;
                }
            }
            if (!_.isEmpty(newData)) addDatas.push(newData);
            if (!_.isEmpty(doc)) updateDatas.push({ID:recode.ID,doc:doc});
        }
        if(addDatas.length > 0 && updateDatas.length > 0) {
            alert("不能同时增加和更新操作");
            return me.showDatas();
        }
        if(addDatas.length > 0)  projectObj.project.projectGLJ.addPriceCalc(addDatas,material.id);
        if(updateDatas.length > 0)  projectObj.project.projectGLJ.updatePriceCalc(updateDatas,material.id);
    },
    getNewPriceData:function (material) {
        let newData = {
            ID:uuid.v1(),
            supplyLocation:"",
            supplyPrice:'0',
            coe:'1',
            connect_key:gljUtil.getIndex(material),
            unit_price_file_id:material.unit_price.unit_price_file_id
        };
        return newData;
    },
    onPriceValueChange:function(sender,args){
        let me = materialCalcObj;
        let dataMap = {};
        dataMap[args.row]={};
        dataMap[args.row][args.col] = args.newValue;
        me.addOrUpdatePriceCalc(dataMap);
    },
    deleteMaterialCal:function (row) {
        let record = this.materialDatas[row];//修改材料计算标记的同时还要删除原价计算，运费计算等
        if(record){
            projectObj.project.projectGLJ.updateCalcMaterial(record,'calcMaterial',0);
        }
    },
    deletePriceCalc:function (row) {
        let record = this.priceDatas[row];
        if(record){
            let material = this.getMaterialSelected();
            projectObj.project.projectGLJ.deletePriceCalc(record.ID,material.id);
        }
    },
    deleteFreightCalc:function (row) {
        let record = this.freightDatas[row];
        if(record){
            let material = this.getMaterialSelected();
            projectObj.project.projectGLJ.deleteFreightCalc(record.ID,material.id);
        }
    },
    deleteRation:function (row,type) {
        let me = this;
        let parent = type == "freight"?me.getSelectedFreight():me.getSelectedPrice();
        let ration =  type == "freight"?me.freightRations[row]:me.priceRations[row];
        let datas = {parentID:parent.ID,rationID:ration.ID,type:type,actionType:"delete"};
        projectObj.project.projectGLJ.updateMaterialRation(datas);

    },
    saveFreight:function (row) {
        let me = this;
        let record = this.freightDatas[row];
        if(record){
            let exist = this.checkSavedFreight(record.start);
            if(exist){//已存在的情况，更新
                let info =`起讫地点“${record.start}”已存在，是否覆盖？`;
                //to do 检查是否已经存在，存在给出是否覆盖提示
                hintBox.infoBox('操作确认', info, 2, function () {
                    me.updateUserFreight(record,exist)
                }, function () {
                    //
                },['确定','取消'],false);
                return true;
            }
            let user_freight = {rootProjectID:projectObj.project.projectInfo.property.rootProjectID};
            let f = {};
            for(let key in record){
                if(key == "_id") continue;
                f[key] = record[key];
                if(key =="ration" || key == "ration_gljs")f[key] = [];//下面的定额和工料机不用保存
            }
            user_freight.freight = f;
            projectObj.project.projectGLJ.updateUserFreight({freights:[user_freight],action:"add"});
        }
    },

    updateUserFreight:function (record,userFreight) {
        let t  = {};
        for(let t_key in userFreight){
            if(t_key == "ID") continue;
            t[t_key] = userFreight[t_key];
        }

        t.rootProjectID = projectObj.project.projectInfo.property.rootProjectID;
        let f = {};
        for(let key in record){
            if(key == "_id") continue;
            f[key] = record[key];
            if(key =="ration" || key == "ration_gljs")f[key] = [];//下面的定额和工料机不用保存
        }
        t.freight = f;
        projectObj.project.projectGLJ.updateUserFreight({ID:userFreight.ID,doc:t,action:"update"});

    },


    getSideResize: function () {
        let rg_sideResizeEles = {};
        rg_sideResizeEles.eleObj = {
            module: this.moduleName,
            resize: $('#mrResize'),
            parent: $('#projectGljBottom'),
            left: $('#materialCalcSheet'),
            right: $('#calcDiv')
        };
        rg_sideResizeEles.limit = {
            min: 100,
            max: `$('#projectGljBottom').width()-100`
        };
        return rg_sideResizeEles;
    },
    initRightClick:function (id,spread) {
        let me = this;
        $.contextMenu({
            selector: '#'+id,
            build: function ($trigger, e) {
                me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, spread);
                return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
                    me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "insertFreight":{
                    name: "内蒙古计算",
                    icon: 'fa-sign-in',
                    visible:function () {
                        return false;//2019-11-17 改成不需要右键插入功能    id == "freightSheet";
                    },
                    disabled: function (){
                       let material = me.getMaterialSelected();
                       return !material;
                    },
                    callback:function () {
                        $("#insertNeimengDiv").modal("show");
                    }

                },
                "saveFreight":{
                    name: "保存运输起讫地点",
                    icon: 'fa-sign-in',
                    visible:function () {
                        return id == "freightSheet";
                    },
                    disabled: function (){
                        if(id == "freightSheet") return me.rightClickTarget.row >= me.freightDatas.length;
                        return me.rightClickTarget.row === undefined;
                    },
                    callback:function () {
                        let row = me.rightClickTarget.row;
                        me.saveFreight(row);
                    }

                },
                "delete": {
                    name: "删除",
                    icon: 'fa-trash-o',
                    disabled: function () {
                        if(id == "priceSheet") return me.rightClickTarget.row >= me.priceDatas.length;
                        if(id == "freightSheet") return me.rightClickTarget.row >= me.freightDatas.length;
                        if(id == "freight_ration_sheet") return me.rightClickTarget.row >= me.freightRations.length;
                        if(id == "price_ration_sheet") return me.rightClickTarget.row >= me.priceRations.length;
                        return me.rightClickTarget.row === undefined;
                    },
                    callback: function (key, opt) {
                        let row = me.rightClickTarget.row;
                        if (id == "materialCalcSheet") me.deleteMaterialCal(row);
                        if (id == "priceSheet") me.deletePriceCalc(row);
                        if (id == "freightSheet") me.deleteFreightCalc(row);
                        if (id == "freight_ration_sheet") me.deleteRation(row,"freight");
                        if (id == "price_ration_sheet") me.deleteRation(row,"price");
                    }
                }
            }
        });
    },
    initTabWidth:function () {
        if($("#mix_ratio_sheet").is(':visible')) return ;//如果是组成物计算界面，返回
        let mr_sideResizeEles = this.getSideResize();
        SlideResize.loadHorizonWidth(mr_sideResizeEles.eleObj.module,
            [mr_sideResizeEles.eleObj.resize], [mr_sideResizeEles.eleObj.left, mr_sideResizeEles.eleObj.right],null,2);
        $("#spreadTabDiv").width( $('#calcDiv').width() - mr_sideResizeEles.eleObj.resize.width() - 32)
    },
    refreshRationView:function () {
        let freight = this.getSelectedFreight();
        let hide = true;
        let stats = $("#freight_ration").is(':visible');
        if(freight && freight.conveyance == "自办运输"){
            this.showFreightRationDatas(freight);
            $("#freightSheet").css("height","50%");
            $("#freight_ration").show();
            hide = false;
        }
        if(hide){
            $("#freightSheet").css("height","100%");
            $("#freight_ration").hide();
        }
        if(stats != $("#freight_ration").is(':visible')){//状态改变了才刷新
            this.freightSpread.refresh();
            this.freightRationSpread.refresh();
        }
    },
    refreshAssView:function () {
        let me = materialCalcObj;
        let sheet = $('#freightSheet').is(':visible')?me.freightRationSheet:me.priceRationSheet;
        let preString = $('#freightSheet').is(':visible')?"freight":"price";
        let show = false;
        let ass = null;
        let ration = me.getSelectedRation();
        let stats = $(`#${preString}_ration_ass`).is(':visible');
        if(ration && ration.rationAssList){
            for(let r of ration.rationAssList){
                if(r.name.indexOf("运距")!= -1){//辅助定额只处理运距的情况，其它的都忽略  模糊匹配
                    show = true;
                    ass = r;
                }
            }
        }
        if(show){
            $(`#${preString}_ration_sheet`).addClass("material-ration-left");
            $(`#${preString}_ration_ass`).addClass("material-ass");
            $(`#${preString}_ass_value`).val(ass.actualValue);
            $(`#${preString}_ass_label`).text(ass.name);
            $(`#${preString}_ration_ass`).show();
        }else {
            $(`#${preString}_ration_sheet`).removeClass("material-ration-left");
            $(`#${preString}_ration_ass`).removeClass("material-ass");
            $(`#${preString}_ration_ass`).hide();
        }
       if(stats !=  $(`#${preString}_ration_ass`).is(':visible')) sheet.parent.refresh();//状态改变了才刷新
    },
    updateMaterialRationAss:function (value,ele) {//to do 同步修改定额工料机的消耗量
        let parent = this.getSelectedRationParent(),ration = this.getSelectedRation();
        let replaceList = [];
        if(value && !number_util.isNum(value)){
            alert("输入的数据类型不对，请重新输入!");
            let a = _.find(ration.rationAssList,function (item) {
                return item.name.indexOf("运距") != -1;
            });
            if(a)ele.val(a.actualValue);
            return;
        }
        for(let ass of ration.rationAssList){
            if(ass.name.indexOf("运距")!= -1){
                ass.actualValue = value?scMathUtil.roundForObj(value,2):ass.stdValue;
            }
            replaceList.push(value);
        }
        let name = ration.caption;
        for(let re of replaceList){
            name = name.replace('%s',re);
        }
        let type =  $('#freightSheet').is(':visible')?"freight":"price";
        //let ration_glj =
        let datas = {parentID:parent.ID,rationID:ration.ID,type:type,actionType:"update",field:"name",value:name,ext:{rationAssList:ration.rationAssList}};

        let ration_gljs = projectObj.project.projectGLJ.calcMaterialAssQuantity(parent,ration,ration.rationAssList);
        if(ration_gljs.length > 0) datas.ration_gljs = ration_gljs;

        projectObj.project.projectGLJ.updateMaterialRation(datas);
    },
    getSelectedRation:function () {
        if($('#freightSheet').is(':visible')){
            return this.getSelectedRecode(this.freightRationSheet,this.freightRations);
        }else {
            return this.getSelectedRecode(this.priceRationSheet,this.priceRations);
        }
    },
    getSelectedRationParent:function () {
        if($('#freightSheet').is(':visible')){
            return this.getSelectedFreight();
        }else {
            return this.getSelectedRecode(this.priceSheet,this.priceDatas);
        }
    },
    getSelectedFreight:function(){
        return this.getSelectedRecode(this.freightSheet,this.freightDatas);
    },
    getSelectedPrice:function () {
       return this.getSelectedRecode(this.priceSheet,this.priceDatas)
    },
    getSelectedRecode:function (sheet,datas) {
        return sheetCommonObj.getSelectedRecode(sheet,datas);
    }

};
$(function () {
    $("#calc-nav").on('shown.bs.tab', function () {
        materialCalcObj.initTabWidth();
        projectGljObject.refreshSubViews();
    });
    $("#calTab ul li a").on('shown.bs.tab', function () {
        materialCalcObj.showFreightDatas();
        materialCalcObj.showPriceDatas();
        projectGljObject.refreshSubViews();
    });
    $(".ration_ass_value").change(function () {
        let me = materialCalcObj;
        me.updateMaterialRationAss($(this).val(),$(this));
    });
    $('#calcCoeDiv').on('show.bs.modal', function () {
        if(materialCalcObj.getAssistProductionLabel) $("#assistProductionLabel").text(materialCalcObj.getAssistProductionLabel);
        $("#assistProductionFeeRate").val(scMathUtil.roundForObj(projectObj.project.projectGLJ.datas.constData.assistProductionFeeRate,getDecimal("feeRate")));
    })
    $("#calcCoeConfirm").click(function () {
        let feeRate =  $("#assistProductionFeeRate").val();
        if(!number_util.isNum(feeRate)){
            alert("输入的数据类型不对，请重新输入!");
           return $("#assistProductionFeeRate").val(scMathUtil.roundForObj(projectObj.project.projectGLJ.datas.constData.assistProductionFeeRate,getDecimal("feeRate")));
        }
        feeRate = scMathUtil.roundForObj(feeRate,getDecimal("feeRate"));
        $("#calcCoeDiv").modal("hide");
        projectObj.project.projectGLJ.changeAssistProductionFeeRate(feeRate);
    });

    $("#insertFreightconfirm").click(function () {
        let me = materialCalcObj;
        let material = me.getMaterialSelected();
        let newData = me.getNewFreightData(material);
        let start = $("#freight_start").val();
        let kmDistance = $("#freight_kmDistance").val();
        let materialType = $("#freight_materialType").val();
        if(!number_util.isNum(kmDistance)){
            alert("运输距离数据类型不对，请重新输入!");
            return ;
        }
        kmDistance = scMathUtil.roundForObj(kmDistance,getDecimal("glj.unitPrice"))+'';
        newData.start = start;
        newData.kmDistance = kmDistance;
        newData.materialType = materialType;
        newData.calcType = "内蒙古";
        newData.unitFreight = me.calcNeiMengUnitFreight(kmDistance,materialType);
        $("#insertNeimengDiv").modal("hide");
        projectObj.project.projectGLJ.addFreightCalc([newData],material.id);
    })

});

let mr_sideResizeEles = materialCalcObj.getSideResize();
SlideResize.horizontalSlide(mr_sideResizeEles.eleObj, mr_sideResizeEles.limit, function(){
    $("#spreadTabDiv").width( $('#calcDiv').width() - mr_sideResizeEles.eleObj.resize.width() - 32);
    projectGljObject.refreshSubViews();
},2);
