/**
 * Created by zhang on 2018/3/13.
 */
let projectGljObject = {
  showTag: 'ration', //mixRatio/machine
  showMixRatioMark: '',
  commonInfoPriceID:'',
  displayType: filterType.ALL,
  mixRatioType: [gljType.CONCRETE, gljType.MORTAR, gljType.MIX_RATIO, gljType.MAIN_MATERIAL],
  machineType: [gljType.GENERAL_MACHINE],
  projectGljSetting: {},
  projectGljSpread: null,
  projectGljSheet: null,
  materialTreeSheet: null,
  projectGljSheetData: [],
  infoPriceData:[],
  infoClassData:[],
  mixRatioSetting: {},
  infoPriceSetting: {
    header: [
      { headerName: "材料名称", headerWidth: 320, dataCode: "name",  dataType: "String"},
      { headerName: "规格型号", headerWidth: 200, dataCode: "specs",hAlign: "left",dataType: "String" },
      { headerName: "单位",headerWidth: 50,dataCode: "unit", dataType: "String", hAlign: "center"},
      { headerName: "含税市场价", headerWidth: 100, dataCode: "taxPrice", hAlign: "right",dataType: "Number",  validator: "number" },
      { headerName: "不含税市场价", headerWidth: 100,   dataCode: "noTaxPrice",   hAlign: "right",   dataType: "Number",    validator: "number"   } //,decimalField:"glj.unitPrice"
    ],
    view: {
      lockColumns: [0, 1, 2, 3, 4] //,
      //colHeaderHeight:30
    }
  },
  infoClassSetting:{
    header: [{ headerName: "分类", headerWidth: 420, dataCode: "name",  dataType: "String"}],
    view: {
      lockColumns: [0] 
    }
  },
  relatedRationSetting: {
    header: [{
        headerName: "编码",
        headerWidth: 100,
        dataCode: "code",
        dataType: "String"
      },
      {
        headerName: "名称",
        headerWidth: 180,
        dataCode: "name",
        dataType: "String"
      },
      {
        headerName: "单位",
        headerWidth: 50,
        dataCode: "unit",
        dataType: "String",
        hAlign: "center"
      },
      {
        headerName: "工程量",
        headerWidth: 65,
        dataCode: "quantity",
        dataType: "Number",
        hAlign: "right",
        decimalField: "ration.quantity"
      },
      {
        headerName: "单价",
        headerWidth: 65,
        dataCode: "feesIndex.common.unitFee",
        dataType: "Number",
        hAlign: "right",
        decimalField: "ration.unitPrice"
      }
    ],
    view: {
      lockColumns: [0, 1, 2, 3, 4] //,
      //colHeaderHeight:30
    }
  },
  materialTreeSetting: {
    "emptyRows": 0,
    "headRows": 1,
    "headRowHeight": [21],
    "defaultRowHeight": 21,
    "treeCol": 0,
    "cols": []
  },
  materialSetting: {
    header: [{
        headerName: "编码",
        headerWidth: 200,
        dataCode: "code",
        dataType: "String"
      },
      {
        headerName: "名称",
        headerWidth: 160,
        dataCode: "name",
        dataType: "String"
      },
      {
        headerName: "规格型号",
        headerWidth: 160,
        dataCode: "specs",
        hAlign: "left",
        dataType: "String"
      },
      {
        headerName: "单位",
        headerWidth: 45,
        dataCode: "unit",
        hAlign: "center",
        dataType: "String"
      },
      {
        headerName: "定额价",
        headerWidth: 70,
        dataCode: "basePrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      }, //,decimalField:'glj.unitPrice'
      {
        headerName: "市场价",
        headerWidth: 70,
        dataCode: "marketPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      }, //,decimalField:"glj.unitPrice"
      {
        headerName: "总消耗量",
        headerWidth: 70,
        dataCode: "quantity",
        hAlign: "right",
        dataType: "Number",
        decimalField: 'glj.quantity'
      },
      {
        headerName: "三材系数",
        headerWidth: 70,
        dataCode: "materialCoe",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      }, //,decimalField:'material'
      {
        headerName: "三材量",
        headerWidth: 100,
        dataCode: "materialQuantity",
        hAlign: "right",
        dataType: "Number",
        decimalField: 'glj.quantity'
      },
      {
        headerName: "三材类别",
        headerWidth: 70,
        dataCode: "materialType",
        hAlign: "center",
        dataType: "String",
        cellType: 'comboBox',
        editorValueType: true,
        options: materialComboMap
      }
    ],
    view: {
      lockColumns: [0, 1, 2, 3, 6, 8]
    }
  },
  mixRatioSpread: null,
  mixRatioSheet: null,
  mixRatioData: [],
  subList: [], //定额工料机，添加组成物时临时保存组成物信息的位置
  usedTenderList: [],
  usedUnitPriceInfo: null,
  displayTypeMap: [{
      ID: 'LABOUR',
      text: '人工'
    },
    {
      ID: 'GENERAL_MATERIAL',
      text: '材料'
    },
    {
      ID: 'GENERAL_MACHINE',
      text: '机械'
    },
    {
      ID: 'MAIN_MATERIAL',
      text: '主材'
    },
    {
      ID: 'EQUIPMENT',
      text: '设备'
    }
  ],
  initInfoPriceSpread: function () {
    if (this.infoPriceSpread) return this.infoPriceSpread.refresh();
    this.infoPriceSpread = SheetDataHelper.createNewSpread($("#info_price_sheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.infoPriceSpread);
    this.infoPriceSheet = this.infoPriceSpread.getSheet(0);
    this.initSheet(this.infoPriceSheet, this.infoPriceSetting);
    this.infoPriceSheet.bind(GC.Spread.Sheets.Events.TopRowChanged, _.debounce(this.onInfoTopRowChanged, 100)); 
    this.infoPriceSheet.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onInfoPriceDoubleClick);
    this.infoPriceSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.infoPriceSelectionChange);
    this.infoPriceSheet.name('infoPriceSheet');
    this.infoPriceSheet.setRowCount(0);
    this.getInfoPriceOptions();

    if (projectReadOnly) {
      sheetCommonObj.disableSpread(this.infoPriceSpread);
    } else {
      this.initInfoPriceRightClick();
    }
  },
  initInfoClassSpread: function () {
    if (this.infoClassSpread) return this.infoClassSpread.refresh();
    this.infoClassSpread = SheetDataHelper.createNewSpread($("#info_class_sheet")[0]);
    sheetCommonObj.spreadDefaultStyle(this.infoPriceSpread);
    this.infoClassSheet = this.infoClassSpread.getSheet(0);
    this.initSheet(this.infoClassSheet, this.infoClassSetting);
    this.infoClassSheet.name('infoClassSheet');
    this.infoClassSheet.setRowCount(0);
    //this.infoClassSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.infoClassSelectionChange);
    this.infoClassSheet.bind(GC.Spread.Sheets.Events.CellClick,this.infoClassClick);
    if (projectReadOnly) {
      sheetCommonObj.disableSpread(this.infoClassSpread);
    } 
  },
  initSpreads: function () {
    if (this.projectGljSpread == null) this.initProjectGljSpread();
    //if(materialAdjustObj.spread == null) materialAdjustObj.initSpread();
    if (configMaterialObj.configSpread == null) configMaterialObj.initSpread();
  },
  initProjectGljSpread: function () {
    if (!this.projectGljSpread) {
      this.projectGljSpread = SheetDataHelper.createNewSpread($("#project_glj_sheet")[0], 2);
      sheetCommonObj.spreadDefaultStyle(this.projectGljSpread);
    }
    this.projectGljSpread.bind(GC.Spread.Sheets.Events.RangeChanged, this.onProjectGljRangeChange);
    this.initProjectGljSheet();
    this.initMaterialTreeSheet();
    disableRightMenu("project_glj_sheet", this.projectGljSpread, this.rightClickCallback);
    //打开别人分享的项目，只读
    if (projectReadOnly) {
      //锁定逻辑走disabledSpread里的
      if (this.projectGljSetting.view.lockColumns) {
        this.projectGljSetting.view.lockColumns = null;
      }
      sheetCommonObj.disableSpread(this.projectGljSpread);
    }
  },
  initProjectGljSheet: function () {
    this.projectGljSheet = this.projectGljSpread.getSheet(0);
    this.initSheet(this.projectGljSheet, this.projectGljSetting);
    this.projectGljSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onProjectGljSelectionChange);
    this.projectGljSheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onProjectGljEditStarting);
    this.projectGljSheet.name('projectGljSheet');
    //this.projectGljSheet.setRowHeight(0, 36, 1);
    this.projectGljSheet.options.frozenlineColor = '#ababab';
    this.projectGljSheet.frozenColumnCount(this.projectGljSetting.frozenCols);
  },
  initMixRatio: function () {
    let me = projectGljObject;
    if (me.mixRatioSpread == null) {
      me.initMixRatioSpread();
      if (!projectReadOnly) {
        me.initRightClick();
      }
    }
  },
  initMixRatioSpread: function () {
    this.mixRatioSpread = SheetDataHelper.createNewSpread($("#mix_ratio_sheet")[0], 2);
    sheetCommonObj.spreadDefaultStyle(this.mixRatioSpread);
    this.mixRatioSheet = this.mixRatioSpread.getSheet(0);
    this.initSheet(this.mixRatioSheet, this.mixRatioSetting);
    this.mixRatioSheet.name('mixRatioSheet');
    this.mixRatioSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onMixRatioRangeChange);
    this.initRelatedRationSheet();

    if (projectReadOnly) {
      if (this.mixRatioSetting.view.lockColumns) {
        this.mixRatioSetting.view.lockColumns = null;
      }
      sheetCommonObj.disableSpread(this.mixRatioSpread);
    }
  },
  initRelatedRationSheet: function () {
    this.relatedRationSheet = this.mixRatioSpread.getSheet(1);
    sheetCommonObj.initSheet(this.relatedRationSheet, this.relatedRationSetting, 30);
    this.relatedRationSheet.name('relatedRation');
    this.relatedRationSheet.bind(GC.Spread.Sheets.Events.CellDoubleClick, this.onRelatedRationDoubleClick);
    //this.mixRatioSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onMixRatioRangeChange);
  },
  initMaterialTreeSheet: function () {
    this.materialTreeSheet = this.projectGljSpread.getSheet(1);
    this.materialTreeSetting = this.createMaterialTreeSheetSetting();
    this.materialTree = cacheTree.createNew(this);
    this.materialTreeController = TREE_SHEET_CONTROLLER.createNew(this.materialTree, this.materialTreeSheet, this.materialTreeSetting);
    this.materialTreeController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, this.onSelectionChange);
    this.materialTreeSheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onProjectGljEditStarting);
    this.materialTreeSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onProjectGLJValueChange);
    this.materialTreeSheet.name('materialTreeSheet');
    if (projectReadOnly && this.materialSetting.view.lockColumns) {
      if (this.materialSetting.view.lockColumns) {
        this.materialSetting.view.lockColumns = null;
      }
    }
  },
  createMaterialTreeSheetSetting: function () {
    return sheetCommonObj.transferToTreeSetting(this.materialSetting, this.materialTreeSetting);
  },
  unitPriceFileInit: function () {
    let me = this;
    let projectGLJ = projectObj.project.projectGLJ;
    let data = projectGLJ.datas;
    me.usedTenderList = data.usedTenderList !== undefined ? data.usedTenderList : [];
    me.usedUnitPriceInfo = data.constData.usedUnitPriceInfo !== undefined ?
      data.constData.usedUnitPriceInfo : {};
    $("#current-name").text(me.usedUnitPriceInfo.name);
    let usedCount = me.usedTenderList.length <= 0 ? 1 : me.usedTenderList.length;
    $("#used-project-count").text(usedCount);
    $("#editUnitFile").attr("href", `/unitPrice/index/${me.usedUnitPriceInfo.id}`)
  },
  getUsedTenderInfo: function () {
    return "人材机单价的变化，将自动影响以下单位工程造价：<br>" + projectGljObject.usedTenderList.join("<br>");
  },
  // 获取选中人材机，添加组成物时，分页查询语句的扩展
  getQueryExtForMixRatio: function () {
    const extend = {};
    if (!this.selectedProjectGLJ) {
      return extend;
    }
    if (this.selectedProjectGLJ.type === gljType.MAIN_MATERIAL) { //对于主材，只显示没有组成物并且除了自已的主材
      extend['component.0'] = {
        $exists: false
      };
      extend.gljType = gljType.MAIN_MATERIAL;
    } else if (_.includes(gljUtil.hasCompMaterial, this.selectedProjectGLJ.type)) { //混凝土、砂浆、配合比
      extend.gljType = gljType.GENERAL_MATERIAL;
    } else if (_.includes(gljUtil.hasCompMachine, this.selectedProjectGLJ.type)) { //me.selectedProjectGLJ.type == gljType.GENERAL_MACHINE//机械中有组成物的类型
      extend.gljType = {
        $in: gljUtil.machineComposition
      };
    }
    return extend;
  },
  filterLibGLJForMixRatio: function () {
    let me = this;
    if (me.selectedProjectGLJ) {
      let showTypes = [];
      if (me.selectedProjectGLJ.type == gljType.MAIN_MATERIAL) { //对于主材，只显示没有组成物并且除了自已的主材
        showTypes = [gljType.MAIN_MATERIAL];
      } else if (_.includes(gljUtil.hasCompMaterial, me.selectedProjectGLJ.type)) { //混凝土、砂浆、配合比
        showTypes = [gljType.GENERAL_MATERIAL];
      } else if (_.includes(gljUtil.hasCompMachine, me.selectedProjectGLJ.type)) { //me.selectedProjectGLJ.type == gljType.GENERAL_MACHINE//机械中有组成物的类型
        showTypes = gljUtil.machineComposition;
      }
      gljOprObj.gljLibSheetData = _.filter(gljOprObj.gljLibSheetData, function (item) {
        if (me.selectedProjectGLJ.type == gljType.MAIN_MATERIAL) {
          let p_index = gljOprObj.getIndex(me.selectedProjectGLJ, gljKeyArray);
          let i_index = gljOprObj.getIndex(item, gljLibKeyArray);
          return item.gljType == gljType.MAIN_MATERIAL && item.component.length == 0 && p_index != i_index
        } else {
          return _.includes(showTypes, item.gljType);
        }
      });
    }
  },
  addMixRatio: async function () {
    let me = this,
      projectGLJ = projectObj.project.projectGLJ;
    let tdatas = me.mixRatioData;
    if (me.subList.length > 0) tdatas = me.subList;
    for (let mix of tdatas) {
      let m_key = gljOprObj.getIndex(mix, gljKeyArray);
      let t_index = gljOprObj.GLJSelection.indexOf(m_key);
      t_index != -1 ? gljOprObj.GLJSelection.splice(t_index, 1) : '';
    }
    await me.addMixRatioFromLib(gljOprObj.GLJSelection, () => {
      me.showMixRatioData(); //这里添加的组成物的消耗量默认都是0，所以对父工料机的价格不会有影响，不用触发计算
      projectGLJ.loadData(function () {
        me.showProjectGljData();
        gljOprObj.showRationGLJSheetData();
        me.onUnitFileChange(me.selectedProjectGLJ);
      });
    });
  },
  addMixRatioFromLib: async function (selections, callback) {
    let gljList = [],
      allGLJ = gljOprObj.AllRecode;
    let url = "/glj/add-ratio";
    let result = null;
    if (selections.length == 0) {
      return;
    }
    try {
      for (let glj of allGLJ) {
        let i_key = gljUtil.getIndex(glj, gljLibKeyArray);
        if (_.includes(selections, i_key)) {
          let pglj = {
            glj_id: glj.ID,
            name: glj.name,
            code: glj.code,
            original_code: glj.code,
            unit: glj.unit,
            specs: glj.specs,
            base_price: glj.basePrice,
            market_price: glj.basePrice,
            shortName: glj.shortName,
            type: glj.gljType,
            model: glj.model,
            adjCoe: glj.adjCoe,
            from: 'std',
            repositoryId: glj.repositoryId,
            materialType: glj.materialType,
            materialCoe: glj.materialCoe,
            grossWeightCoe: glj.grossWeightCoe,
            purchaseStorageRate: glj.purchaseStorageRate,
            offSiteTransportLossRate: glj.offSiteTransportLossRate,
            handlingLossRate: glj.handlingLossRate
          };
          if (typeof projectObj !== 'undefined') pglj.project_id = projectObj.project.ID();
          if (glj.hasOwnProperty("compilationId")) {
            pglj.from = "cpt";
            if (glj.code.indexOf('-') != -1) { //这条工料机是用户通过修改名称、规格、型号等保存到补充工料机库的
              pglj.original_code = glj.code.split('-')[0]; //取-前的编号作为原始编号
            }
          }
          gljList.push(pglj);
        }
      }
      gljList = _.sortByAll(gljList, ['type', 'code']);
      if (gljList.length == 0) return;
      let parentInfo = {};
      if (typeof unitPriceObj !== 'undefined') {
        url = "/unitPrice/addMixRatio";
        pdata = unitPriceObj.getSelectedUnitPrice();
        parentInfo = {
          unit_price_file_id: pdata.unit_price_file_id,
          connect_key: gljUtil.getIndex(pdata)
        };
      } else {
        parentInfo = {
          unit_price_file_id: projectObj.project.property.unitPriceFile.id,
          connect_key: gljOprObj.getIndex(projectGljObject.selectedProjectGLJ, gljKeyArray)
        };
      }

      $.bootstrapLoading.start();
      result = await ajaxPost(url, {
        gljList: gljList,
        parentInfo: parentInfo
      })
      if (callback) callback(result);
    } catch (error) {
      alert(error);
      console.log(error);
    }
    $.bootstrapLoading.end();
    return result;
  },
  showMixRatioData: function () {
    let me = this,
      gljId = null,
      gljType = null;
    if (!$('#mixRatio-nav').hasClass('active')) return;
    if (!me.projectGljSpread) return;
    if (!me.mixRatioSpread) return;
    me.mixRatioSpread.setActiveSheetIndex(0);
    let sheet = me.projectGljSpread.getActiveSheet();
    let oldSel = me.mixRatioSheet.getSelections()[0];
    if (sheet.name() == 'projectGljSheet') { //projectGljSheet/materialSheet 工料机汇总和三材汇总表
      let sel = me.projectGljSheet.getSelections()[0];
      let srow = sel.row == -1 || sel.row == "" ? 0 : sel.row;
      if (me.projectGljSheetData.length > srow) {
        gljId = me.projectGljSheetData[srow].id;
        gljType = me.projectGljSheetData[srow].type;
      }
    } else if (sheet.name() == 'materialTreeSheet') {
      if (this.materialTree.selected) {
        gljId = this.materialTree.selected.data.id;
        gljType = this.materialTree.selected.data.type;
      }
    }
    if (compositionTypes.indexOf(gljType) == -1) { //如果不是有组成物的类型，工料机id设置为空，组成物表设置为空
      gljId = null
    }
    projectObj.project.projectGLJ.getRatioData(gljId, function (data) {
      if (gljId !== projectObj.project.projectGLJ.getRatioId) { //两个id不一致说明不是最新的请求，不用往下执行。
        return;
      }
      let ratioList = [];
      for (let glj of data) {
        ratioList.push(me.getMixRatioSheetData(glj));
      }
      ratioList = gljUtil.sortRationGLJ(ratioList);
      me.mixRatioData = ratioList;
      me.mixRatioSheet.setRowCount(0);
      sheetCommonObj.showData(me.mixRatioSheet, me.mixRatioSetting, me.mixRatioData);
      me.mixRatioSheet.setRowCount(me.mixRatioData.length);
      me.mixRatioSheet.setSelection(oldSel.row == -1 ? 0 : oldSel.row, oldSel.col, oldSel.rowCount, oldSel.colCount);
    })
  },
  showRelatedRationDatas: function () {
    let me = this;
    if (!$('#ration-nav').hasClass('active')) return;
    if(!me.mixRatioSpread) return;
    me.mixRatioSpread.setActiveSheetIndex(1);
    let projectGLJData = me.getProjectGLJSelected();
    let rationIDMap = {};
    let rations = [];
    if (projectGLJData) {
      for (let rg of projectObj.project.ration_glj.datas) {
        if (rg.projectGLJID == projectGLJData.id) rationIDMap[rg.rationID] = true;
      }
      for (let r of projectObj.project.Ration.datas) {
        if (rationIDMap[r.ID] || (r.type == rationType.gljRation && r.projectGLJID == projectGLJData.id)) {
          rations.push(r);
        }
      }
    }
    this.relatedRationSheetData = rations;
    sheetCommonObj.showData(me.relatedRationSheet, me.relatedRationSetting, rations);
    me.relatedRationSheet.setRowCount(rations.length);
  },
  setInfoClassSelection:function(){
    let me = this;
    let priceRow = me.infoPriceSheet.getSelections()[0].row;
    let infoPrice = me.infoPriceData[priceRow];
    if(infoPrice && me.infoClassData.length > 0){
      const index = _.findIndex(me.infoClassData,{'ID':infoPrice.classID});
      me.infoClassSheet.setSelection(index,0,1,1);
      //me.infoClassSheet.clearSelection(); 清除焦点行
      me.infoClassSheet.showRow(index, GC.Spread.Sheets.VerticalPosition.center);
    }


  },
  showInforPriceData: function (datas) {
    let me = this;
    me.infoPriceData = datas;
    sheetCommonObj.showData(me.infoPriceSheet, me.infoPriceSetting, datas);
    me.infoPriceSheet.setRowCount(datas.length);
    if(datas.length > 0) me.setInfoClassSelection();
  },
  showInforClassData: function (datas) {
    let me = this;
    me.infoClassData = datas;
    for(let d of datas){
      d.collapsed = false;
    }
    sheetCommonObj.showTreeData(me.infoClassSheet, me.infoClassSetting, datas);
  },
  autoShowInfoPriceData: function () { 
    if (!$('#info-nav').hasClass('active')) return;
    let projectGLJData = this.getProjectGLJSelected();
    if(projectGLJData){
      $('#info_search_name').val(projectGLJData.name);
      let code = projectGLJData.code.substr(0, 4);
      $('#info_glj_name').val(projectGLJData.name);
      $('#info_glj_code').val(code);
      this.searchInfoPrice(null);
    }
  },
  getMixRatioSheetData: function (glj) {
    let data = {
      id: glj.id,
      mix_ratio_id: glj.ratio_data.id,
      code: glj.code,
      name: glj.name,
      specs: glj.specs,
      unit: glj.unit,
      type: glj.type,
      short_name: projectObj.project.projectGLJ.getShortNameByID(glj.type),
      consumption: glj.ratio_data.consumption,
      unit_price: glj.unit_price,
      connect_key: glj.ratio_data.connect_key
    };
    gljOprObj.setGLJPrice(data, glj);
    return data;
  },
  onProjectGljEditStarting: function (sender, args) {
    let me = projectGljObject;
    let row = args.row;
    let col = args.col;
    if (me.projectGljEditChecking(row, col) == false) {
      args.cancel = true;
    }
  },
  projectGljEditChecking: function (row, col, isPaste = false) { //return false表示不能编辑
    let me = projectGljObject;
    let data = null,
      setting = null;
    let sheet = me.projectGljSpread.getActiveSheet();
    if (sheet.name() == 'projectGljSheet') {
      if (row >= me.projectGljSheetData.length) return false;
      data = me.projectGljSheetData[row];
      setting = me.projectGljSetting;
    } else if (sheet.name() == 'materialTreeSheet') {
      data = me.materialTree.selected.data;
      setting = me.materialSetting;
      let notEditId = ['GC', 'GJ', 'MC', 'SN', 'SZ'];
      if (notEditId.indexOf(data.id) != -1) {
        return false;
      }
    }
    let dataCode = setting.header[col].dataCode;
    let lockColumns = setting.view.lockColumns;
    if (lockColumns.indexOf(col) != -1) return false;

    if (isPaste == false && (dataCode == 'is_adjust_price' || dataCode == 'is_evaluate' || dataCode == 'is_main_material' || dataCode == 'is_eval_material' || dataCode == 'no_tax_eqp')) { //除了粘贴，拖动填充等操作，其它的都不能编辑
      return false;
    }
    if (dataCode == 'basePrice' || dataCode == 'marketPrice' || dataCode == 'supply') { //有组成物时，市场单价、定额价、供货方式不能修改
      if (data.ratio_data && data.ratio_data.length > 0) return false;
      if (dataCode == 'basePrice' && data.is_add != 1) return false; //如果不是新增，定额价不可修改。
    }
    if (dataCode == 'supply_quantity' && data.supply != 1) return false; // 如果为部分甲供则甲供数量需要可编辑,其它的都不能编辑

    if (dataCode == 'materialCoe') { //三材类别为空时，三材系数应只读，不允许输入。
      if (data.materialType == undefined || data.materialType == null || data.materialType == '') return false;
    }
    if (dataCode == 'taxRate') {
      //普通材料、商品混凝土、商品砂浆、机械组成物、主材、设备才能编辑
      if (!_.includes([gljType.GENERAL_MATERIAL, gljType.COMMERCIAL_CONCRETE, gljType.COMMERCIAL_MORTAR, gljType.MACHINE_COMPOSITION, gljType.MAIN_MATERIAL, gljType.EQUIPMENT], data.type)) {
        return false
      }
    }

    return true;
  },
  onSelectionChange: function () {
    let me = projectGljObject;
    me.showMixRatioData();
    me.materialTreeSheet.repaint();
  },
  onRelatedRationDoubleClick: function (sender, args) {
    let me = projectGljObject;
    let record = me.relatedRationSheetData[args.row];
    $("#tab_zaojiashu").click();
    locateObject.locateNode(record.ID);
  },
  onInfoPriceDoubleClick: function(sender, args) {
    projectGljObject.preApplyInfoPrice(args.row);
  },
  infoPriceSelectionChange:function(sender, args){
    projectGljObject.setInfoClassSelection();
  },
  infoClassClick:function(sender,args){
    let me = projectGljObject;
    let row = args.row;
    let infoClass = me.infoClassData[row];
    if(infoClass){
      if( $("#info_class").val() == infoClass.ID) return; // 不用重复查询
      $("#info_class").val(infoClass.ID);
      $("#info_glj_name").val("")//清除工料机名字搜索项
      me.searchInfoPrice();
    }
  },
 /*  infoClassSelectionChange:function(sender, args){
    let me = projectGljObject;
    let row = args.newSelections[0].row;
    let infoClass = me.infoClassData[row];
    if(infoClass){
      $("#info_class").val(infoClass.ID);
      $("#info_glj_name").val("")//清除工料机名字搜索项
      me.searchInfoPrice();
    }
  }, */
  onProjectGljSelectionChange: function (sender, args) {
    let me = projectGljObject;
    let newSel = args.newSelections[0];
    let oldSel = args.oldSelections ? args.oldSelections[0] : {};
    me.projectGljSheet.suspendPaint();
    me.projectGljSheet.suspendEvent();
    if (newSel.row != oldSel.row) {
      let style = gljOprObj.getSelStyle(true, {});
      me.projectGljSheet.setStyle(newSel.row, -1, style);
      let orow = oldSel.row == '' || oldSel.row == -1 ? 0 : oldSel.row;
      if (me.projectGljSheetData[orow]) {
        style = gljOprObj.getSelStyle(false, {}, me.projectGljSheetData[orow].bgColour);
      } else {
        style.backColor = "White";
      }
      console.log(style);
      me.projectGljSheet.setStyle(orow, -1, style);
      me.projectGljRowChang();
    } else {
      me.projectGljSheet.repaint();
    }
    me.projectGljSheet.resumeEvent();
    me.projectGljSheet.resumePaint();
  },
  projectGljRowChang: function (row) {
    let me = projectGljObject;
    let sel = me.mixRatioSheet.getSelections()[0];
    sel.row = -1;
    sel.col = 0;
    sel.rowCount = 1;
    sel.colCount = 1;
    me.showMixRatioData();
    me.showRelatedRationDatas();
    $("#info_class").val("");
    me.autoShowInfoPriceData();
  },
  rightClickCallback: function (row) {
    let me = projectGljObject;
    let sheet = me.projectGljSpread.getActiveSheet();
    if (sheet.name() == 'projectGljSheet') {
      me.projectGljRowChang(row);
    } else if (sheet.name() == 'materialTreeSheet') {
      me.materialTreeController.setTreeSelected(me.materialTreeController.tree.items[row]);
    }
  },
  onProjectGljRangeChange: function (sender, info) {
    let me = projectGljObject;
    let changeInfo = [];
    let canChange = true;
    if (info.action == GC.Spread.Sheets.RangeChangedAction.clear) {
      if (me.projectGljEditChecking(info.row, info.col) == false) {
        canChange = false;
      } else {
        info.newValue = null;
        me.onProjectGLJValueChange(sender, info);
        return;
      }
    }
    for (let c of info.changedCells) {
      let value = info.sheet.getCell(c.row, c.col).text();
      changeInfo.push({
        row: c.row,
        col: c.col,
        value: value
      });
      if (me.projectGljEditChecking(c.row, c.col, true) == false) { //如果不能编辑
        canChange = false;
        break;
      }
      if (!me.checkData(c.col, me.projectGljSetting, value)) {
        alert('输入的数据类型不对，请重新输入!');
        canChange = false;
        break;
      }
    }
    if (canChange == false) { //恢复原来的值
      info.sheetName == "materialTreeSheet" ? me.showMaterialTreeData() : me.showProjectGljData();
    } else if (info.sheetName == "projectGljSheet") {
      me.batchUpdateProjectGLJ(changeInfo, info.sheetName);
    }
  },
  onMixRatioRangeChange: function (sender, info) {
    let me = projectGljObject;
    let canChange = true;
    let changeInfo = [];
    /*  if (info.action == GC.Spread.Sheets.RangeChangedAction.clear) {
         info.newValue = 0;
         me.onMixRatioValueChange(sender,info);
         info.sheet.getCell(info.row, info.col).text(0);
         return ;
     } */
    for (let c of info.changedCells) {
      let value = info.sheet.getCell(c.row, c.col).text();
      if (_.isEmpty(value)) value = 0;
      if (!me.checkData(c.col, me.mixRatioSetting, value)) {
        alert('输入的数据类型不对，请重新输入!');
        canChange = false;
        break;
      } else {
        changeInfo.push({
          row: c.row,
          col: c.col,
          value: value
        });
      }
    }
    if (canChange == false) me.showMixRatioData(); //数据类型不对
    if (changeInfo.length > 0) me.batchUpdateConsumption(changeInfo);
  },
  batchUpdateProjectGLJ: function (changeInfo, sheetName) {
    let projectGLJ = projectObj.project.projectGLJ;
    let me = projectGljObject;
    let propertyCells = [],
      priceCells = [];
    let setting = sheetName == "materialTreeSheet" ? me.materialSetting : me.projectGljSetting;
    for (let c of changeInfo) {
      c.dataCode = setting.header[c.col].dataCode;
      if (c.dataCode == 'basePrice' || c.dataCode == 'marketPrice') {
        priceCells.push(c);
      } else {
        propertyCells.push(c);
      }
    }
    me.batchUpdateGLJProperty(propertyCells, sheetName, function () {
      //价格属于单价文件表，如果与项目工料机的其它属性一起的话计算起来会比较复杂，同时出现价格与其它属性一起更新的情况也会比较少;
      projectGLJ.batchUpdatePrice(priceCells, sheetName);
      //me.refreshBySheetName(sheetName); 2020-07-27  改在projectGLJ里统一刷新了
      //gljOprObj.refreshView();
    });
  },
  refreshBySheetName: function (sheetName) {
    let me = projectGljObject;
    if (sheetName == "projectGljSheet") {
      me.showProjectGljData();
    } else if (sheetName == "materialTreeSheet") {
      me.showMaterialTreeData();
    }
  },
  batchUpdateGLJProperty: function (changeInfo, sheetName, callback) {
    let me = projectGljObject,
      updateMap = {};
    let projectGLJ = projectObj.project.projectGLJ;
    for (let c of changeInfo) {
      if (c.dataCode == 'is_evaluate') continue; //暂估，暂时跳过
      let recode = sheetName == "materialTreeSheet" ? me.materialTree.items[c.row].data : me.projectGljSheetData[c.row];
      if (recode[c.dataCode] == c.value) {
        continue;
      }
      me.getUpdateData(recode.id, c.value, c.dataCode, recode.quantity, updateMap);
    }
    if (_.isEmpty(updateMap)) {
      callback ? callback() : '';
      return;
    }
    projectGLJ.batchUpdateGLJProperty(updateMap, callback);
  },
  getUpdateData: function (id, value, dataCode, quantity, updateMap) {
    let me = projectGljObject;
    let supplyMap = {
      "自行采购": 0,
      "部分甲供": 1,
      "完全甲供": 2,
      "甲定乙供": 3
    };
    let materialMap = {
      "钢材": 1,
      "钢筋": 2,
      "木材": 3,
      "水泥": 4,
      "商品砼": 5,
      "商品砂浆": 6
    };
    let data = updateMap[id] ? updateMap[id] : {};
    //供货方式 和三材类型 粘贴和填充过来的数据，要做对应转换，因为这里value只是中文文本，并不是实际的值
    // 如果是供货方式则需要处理数据
    if (dataCode === 'supply') {
      if (supplyMap[value] !== undefined || supplyMap[value] !== null) {
        value = supplyMap[value];
      }
      data.supply_quantity = me.getSupplyQuantity(value, quantity);
    }
    if (dataCode === 'supply_quantity') { //修改数量需做4舍5入
      value = scMathUtil.roundForObj(value, getDecimal('glj.quantity'));
    }
    if (dataCode === 'is_evaluate' || dataCode === 'is_adjust_price' || dataCode === 'is_main_material') {
      value = value ? 1 : 0;
    }
    if (dataCode === 'materialType') { //三材类型要做对应转换，因为这里value只是中文文本，并不是实际的值
      if (materialMap[value] !== undefined || materialMap[value] !== null) {
        value = materialMap[value];
      }
      if (value == null || value == "") { //删除三材类别时，清空三材系数
        value = null;
        data.materialCoe = null;
      }
    }
    if (dataCode == 'materialCoe') {
      value = scMathUtil.roundForObj(value, getDecimal("material"));
    }

    data[dataCode] = value;
    updateMap[id] = data;
  },
  batchUpdateConsumption: function (changeInfo) {
    let projectGLJ = projectObj.project.projectGLJ;
    let me = projectGljObject;
    let updateMap = {},
      updateData = [],
      parentBasePrice = 0,
      parentMarketPrice = 0;
    let parentKey = '',
      unit_price_file_id = null;
    for (let c of changeInfo) {
      let record = me.mixRatioData[c.row];
      let value = scMathUtil.roundForObj(c.value, getDecimal("glj.quantity"));
      updateMap[record.mix_ratio_id] = {
        consumption: value,
        record: record
      };
      updateData.push({
        type: 'mix_ratio',
        query: {
          id: record.mix_ratio_id
        },
        doc: {
          consumption: value
        }
      });
      parentKey = record.connect_key;
      unit_price_file_id = record.unit_price.unit_price_file_id;
    }
    for (let sub of me.mixRatioData) {
      let marketPrice = scMathUtil.roundForObj(sub.unit_price.market_price, getDecimal("process"));
      let basePrice = scMathUtil.roundForObj(sub.unit_price.base_price, getDecimal("process"));
      let consumption = updateMap[sub.mix_ratio_id] ? updateMap[sub.mix_ratio_id].consumption : scMathUtil.roundForObj(sub.consumption, getDecimal("glj.quantity"));
      parentMarketPrice = scMathUtil.roundForObj(marketPrice * consumption + parentMarketPrice, getDecimal("process"));
      parentBasePrice = scMathUtil.roundForObj(basePrice * consumption + parentBasePrice, getDecimal("process"));
    }
    parentBasePrice = scMathUtil.roundForObj(parentBasePrice, getDecimal("glj.unitPrice"));
    parentMarketPrice = scMathUtil.roundForObj(parentMarketPrice, getDecimal("glj.unitPrice"));
    updateData.push({
      type: 'parent',
      connect_key: parentKey,
      base_price: parentBasePrice,
      market_price: parentMarketPrice,
      unit_price_file_id: unit_price_file_id
    });
    projectGLJ.batchUpdateConsumption(updateData, updateMap, function () {
      //更新人材机汇总表
      let parentSheet = me.projectGljSpread.getActiveSheet(); //三材汇总表和工料机汇总表
      let prow = parentSheet.getActiveRowIndex(); //取父机械或组成物的下标
      let prowData = parentSheet.name() == 'projectGljSheet' ? me.projectGljSheetData[prow] : me.materialTree.items[prow].data;
      me.refreshParentData(prow, prowData.id);
      me.onUnitFileChange(updateData);
    });

  },
  showProjectGljData: function () {
    if (!this.projectGljSpread) return;
    let me = this;
    this.projectGljSpread.setActiveSheetIndex(0);
    let sel = this.projectGljSheet.getSelections()[0];
    let oldData = sel.row < this.projectGljSheetData.length ? this.projectGljSheetData[sel.row] : "";
    let projectGljSheetData = [];
    let gljList = projectObj.project.projectGLJ.datas.gljList;
    gljList = this.filterProjectGLJ(gljList);
    gljList = sortProjectGLJ(gljList);
    for (let glj of gljList) {
      projectGljSheetData.push(this.getSheetDataByGLJ(glj));
    }
    this.projectGljSheetData = projectGljSheetData;
    sheetCommonObj.showData(this.projectGljSheet, this.projectGljSetting, this.projectGljSheetData, null, function () {
      me.projectGljSheet.setRowCount(me.projectGljSheetData.length);
      sel.row = oldData ? _.findIndex(me.projectGljSheetData, {
        'id': oldData.id
      }) : -1;
      me.projectGljSheet.setSelection(sel.row == -1 ? 0 : sel.row, sel.col, sel.rowCount, sel.colCount);
    });

  },
  showMaterialTreeData: function () {
    this.projectGljSpread.setActiveSheetIndex(1);
    let sel = this.materialTreeSheet.getSelections()[0];
    let oldNodeID = this.materialTree.selected ? this.materialTree.selected.data.id : "";
    let gljList = projectObj.project.projectGLJ.datas.gljList;
    gljList = _.sortByAll(gljList, ['code']);
    this.createMaterialTree(gljList);
    this.materialTreeController.showTreeData();
    let newNode = this.materialTree.getNodeByID(oldNodeID);
    sel.row = newNode ? newNode.serialNo() : -1;
    this.materialTreeSheet.setSelection(sel.row == -1 ? 0 : sel.row, sel.col, sel.rowCount, sel.colCount);
    this.materialTreeController.setTreeSelected(this.materialTree.items[sel.row == -1 ? 0 : sel.row]);
  },
  initSheetViews: function () {
    let me = projectGljObject;
    if (me.displayType == filterType.AMAE || me.displayType == filterType.ZGCL || me.displayType == filterType.PBCL) {
      $('#adjustType').hide();
      if (me.displayType == filterType.AMAE) {
        let adjustType = projectObj.project.projectInfo.property.gljAdjustType || 'priceInfo';
        $('#adjustType').val(adjustType);
        $('#adjustType').show();
      }
      configMaterialObj.setNavLinkText(me.displayType);
      $('#material_adjust').hide();
      $('#project-glj-main').hide();
      $('#config_material').show();
    } else {
      $('#material_adjust').hide();
      $('#adjustType').hide();
      $('#config_material').hide();
      $('#project-glj-main').show();
      if (me.displayType == filterType.JGCL || me.displayType == filterType.SCHZ) {
        $("#projectGljResize").hide();
        $("#projectGljBottom").hide();
      } else {
        $("#projectGljResize").show();
        $("#projectGljBottom").show();
      }

    }
  },
  refreshViewsData: function () {
    let me = projectGljObject;
    if (me.displayType == filterType.AMAE) return materialAdjustObj.refreshSheetDatas();
    if (me.displayType == filterType.ZGCL || me.displayType == filterType.PBCL) return configMaterialObj.refreshSheetDatas();
    me.refreshDataSheet();
  },
  refreshDataSheet: function (refresh) { //refresh = true 的时候不用更新表头信息
    let me = projectGljObject;
    if (!refresh) {
      let quantityCol = _.findIndex(me.projectGljSetting.header, function (header) {
        return header.dataCode == 'quantity' || header.dataCode == 'techQuantity' || header.dataCode == 'subdivisionQuantity';
      });
      if (me.displayType == filterType.FBFX) { //分部分项人材机，将“总消耗量”替换显示为“分部分项总消耗量”。
        me.projectGljSetting.header[quantityCol].dataCode = 'subdivisionQuantity';
        me.projectGljSheet.setValue(0, quantityCol, "分部分项总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
      } else if (me.displayType == filterType.TECH) { //措施项目人材机，将“总消耗量”替换显示为“措施项目总消耗量”。
        me.projectGljSetting.header[quantityCol].dataCode = 'techQuantity';
        me.projectGljSheet.setValue(0, quantityCol, "措施项目总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
      } else {
        me.projectGljSetting.header[quantityCol].dataCode = 'quantity';
        me.projectGljSheet.setValue(0, quantityCol, "总消耗量", GC.Spread.Sheets.SheetArea.colHeader);
      }
    }
    if (me.displayType == filterType.SCHZ) { //三材汇总树节点
      me.showMaterialTreeData();
    } else {
      me.showProjectGljData();
      me.showMixRatioData();
      me.showRelatedRationDatas();
    }
  },
  createMaterialTree: function (gljList) {
    let me = projectGljObject;
    let q_decimal = getDecimal("glj.quantity");
    let GC = {
      id: 'GC',
      name: materialType[materialTypeMap.GC],
      code: 'GC',
      unit: 't',
      ParentID: -1,
      NextSiblingID: 'MC'
    };
    let GJ = {
      id: 'GJ',
      name: materialType[materialTypeMap.GJ],
      code: 'GJ',
      unit: 't',
      ParentID: 'GC',
      NextSiblingID: -1
    };
    let MC = {
      id: 'MC',
      name: materialType[materialTypeMap.MC],
      code: 'MC',
      unit: 'm3',
      ParentID: -1,
      NextSiblingID: 'SN'
    };
    let SN = {
      id: 'SN',
      name: materialType[materialTypeMap.SN],
      code: 'SN',
      unit: 't',
      ParentID: -1,
      NextSiblingID: 'ST'
    };
    let ST = {
      id: 'ST',
      name: materialType[materialTypeMap.ST],
      code: 'SPT',
      unit: 'm3',
      ParentID: -1,
      NextSiblingID: 'SS'
    };
    let SS = {
      id: 'SS',
      name: materialType[materialTypeMap.SS],
      code: 'SPJS',
      unit: 'm3',
      ParentID: -1,
      NextSiblingID: '-1'
    };
    let rootDatas = [GC, GJ, MC, SN, ST, SS];
    let parentMap = {};
    let sumMap = {};
    this.materialTree.nodes = {}, this.materialTree.selected = null, this.materialTree.roots = [], this.materialTree.items = [];
    for (let r of rootDatas) {
      let baseNode = null;
      if (r.id == 'GJ') {
        baseNode = createMaterialNode(r, parentMap['GC'], null); //钢筋的父节点为钢材
      } else {
        baseNode = createMaterialNode(r, null, null);
      }
      parentMap[r.id] = baseNode;
    }
    for (let g of gljList) {
      if (g.quantity !== 0 && g.quantity !== '0') {
        if (g.materialType) {
          let tem = me.getMaterialSheetDataByGLJ(g);
          if (tem.materialQuantity) {
            sumMap[g.materialType] = sumMap[g.materialType] ? sumMap[g.materialType] + tem.materialQuantity : tem.materialQuantity;
            tem.materialQuantity = scMathUtil.roundToString(tem.materialQuantity, q_decimal); //转成string
          }
          if (g.materialType == materialTypeMap.GC) { //钢材的下一节点是钢筋
            createMaterialNode(tem, parentMap['GC'], parentMap['GJ']);
          } else {
            createMaterialNode(tem, parentMap[materialTypeMap[g.materialType]]);
          }
        }
      }
    }
    for (let mkey in sumMap) {
      if (mkey == materialTypeMap.GC && sumMap[materialTypeMap.GJ]) { //钢材汇总要加上钢筋的总量
        parentMap['GC'].data.materialQuantity = scMathUtil.roundToString(sumMap[mkey] + sumMap[materialTypeMap.GJ], q_decimal);
      } else {
        parentMap[materialTypeMap[mkey]].data.materialQuantity = scMathUtil.roundToString(sumMap[mkey], q_decimal);
      }
    }
    this.materialTree.sortTreeItems();

    function createMaterialNode(data, parent, next) {
      let newNode = me.materialTree.addNode(parent, next, data.id);
      newNode.data = data;
      return newNode;
    }
  },
  getMaterialSheetDataByGLJ: function (glj) {
    let q_decimal = getDecimal("glj.quantity");
    let m_decimal = getDecimal("material");
    let p_decimal = getDecimal("glj.unitPrice");
    let projectGLJ = projectObj.project.projectGLJ;
    let data = {
      id: glj.id,
      code: glj.code,
      name: glj.name,
      specs: glj.specs,
      unit: glj.unit,
      type: glj.type,
      short_name: projectGLJ.getShortNameByID(glj.type),
      quantity: scMathUtil.roundToString(glj.quantity, q_decimal),
      supply: glj.supply,
      supply_quantity: glj.supply_quantity,
      materialType: glj.materialType,
      delivery: glj.delivery,
      delivery_address: glj.delivery_address,
      is_adjust_price: glj.is_adjust_price,
      ratio_data: glj.ratio_data,
      is_add: glj.unit_price.is_add,
      bgColour: 'white'
    };
    if (glj.materialCoe) {
      data.materialCoe = scMathUtil.roundForObj(glj.materialCoe, m_decimal);
      data.materialQuantity = scMathUtil.roundForObj(glj.materialCoe * glj.quantity, q_decimal); //还要做汇总，汇总完再转成string
    }
    gljOprObj.setGLJPrice(data, glj);
    data.basePrice = scMathUtil.roundToString(data.basePrice, p_decimal);
    data.marketPrice = scMathUtil.roundToString(data.marketPrice, p_decimal);
    return data;
  },
  filterProjectGLJ: function (gljList) {
    let me = projectGljObject;
    if (gljList.length > 0) {
      gljList = _.filter(gljList, function (item) {
        return me.displayTypeFilter(item);
      });
    }
    return gljList;
  },
  displayTypeFilter: function (item) {
    let me = this;
    if (item.quantity !== 0 && item.quantity !== '0') { //过滤掉消耗量为0的工料机
      if (me.displayType == filterType.ALL) { //所有工料机
        return true;
      } else if (filterTypeArray.indexOf(me.displayType) != -1) { //人工、材料、机械、主材、设备
        let typeString = item.type + "";
        return typeString.startsWith(me.displayType);
      } else if (me.displayType == filterType.FBFX) { //“分部分项总消耗量”≠0的工料机行
        return item.subdivisionQuantity !== 0 && item.subdivisionQuantity !== '0';
      } else if (me.displayType == filterType.TECH) { //筛选“措施项目总消耗量”≠0的工料机行
        return item.techQuantity !== 0 && item.techQuantity !== '0';
      } else if (me.displayType == filterType.JGCL) { //筛选“供货方式”=“完全甲供”或“部分甲供”的工料机行
        return item.supply == supplyType.WQJG || item.supply == supplyType.BFJG;
      } else if (me.displayType == filterType.ZGCL) { //筛选“是否暂估”=“是”的工料机行。
        return item.is_evaluate == 1;
      } else if (me.displayType == filterType.ZYCL) { //筛选“主要材料”=“是”的工料机行。
        return item.is_main_material == 1;
      }
    }
    return false;
  },
  getSheetDataByGLJ: function (glj) {
    let projectGLJ = projectObj.project.projectGLJ;
    let materialIdList = projectGLJ.datas.constData.materialIdList;
    let data = {
      id: glj.id,
      code: glj.code,
      name: glj.name,
      specs: glj.specs,
      unit: glj.unit,
      type: glj.type,
      short_name: projectGLJ.getShortNameByID(glj.type),
      quantity: glj.quantity,
      tenderQuantity: glj.tenderQuantity,
      supply: glj.supply,
      supply_quantity: glj.supply_quantity,
      materialType: glj.materialType,
      materialCoe: glj.materialCoe,
      delivery: glj.delivery,
      delivery_address: glj.delivery_address,
      is_adjust_price: glj.is_adjust_price,
      ratio_data: glj.ratio_data,
      is_add: glj.unit_price.is_add,
      bgColour: 'white',
      techQuantity: glj.techQuantity,
      subdivisionQuantity: glj.subdivisionQuantity,
      originPlace: glj.originPlace,
      vender: glj.vender,
      qualityGrace: glj.qualityGrace,
      brand: glj.brand,
      unitPriceID: glj.unit_price.id,
      priceFrom: glj.unit_price.priceFrom,
      remark: glj.remark
    };
    gljOprObj.setGLJPrice(data, glj);

    data.is_main_material = glj.is_main_material == 1 ? 1 : 0;
    //供货方式为完全甲供时设置甲供数量为总消耗量
    if (data.supply == 2) data.supply_quantity = glj.quantity;

    // 只有材料才显示是否暂估
    if (materialIdList.indexOf(glj.type) >= 0) data.is_evaluate = glj.is_evaluate;
    //是“材料”、“主材”、“设备”时显示评标材料
    if (materialIdList.indexOf(glj.type) >= 0 || glj.type == gljType.MAIN_MATERIAL || glj.type == gljType.EQUIPMENT) data.is_eval_material = glj.is_eval_material ? glj.is_eval_material : 0;
    //类型是“设备”时有效
    if (glj.type == gljType.EQUIPMENT) data.no_tax_eqp = glj.no_tax_eqp ? glj.no_tax_eqp : 0;

    if (glj.materialCoe !== null && glj.materialCoe !== undefined) {
      data.materialCoe = scMathUtil.roundForObj(glj.materialCoe, getDecimal("material"));
    }
    //bgColour
    if (data.basePrice == data.marketPrice) { //如果定额价等于市场价时，改底色。 优先度低于有组成物时的底色
      data.bgColour = "#C4CAFB";
    }
    if (gljUtil.notEditType.indexOf(glj.type) >= 0) {
      if (data.ratio_data && data.ratio_data.length > 0) { //有组成物时
        //设置底色
        data.bgColour = "#E0E0E0";
      }
    }
    return data;
  },
  refreshProjectGljRow: function (row) {
    let me = projectGljObject;
    let rowData = me.projectGljSheetData[row];
    let glj = projectObj.project.projectGLJ.getByID(rowData.id);
    let newRow = null;
    if (glj) {
      newRow = me.getSheetDataByGLJ(glj);
    }
    if (me.displayTypeFilter(newRow) == true) {
      me.projectGljSheetData[row] = newRow;
      sheetCommonObj.showRowData(this.projectGljSheet, this.projectGljSetting, row, this.projectGljSheetData);
    } else {
      me.projectGljSheetData.splice(row, 1);
      me.projectGljSheet.deleteRows(row, 1);
      me.showMixRatioData();
      me.showRelatedRationDatas();
    }
    //me.projectGljSheetData[row] = me.getSheetDataByGLJ(glj);
  },
  initSheet: function (sheet, setting) {
    var me = this;

    sheetCommonObj.initSheet(sheet, setting, 30);
    sheet.bind(GC.Spread.Sheets.Events.ValueChanged, me.onSheetValueChange);
  },
  onSheetValueChange: function (e, info) {
    let me = projectGljObject;
    if (info.sheetName == 'projectGljSheet') {
      me.onProjectGLJValueChange(e, info);
    } else if (info.sheetName == 'mixRatioSheet') {
      me.onMixRatioValueChange(e, info);
    }
  },
  onMixRatioValueChange: function (e, info) {
    let composition = projectObj.project.composition;
    let me = projectGljObject,
      row = info.row,
      col = info.col;
    let dataCode = me.mixRatioSetting.header[col].dataCode;
    let recode = me.mixRatioData[row];
    let value = info.newValue;
    let parentSheet = me.projectGljSpread.getActiveSheet(); //三材汇总表和工料机汇总表
    if (!me.checkData(col, me.mixRatioSetting, value)) {
      alert('输入的数据类型不对，请重新输入!');
      me.mixRatioSheet.setValue(row, col, info.oldValue);
      return false;
    }
    value = scMathUtil.roundToString(value, getDecimal("glj.quantity"));
    me.batchUpdateConsumption([{
      row: row,
      col: col,
      value
    }]);
  },
  refreshParentData: function (row, pid, sid) {
    let me = this;
    let sheet = me.projectGljSpread.getActiveSheet();
    let parantData = null;
    if (sheet.name() == 'projectGljSheet') {
      me.showProjectGljData(); // me.refreshProjectGljRow(row)  这里原来是分开刷新的，现在整个统一刷新，先留着
      //parantData = _.find();  //me.projectGljSheetData[row];
    } else {
      me.showMaterialTreeData();
      //parantData = me.materialTree.items[row].data;
    }
    let pglj = _.find(projectObj.project.projectGLJ.datas.gljList, {
      'id': pid
    });
    parantData = pglj ? me.getSheetDataByGLJ(pglj) : null;
    //projectObj.project.projectGLJ.datas.gljList

    // 更新组成物缓存
    projectObj.project.composition.loadData();
    me.updateParentNodes(pid, parantData.marketPrice, sid);
  },
  updateParentNodes: function (pid, marketPrice, sid) {
    //先查找使用了父项目工料机的定额工料机
    let updateNodes = [];
    let ration_gljs = _.filter(projectObj.project.ration_glj.datas, {
      'projectGLJID': pid
    });
    for (let rg of ration_gljs) {
      let node = projectObj.project.mainTree.getNodeByID(rg.rationID);
      if (node) {
        updateNodes.push(node);
      }
    }
    //或者是使用了父项目工料机的工料机类型的定额
    let rations = _.filter(projectObj.project.Ration.datas, {
      'type': 3,
      'projectGLJID': pid
    });
    for (let r of rations) {
      let r_node = projectObj.project.mainTree.getNodeByID(r.ID);
      if (r_node) {
        r_node.data.marketUnitFee = marketPrice; //parentMarketPrice;//这里用显示的价格
        updateNodes.push(r_node);
      }
    }
    if (sid) {
      let subRations = calcTools.getRationsByProjectGLJ(sid);
      updateNodes = updateNodes.concat(subRations);
    }
    if (updateNodes.length > 0) {
      projectObj.project.calcProgram.calcNodesAndSave(updateNodes, async function () {
        projectObj.mainController.refreshTreeNode(projectObj.project.mainTree.roots);
        installationFeeObj.calcInstallationFee(); //计算安装增加费
        await OVER_HEIGHT.reCalcOverHeightFee();
        await itemIncreaseFeeObj.calcItemIncreaseFeeByNodes(updateNodes);
      });
    }
    gljOprObj.refreshView();
  },

  onUnitFileChange: function (data) {
    projectObj.project.markUpdateProject({
      projectID: projectObj.project.ID(),
      'unitFileID': socketObject.getUnitFileRoomID()
    }, "unitFile", function () {
      //socket.emit('unitFileChangeNotify', JSON.stringify(data));
      socket.emit('unitFileChangeNotify', {
        projectID: projectObj.project.ID(),
        userID: userID,
        'unitFileID': socketObject.getUnitFileRoomID()
      });
    });
  },
  deleteMixRatio: function (row) {
    let me = this,
      deleteRecode = me.mixRatioData[row];
    let consumption = deleteRecode.consumption;
    let [parentMarketPrice, parentBasePrice] = me.getCompositionSumPrice('delete', row);
    let parentSheet = me.projectGljSpread.getActiveSheet(); //三材汇总表和工料机汇总表
    let prow = parentSheet.getActiveRowIndex(); //取父机械或组成物的下标
    let prowData = parentSheet.name() == 'projectGljSheet' ? me.projectGljSheetData[prow] : me.materialTree.items[prow].data;
    let updateData = {
      id: deleteRecode.mix_ratio_id,
      field: 'mix_ratio.consumption',
      value: 0,
      market_price: parentMarketPrice,
      base_price: parentBasePrice
    };
    projectObj.project.composition.deleteComposition(updateData, deleteRecode, prowData.id, function () {
      _.remove(me.mixRatioData, {
        "mix_ratio_id": deleteRecode.mix_ratio_id
      });
      me.refreshParentData(prow, prowData.id);
      me.mixRatioSheet.deleteRows(row, 1);
      me.onUnitFileChange(deleteRecode);
    });
  },
  getCompositionSumPrice: function (scene, affectRow, newValue = 0) {
    let me = this;
    let parentMarketPrice = 0;
    let parentBasePrice = 0;
    for (let i = 0; i < me.mixRatioData.length; i++) {
      let ratio = me.mixRatioData[i];
      let marketPrice = ratio.unit_price.market_price;
      let basePrice = ratio.unit_price.base_price;
      // 如果是删除则忽略即将被删除的行数据
      if (scene === 'delete' && affectRow === i) {
        continue;
      }
      let consumption = i === affectRow ? newValue : ratio.consumption;
      parentMarketPrice += operationWithRound(consumption, marketPrice, "glj.unitPrice", "*");
      parentBasePrice += operationWithRound(consumption, basePrice, "glj.unitPrice", "*");
    }
    parentMarketPrice = parentMarketPrice.toDecimal(getDecimal("glj.unitPrice"));
    parentBasePrice = parentBasePrice.toDecimal(getDecimal("glj.unitPrice"));
    return [parentMarketPrice, parentBasePrice];

  },
  onProjectGLJValueChange: function (e, info) { //me.projectGljSetting
    let projectGLJ = projectObj.project.projectGLJ;
    let me = projectGljObject,
      row = info.row,
      col = info.col;
    let setting = info.sheetName == "materialTreeSheet" ? me.materialSetting : me.projectGljSetting;
    let dataCode = setting.header[col].dataCode;
    let recode = info.sheetName == "materialTreeSheet" ? me.materialTree.selected.data : me.projectGljSheetData[row];
    let value = info.newValue;
    if (info.newValue === undefined) {
      return;
    }
    if (value && !me.checkData(col, setting, value)) {
      alert('输入的数据类型不对，请重新输入!');
      info.sheetName == "materialTreeSheet" ? me.materialTreeController.refreshTreeNode([me.materialTree.selected]) : me.refreshProjectGljRow(row);
      return;
    }
    let callback = function (impactList) {
      info.sheet.suspendPaint();
      info.sheet.suspendEvent();
      if (dataCode === 'is_adjust_price') {
        projectGLJ.calcQuantity();
      };

      if (info.sheetName == "materialTreeSheet") {
        me.showMaterialTreeData();
      } else {
        // me.refreshProjectGljRow(row);
        me.showProjectGljData();
        for (let g of impactList) {
          me.refreshProjectGljRowByID(g.id, row);
        }
      }
      info.sheet.resumeEvent();
      info.sheet.resumePaint();
      if (dataCode === 'supply' || dataCode === 'supply_quantity' || dataCode === 'is_adjust_price') { // basePrice、marketPrice 有自己的计算代码，无需走这里重复计算
        let rations = calcTools.getRationsByProjectGLJ(recode.id);
        projectObj.project.calcProgram.calcNodesAndSave(rations, function () {
          projectObj.mainController.refreshTreeNode(projectObj.project.mainTree.roots);
        });
      };
      gljOprObj.refreshView();
    };
    if (dataCode == 'basePrice' || dataCode == 'marketPrice') { //修改市场价和修改定额价时需要重新记算很多受影响的树节点，现在改成与定字额工料机那里调相同的方法。
      let editField = dataCode === 'basePrice' ? "base_price" : "market_price";
      projectObj.project.projectGLJ.updatePrice(recode, editField, value, 'pg', null, callback);
    } else {
      let extend = {};
      // 如果是供货方式则需要处理数据
      if (dataCode === 'supply') {
        extend.supply_quantity = me.getSupplyQuantity(value, recode.quantity);
      }
      if (dataCode === 'supply_quantity') { //修改数量需做4舍5入
        value = scMathUtil.roundForObj(value, getDecimal('glj.quantity'));
      }
      if (dataCode === 'is_evaluate' || dataCode === 'is_adjust_price' || dataCode === 'is_main_material' || dataCode === 'no_tax_eqp' || dataCode == 'is_eval_material') {
        value = value == true ? 1 : 0;
        if (dataCode === 'is_evaluate' || dataCode == 'is_eval_material') {
          configMaterialObj.updateConfigMaterial(dataCode, value, recode); //暂估材料，主要材料等新需求
          return
        }

      }
      if (dataCode === 'materialType' && (value == null || value == "")) { //删除三材类别时，清空三材系数
        value = null;
        extend.materialCoe = null;
      }
      if (dataCode == 'materialCoe') {
        value = scMathUtil.roundForObj(value, getDecimal("material"));
      }
      if (dataCode == 'taxRate') value = scMathUtil.roundToString(value, 2);

      extend = Object.keys(extend).length > 0 ? JSON.stringify(extend) : '';
      if (recode[dataCode] == value) return;

      let updateData = {
        id: recode.id,
        field: dataCode,
        value: value,
        extend: extend
      };
      projectGLJ.pGljUpdate(updateData, callback);
    };
  },
  refreshProjectGljRowByID: function (ID, row) { //row 可以不传，如果row 和 index 相等就不刷新
    let me = this;
    let index = _.findIndex(me.projectGljSheetData, {
      'id': ID
    });
    if (index >= 0 && index != row) {
      me.refreshProjectGljRow(index);
    }
  },
  getSupplyQuantity: function (supplyType, quantity) {
    // 自行采购和甲定乙供则把甲供数量设置为0，其余情况则设置为当前总消耗量
    let supplyQuantity = supplyType == 0 || supplyType == 3 ? 0 : quantity;
    supplyQuantity = parseFloat(supplyQuantity);
    return supplyQuantity;
  },
  getSupplyQuantityByGlj: function (glj, tender) {
    //{"自行采购":0,"部分甲供":1,"完全甲供":2,"甲定乙供":3};
    let supply_quantity = glj.supply_quantity;
    switch (glj.supply) {
      case 0:
        supply_quantity = 0;
        break;
      case 1:
        break;
      case 2:
        supply_quantity = tender ? glj.tenderQuantity : glj.quantity;
        break;
      case 3:
        supply_quantity = 0;
        break;
    }
    return supply_quantity
  },
  checkData: function (col, setting, value) {
    return sheetCommonObj.checkData(col, setting, value);
  },
  getProjectGLJSelected: function () {
    let me = this,
      data = null;
    let sheet = me.projectGljSpread.getActiveSheet();
    if (sheet.name() == 'projectGljSheet') { //projectGljSheet/materialSheet 工料机汇总和三材汇总表
      let sel = me.projectGljSheet.getSelections()[0];
      let srow = sel.row == -1 || sel.row == "" ? 0 : sel.row;
      if (me.projectGljSheetData.length > srow) {
        data = me.projectGljSheetData[srow];
      }
    } else if (sheet.name() == 'materialTreeSheet') {
      if (this.materialTree.selected) {
        data = this.materialTree.selected.data;
      }
    }
    return data;
  },
  initInfoPriceRightClick: function () {
    let me = this;
    $.contextMenu({
      selector: '#info_price_sheet',
      build: function ($trigger, e) {
        me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, me.infoPriceSpread);
        return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
          me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
      },
      items: {
        "apply": {
          name: "确认套用（或双快速套用）",
          icon: 'fa-sign-in',
          disabled: function () {
            return me.rightClickTarget.row === undefined;
          },
          callback: function (key, opt) {
            let row = me.rightClickTarget.row;
            me.preApplyInfoPrice(row);
          }
        }
      }
    });
  },
  initRightClick: function () {
    let activeSheet = this.mixRatioSheet;
    let me = this;
    $.contextMenu({
      selector: '#mix_ratio_sheet',
      build: function ($trigger, e) {
        me.rightClickTarget = SheetDataHelper.safeRightClickSelection($trigger, e, me.mixRatioSpread);
        return me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.viewport ||
          me.rightClickTarget.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
      },
      items: {
        "deleteMixRatio": {
          name: "删除",
          icon: 'fa-trash-o',
          disabled: function () {
            return me.rightClickTarget.row === undefined;
          },
          callback: function (key, opt) {
            let row = me.rightClickTarget.row;
            me.deleteMixRatio(row);
          },
          visible: function (key, opt) {
            if (!$('#mixRatio-nav').hasClass('active')) return false;
            return true;
          }
        },
        "addMixRatio": {
          name: '添加',
          icon: 'fa-sign-in',
          disabled: function () {
            let projectGLJ = projectGljObject.getProjectGLJSelected();
            return !_.includes(compositionTypes, projectGLJ.type);
          },
          callback: function (key, opt) {
            me.selectedProjectGLJ = projectGljObject.getProjectGLJSelected();
            getGLJData('addMix', null, true, null);
          },
          visible: function (key, opt) {
            if (!$('#mixRatio-nav').hasClass('active')) return false;
            return true;
          }
        }
      }
    });
  },
  changeFileCallback: function () {
    projectGljObject.unitPriceFileInit();
    projectGljObject.refreshViewsData();
    gljOprObj.refreshView();
    projectObj.project.calcProgram.calcAllNodesAndSave(calcAllType.catAll, function () {
      if (socketObject.roomInfo) {
        let data = {
          projectID: projectObj.project.ID(),
          oldRoom: socketObject.roomInfo.unitFile,
          newRoom: socketObject.getUnitFileRoomID(),
          userID: userID,
          name: 'unitFile'
        };
        socket.emit('changeNewRoom', data);
        socketObject.roomInfo.unitFile = socketObject.getUnitFileRoomID();
      }
    });

  },
  calcPartASupplyFeeByProjectGLJs: function (projectGLJsArr) {
    for (let pGLJ of projectGLJsArr) {
      if (pGLJ.supply == supplyType.BFJG) {
        let rations = calcTools.getRationsByProjectGLJ(pGLJ.id);
        projectObj.project.calcProgram.calcNodesAndSave(rations, function () {
          projectObj.mainController.refreshTreeNode(projectObj.project.mainTree.roots);
        });
      }
    }
  },
  checkUnitFileName: function (name, callback) {
    let projectGLJ = projectObj.project.projectGLJ;
    projectGLJ.checkUnitFileName(name, function (data) {
      if (data) {
        $("#save-as-tips").text('已存在同名单价文件').show();
        $('#save-as-confirm').attr("disabled", "disabled");
      } else {
        $("#save-as-tips").hide();
        $('#save-as-confirm').removeAttr("disabled");
        if (callback) callback();
      }
    });
  },
  initFilterTypeList: function () { //初始化人材机汇总工料机类型过滤列表
    let htmlString = ' <ul class="nav flex-column">';
    for (let t of this.displayTypeMap) {
      htmlString += '<li class="nav-item "><a class="nav-link pl-4" href="javascript:void(0)" id="' + t.ID + '">' + t.text + '</a></li>';
    }
    htmlString += '</ul>';
    $('#ALL').after(htmlString);
  },
  getInfoPriceOptions: async function () {
    let options = await ajaxPost("/infoPrice/getOptions", {});
    this.infoPriceOptions = options;
    this.createSelectOptions($("#info_area"), options.areas, true);
    let years = _.keysIn(options.periodMap);
    this.createSelectOptions($("#info_year"), _.sortBy(years));
  },
  createSelectOptions: function (ele, opts, isArea) {
    ele.empty();
    let str = `<option value=""></option>`;
    opts.sort((a, b) => a.serialNo - b.serialNo);
    for (let o of opts) {
      if (isArea == true) {
        str += `<option value="${o.ID}">${o.name}</option>`
        if (o.name == "通用") this.commonInfoPriceID = o.ID;
      } else {
        str += `<option value="${o}">${o}</option>`
      }

    }
    ele.html(str);
  },
  onInfoTopRowChanged: function (sender, args) {
    let me = projectGljObject;
    const bottomRow = args.sheet.getViewportBottomRow(1);
    if (me.infoPriceData >= me.infoPriceTotalSize) return;
    if (me.infoPriceData.length - bottomRow < 20) {
      if (projectGljObject.infoPriceLastLoadingRow == me.infoPriceData.length) { //如果最后一行已经加载过了，就不用再加载了，不然会重复加载
        return;
      }
      me.infoPriceLastLoadingRow = me.infoPriceData.length;
      //只有在空的搜索条件下才执行分页查询，其它情况无法分页
      if ($('#info_search_name').val() == "") me.searchInfoPrice(me.infoPriceData[me.infoPriceData.length - 1]._id)
    }
  },
  searchInfoClass:async function(){
    let me = projectGljObject;
    let areaID = $('#info_area').val();
    let year = $('#info_year').val();
    let month = $('#info_month').val();
    let datas = [];
    $('#info_class').val("");
    try {
      if (year != "" && month != "" && areaID != ""){
        let period = year + "-" + month;
        let condition = {areaID:areaID,period:period};
        if (projectGljObject.addCommonInfoPriceID) projectGljObject.addCommonInfoPriceID(condition);
        datas = await ajaxPost("/infoPrice/getClassByAreaID", condition);
      }
      me.showInforClassData(datas);
    } catch (error) {
       console.log(error)
    }
  },
  searchInfoPrice: async function (objectID) {
    let year = $('#info_year').val();
    let month = $('#info_month').val();
    let areaID = $('#info_area').val();
    let keyWord = $('#info_search_name').val();
    let name =  $('#info_glj_name').val();
    let code =  $('#info_glj_code').val();
    let classID = $("#info_class").val();
    let me = projectGljObject;
    try {
      if (year != "" && month != "" && areaID != "") {
        let condition = {
          period: year + "-" + month,
          areaID: areaID
        }
        if(classID!=""){
          keyWord = "";
          condition.classID = classID;
        } 
        
        if (projectGljObject.addCommonInfoPriceID) projectGljObject.addCommonInfoPriceID(condition);
        let data = {
          condition: condition
        };
        
        if (keyWord != "") data.keyWord = keyWord;
        if (name !="") data.keyWord = name;
        if (objectID) data.lastID = objectID;
        if (code !="" ) data.code = code;
        let result = await ajaxPost("/infoPrice/getDataByCondition", data);
        if (objectID) { //分页查询
          sheetCommonObj.appendData(me.infoPriceSheet, me.infoPriceData.length, 0, me.infoPriceSetting, result.items);
          me.infoPriceData.splice(me.infoPriceData.length, 0, ...result.items);
        } else {
          me.infoPriceTotalSize = result.totalSize;
          me.infoPriceLastLoadingRow = 0;

          me.showInforPriceData(result.items);
          if (result.totalSize == 0) {
            $("#info-warning").text("当前材料没有信息价！ ");
          } else { 
            $("#info-warning").text("");
          }
        }
      } else { //当有任意一个为空时，都清空表格
        me.infoPriceTotalSize = 0;
        me.infoPriceLastLoadingRow = 0;
        me.showInforPriceData([]);
      }
    } catch (error) {
      console.log(error)
    }
  },
  preApplyInfoPrice: function (row) {
    let info = this.infoPriceData[row];
    let projectGLJData = this.getProjectGLJSelected();
    if(!projectGLJData) return;
    if (projectGLJData.ratio_data && projectGLJData.ratio_data.length > 0) return;
    let marketPrice = this.getInfoMarketPrice(info);
    if (projectGLJData.unit == info.unit) {
      this.applyInfoPrice(projectGLJData, marketPrice, 1);
    } else if (_.includes(["t", "kg"], projectGLJData.unit) && _.includes(["t", "kg"], info.unit)) {
      //遇到t和kg之间的转换，默认处理：1t=1000kg，不弹换算窗口
      let coeMap = {
        "t": 1,
        "kg": 1000
      };
      let coe = coeMap[info.unit] / coeMap[projectGLJData.unit];
      this.applyInfoPrice(projectGLJData, marketPrice, coe);
    } else { //弹出单位转换窗口
      $("#infoRow").val(row);
      $("#applyGLJName").text(projectGLJData.name);
      $("#applyGLJUnit").text(projectGLJData.unit);
      $("#infoPriceCoe").val("");
      $("#applyInfoUnit").text(info.unit);
      $("#infoPriceCoeDiv").modal('show')
    }
  },
  applyInfoPrice: function (projectGLJData, price, coe) {
    let priceFrom = this.getPriceFrom();
    projectObj.project.projectGLJ.updatePrice(projectGLJData, "market_price", price * coe, 'pg', {
      "priceFrom": priceFrom
    });

  },
  getPriceFrom: function () {
    let area = "";
    for (let o of this.infoPriceOptions.areas) {
      if (o.ID == $("#info_area").val()) {
        area = o.name;
        break;
      }
    }
    return `${area}信息价(${$("#info_year").val()}${$("#info_month").val()})`;
  },

  getInfoMarketPrice: function (info) {
    let taxType = projectObj.project.property.taxType; //1: 一般计税 2: 简易计税
    return gljUtil.getInfoMarketPrice(info, taxType);
  },
  refreshInfoPrice: function () { 
    this.setInfoDivHeight();
    if ($('#info_price_sheet').is(':visible')){
      this.initInfoPriceSpread();
      this.initInfoClassSpread();
    }
  },
  setInfoDivHeight:function(){
    let info_height = $("#mix_ratio_sheet").height() - $("#infoToolDiv").height()-10;
    $('#info_price_main').height(info_height);
    $('#info_class_sheet').height(info_height);
    $('#info_price_sheet').height(info_height);
  }
};

function getProjectResizeEles() {
  let pojGljResizeEles = {};
  pojGljResizeEles.eleObj = {
    module: 'projectGlj',
    resize: $('#projectGljResize'),
    top: $('#projectGljTop'),
    topSpread: $('#project_glj_sheet'),
    bottom: $('#projectGljBottom'),
    bottomSpread: $('#mix_ratio_sheet')
  };
  pojGljResizeEles.limit = {
    min: 150,
    max: `$(window).height()-$('.header').height()-$('#projectGljToolsBar').height()-150-5`, //5: resize.height()
    notTopSpread: 0,
    notBottomSpread: 0,
    totalHeight: `$(window).height()-$('.header').height()-$('#projectGljToolsBar').height()-5`
  };
  return pojGljResizeEles;
}

function getConficMaterialResizeEles() {
  let conficMaterialResizeEles = {};
  conficMaterialResizeEles.eleObj = {
    module: 'conficMaterial',
    resize: $('#configMaterialResize'),
    top: $('#configMaterialTop'),
    topSpread: $('#config_material_sheet'),
    bottom: $('#configMaterialBottom'),
    bottomSpread: $('#related_sheet')
  };
  conficMaterialResizeEles.limit = {
    min: 150,
    max: `$(window).height()-$('.header').height()-$('#projectGljToolsBar').height()-150-5`, //5: resize.height()
    notTopSpread: 0,
    notBottomSpread: 0,
    totalHeight: `$(window).height()-$('.header').height()-$('#projectGljToolsBar').height()-5`,
    bottomNav: `$('#configMaterialBottom ul').height() + $('#filterToolDiv').height()+10`
  };
  return conficMaterialResizeEles;
}

function loadProjectGljSize() {
  if ($('#project-glj-main').is(':visible')) {
    let me = projectGljObject;
    let pojGljResizeEles = getProjectResizeEles();
    if (!$("#projectGljBottom").is(':visible')) {
      let total = $(window).height() - $('.header').height() - $('#projectGljToolsBar').height() + 3;
      $("#projectGljTop").height(total);
      $("#project_glj_sheet").height(total);
      me.projectGljSpread ? me.projectGljSpread.refresh() : '';
    } else {
      SlideResize.loadVerticalHeight(pojGljResizeEles.eleObj.module, pojGljResizeEles.eleObj, pojGljResizeEles.limit, function () {
        me.projectGljSpread ? me.projectGljSpread.refresh() : '';
        me.mixRatioSpread ? me.mixRatioSpread.refresh() : '';
        //信息价相关
        me.refreshInfoPrice();
      });
    }

  } else if ($('#material_adjust').is(':visible')) {
    $('#material_adjust_sheet').height($(window).height() - $('.header').height() - $('#projectGljToolsBar').height() + 3);
    if (materialAdjustObj.spread) materialAdjustObj.spread.refresh();
  } else if ($('#config_material').is(':visible')) {
    let configMaterialResizeEles = getConficMaterialResizeEles();
    SlideResize.loadVerticalHeight(configMaterialResizeEles.eleObj.module, configMaterialResizeEles.eleObj, configMaterialResizeEles.limit, function () {
      configMaterialObj.configSpread ? configMaterialObj.configSpread.refresh() : '';
      configMaterialObj.relatedSpread ? configMaterialObj.relatedSpread.refresh() : '';
      /*
      me.mixRatioSpread?me.mixRatioSpread.refresh():'';*/
    });
  }

}
//从其他建设项目中复制中，建设项目的文件层次结构名称和顺序
function getFileHierarchyInfo(treeData) {
  let tree = idTree.createNew({
    id: 'ID',
    pid: 'ParentID',
    nid: 'NextSiblingID',
    rootId: -1
  });
  tree.loadDatas(treeData);
  let items = tree.items;
  let rst = [];

  function getFileHierarchyName(node) {
    let nodeName = node.data.name;
    let name = [];
    while (node.parent) {
      name.push(node.parent.data.name ? node.parent.data.name : '');
      node = node.parent;
    }
    name = name.reverse();
    name.push(nodeName);
    return name.join('\\');
  }
  for (let node of items) {
    if (node.children.length === 0) { //project
      rst.push({
        ID: node.data.ID,
        fileHierarchyName: getFileHierarchyName(node)
      })
    }
  }
  return rst;
}

$(function () {
  let pojGljResizeEles = getProjectResizeEles();
  SlideResize.verticalSlide(pojGljResizeEles.eleObj, pojGljResizeEles.limit, function () {
    projectGljObject.projectGljSpread.refresh();
    projectGljObject.mixRatioSpread ? projectGljObject.mixRatioSpread.refresh() : '';
    projectGljObject.refreshInfoPrice();
  });

  let tr = getConficMaterialResizeEles();
  SlideResize.verticalSlide(tr.eleObj, tr.limit, function () {
    configMaterialObj.configSpread ? configMaterialObj.configSpread.refresh() : '';
    configMaterialObj.relatedSpread ? configMaterialObj.relatedSpread.refresh() : '';
  });


  $('#tab_project_glj').on('shown.bs.tab', function (e) {
    sessionStorage.setItem('mainTab', '#tab_project_glj');
    let me = projectGljObject;
    $(e.relatedTarget.hash).removeClass('active');
    if (me.projectGljSpread == null) {
      me.initSpreads();
    }
    me.unitPriceFileInit();
    me.initMixRatio();
    me.initSheetViews();
    //projectObj.project.projectGLJ.calcQuantity(); 在工程量有更新的地方调用
    me.refreshViewsData();
    loadProjectGljSize();
  });
  /*  $('#ration_link').on('shown.bs.tab', function (e) {
   let me = projectGljObject;
   me.showTag='ration';
   me.showProjectGljData();
   });
   $('#mix_ratio_link').on('shown.bs.tab', function (e) {
   let me = projectGljObject;
   me.showTag='mixRatio';
   me.showProjectGljData();
   me.initMixRatio();
   });
   $('#machine_ratio_link').on('shown.bs.tab', function (e) {
   let me = projectGljObject;
   me.showTag='machine';
   me.showProjectGljData();
   me.initMixRatio();
   });*/
  $('#pop-used-list').tooltip({
    placement: "bottom",
    html: true,
    trigger: "hover | focus",
    title: projectGljObject.getUsedTenderInfo
  });
  // 单价文件切换弹框
  $('#change-unitFile').on('shown.bs.modal', function () {
    let rootProjectID = projectObj.project.projectInfo.property.rootProjectID;
    // 获取切换单价文件相关数据
    $.ajax({
      url: '/glj/get-project-info',
      type: 'post',
      data: {
        project_id: scUrlUtil.GetQueryString('project'),
        rootProjectID: rootProjectID
      },
      dataType: 'json',
      success: function (response) {
        if (response.err === 1) {
          alert('数据传输错误!');
          return false;
        }
        let data = response.data;
        projectGljObject.changeInfo = data;
        $("#current-project-name").text(data.currentProjectName);
        // 本项目中的单价文件
        if (data.self.length > 0) {
          let selfFileHtml = '';
          for (let tmp of data.self) {
            let select = usedUnitPriceInfo === tmp.id ? ' selected="selected"' : '';
            selfFileHtml += '<option' + select + ' value="' + tmp.id + '">' + tmp.name + '</option>';
          }
          $("#self-file").html(selfFileHtml);
        }
        // 其他建设项目数据
        let newDataOther = [];
        if (data.other.length > 0) {
          //转换成按项目管理顺序，名称包含文件夹层次
          let fileHierarchyDatas = getFileHierarchyInfo(data.treeData);
          for (let fileHierarchyData of fileHierarchyDatas) {
            let projData = _.find(data.other, {
              ID: fileHierarchyData.ID
            });
            if (projData) {
              projData.name = fileHierarchyData.fileHierarchyName;
              newDataOther.push(projData);
            }
          }
          data.other = newDataOther;
          let otherProjectHtml = '';
          let otherFileHtml = '';
          for (let tmp of data.other) {
            otherProjectHtml += '<option value="' + tmp.ID + '">' + tmp.name + '</option>';
            otherFileData[tmp.ID] = tmp.unitPriceList;
            if (otherFileHtml !== '') {
              continue;
            }
            for (let unitPrice of tmp.unitPriceList) {
              otherFileHtml += '<option value="' + unitPrice.id + '">' + unitPrice.name + '</option>';
            }
          }
          $("#other-project").html(otherProjectHtml);
          $("#other-file").html(otherFileHtml);
        }
      }
    });
  });
  // 单价文件切换确认
  $("#change-file-confirm").click(function () {
    let type = $("input[name='change-type']:checked").val();
    type = parseInt(type);
    let changeUnitPriceId = 0;
    $('#change-unitFile').modal("hide");
    if (type === 0) {
      // 从本项目中选择
      changeUnitPriceId = $("#self-file").val();
      if (!changeUnitPriceId) {
        alert('单价文件不可为空');
        return;
      }
      submitFileChange(changeUnitPriceId, type);
    } else {
      // 从其他项目中复制
      changeUnitPriceId = $("#other-file").val();
      let newName = $("#other-file").children("option:selected").text();
      projectObj.project.projectGLJ.checkUnitFileName(newName, function (need_rename) {
        if (need_rename) {
          $("#rename-unitFile").modal({
            show: true
          });
          $("#newUnitFileID").val(changeUnitPriceId);
          $("#newUnitFileName").val(newName);
        } else {
          submitFileChange(changeUnitPriceId, type);
        }
      });
    }

    function submitFileChange(changeUnitPriceId, type) {
      let data = {
        project_id: scUrlUtil.GetQueryString('project'),
        change_id: changeUnitPriceId,
        type: type
      };
      projectObj.project.projectGLJ.changeFile(data, function () {
        projectGljObject.changeFileCallback();
      })
    }
  });
  // 单价文件选项切换
  $("input[name='change-type']").change(function () {
    let type = $(this).val();
    type = parseInt(type);
    $("#change-unitFile .option").hide();
    if (type === 0) {
      $(".option.select").show();
    } else {
      $(".option.copy").show();
    }
  });
  $("#unitFile-save-as").on('shown.bs.modal', function () {
    // 获取当前建设项数据
    $("#save-as-name").val(projectGljObject.usedUnitPriceInfo.name + '副本');
    projectGljObject.checkUnitFileName(projectGljObject.usedUnitPriceInfo.name + '副本');
  });

  // 从其他建设项目中复制 选择建设项目
  $("#other-project").change(function () {
    let projectId = $(this).val();
    if (otherFileData[projectId] === undefined) {
      return false;
    }
    let otherFileHtml = '';
    for (let unitPrice of otherFileData[projectId]) {
      otherFileHtml += '<option value="' + unitPrice.id + '">' + unitPrice.name + '</option>';
    }
    $("#other-file").html(otherFileHtml);
  });

  $('#save-as-name').change(function () {
    projectGljObject.checkUnitFileName(this.value);
  });

  $('#newUnitFileName').change(function () {
    let projectGLJ = projectObj.project.projectGLJ;
    projectGLJ.checkUnitFileName(this.value, function (data) {
      if (data) {
        $("#renameError_unitFile").text('已存在同名单价文件').show();
        //$('#renameUnitFileConfirm').attr("disabled","disabled");
      } else {
        $("#renameError_unitFile").hide();
        // $('#renameUnitFileConfirm').removeAttr("disabled");
      }
    });

  });
  $("#renameUnitFileConfirm").click(function () {
    let projectGLJ = projectObj.project.projectGLJ;
    let newName = $('#newUnitFileName').val();
    let changeUnitPriceId = $('#newUnitFileID').val();
    projectGLJ.checkUnitFileName(newName, function (data) {
      if (data) {
        $("#renameError_unitFile").text('已存在同名单价文件').show();
        //$('#renameUnitFileConfirm').attr("disabled","disabled");
      } else {
        $("#renameError_unitFile").hide();
        $('#rename-unitFile').modal('hide');
        // $('#renameUnitFileConfirm').removeAttr("disabled");
        let data = {
          project_id: scUrlUtil.GetQueryString('project'),
          change_id: changeUnitPriceId,
          type: 1,
          newName: newName
        };
        projectObj.project.projectGLJ.changeFile(data, function () {
          projectGljObject.changeFileCallback();
        })
      }
    });
  });
  // 单价文件另存为操作
  $("#save-as-confirm").click(function () {
    let projectGLJ = projectObj.project.projectGLJ;
    let name = $("#save-as-name").val();
    if (name === '') {
      $("#save-as-tips").text('请填写单价文件名称').show();
      return false;
    }
    let saveData = {
      name: name,
      project_id: scUrlUtil.GetQueryString('project')
    };
    projectGljObject.checkUnitFileName(name, function () {
      projectGLJ.saveAs(saveData, function () {
        projectGljObject.changeFileCallback();
        $("#unitFile-save-as").modal("hide");
      });
    });
  });

  $("#filterType").on("click", "ul li a", function (e) {
    let children = $('#filterType a');
    for (let c of children) {
      $(c).removeClass('active');
    }
    $(this).addClass('active');
    let me = projectGljObject;
    me.displayType = filterType[this.id];
    me.initSheetViews();
    me.refreshViewsData();
    loadProjectGljSize();
  });

  $("#mixRatio-nav").on('shown.bs.tab', function () {
    projectGljObject.mixRatioSpread.refresh();
    projectGljObject.showMixRatioData();
  });

  $("#ration-nav").on('shown.bs.tab', function () {
    projectGljObject.mixRatioSpread.refresh();
    projectGljObject.showRelatedRationDatas();
  });
  $("#info-nav").on('shown.bs.tab', function () {
    projectGljObject.refreshInfoPrice();
    projectGljObject.autoShowInfoPriceData(); 
  });
  $('#info_year').change(async function () {
    let periodMap = projectGljObject.infoPriceOptions.periodMap;
    let year = $(this).val();
    let month = $("#info_month").val();
    let options = periodMap[year];
    if (year == "") return projectGljObject.searchInfoPrice(); //为空的时候清空显示
    projectGljObject.createSelectOptions($("#info_month"), periodMap[year]);
    if (month != "") {
      if (_.includes(options, month)) {
        $("#info_month").val(month);
        projectGljObject.searchInfoClass();
        projectGljObject.searchInfoPrice();
      }
    }
  });
  $('#info_month').change(async function () {
    await projectGljObject.searchInfoClass();
    await projectGljObject.searchInfoPrice();
  });
  $('#info_area').change(async function () {
    await projectGljObject.searchInfoClass()
    await projectGljObject.searchInfoPrice();
  });
  $('#info_search_name').on('keypress', function (e) {
    $("#info-warning").text("");
    if (e.keyCode === 13) {
      $('#info_glj_name').val("");
      $('#info_glj_code').val("");
      $('#info_class').val("");
      projectGljObject.searchInfoPrice();
    }
  });

  $('#info_search_btn').on('click', function (e) {
    $('#info_glj_name').val("");
    $('#info_glj_code').val("");
    $('#info_class').val("");
    projectGljObject.searchInfoPrice();
  });

  $('#infoPriceCoeConfirm').on('click', function (e) {
    let me = projectGljObject;
    let infoPriceCoe = $("#infoPriceCoe").val();
    if (infoPriceCoe === "") return alert("请输入单位转换值!");
    if (!(/^\d+(\.\d+)?$/.test(infoPriceCoe))) return alert("请输入数字!");
    $("#infoPriceCoeDiv").modal('hide');
    let pojectGLJData = me.getProjectGLJSelected();
    let info = me.infoPriceData[parseInt($("#infoRow").val())];
    let marketPrice = me.getInfoMarketPrice(info);
    me.applyInfoPrice(pojectGLJData, marketPrice, parseFloat(infoPriceCoe));
  });

  $('#muti_apply_info').on('click', function (e) {
    let year = $('#info_year').val();
    let month = $('#info_month').val();
    let areaID = $('#info_area').val();
    if (year != "" && month != "" && areaID != "") {
      $("#mutiApplyInfoPriceDiv").modal("show");
    }
  });
  $('#mutiApplyinfoPriceConfirm').on('click', function (e) {
    let typeMap = {};
    let pgljMap = {};
    let year = $('#info_year').val();
    let month = $('#info_month').val();
    let areaID = $('#info_area').val();
    for (let e of $(".info_apply_type")) {
      if ($(e).prop('checked') == true) {
        typeMap[$(e).val()] = true;
      }
    }
    for (let pglj of projectGljObject.projectGljSheetData) {
      if (pglj.ratio_data && pglj.ratio_data.length > 0) continue; //有组成物时跳过
      let typeString = pglj.type + "";
      if (typeMap[typeString.charAt(0)]) {
        let index = gljUtil.getIndex(pglj, ["name", "specs", "unit"]);
        let obj = {
          pgljID: pglj.id,
          unitPriceID: pglj.unitPriceID,
          fullIndex: gljUtil.getIndex(pglj)
        };
        pgljMap[index] ? pgljMap[index].push(obj) : pgljMap[index] = [obj]; //考虑到只用三个去匹配会有重复的工料机，所以这里用数组
      }
    }
    if (_.isEmpty(pgljMap)) return;
    let condition = {
      period: year + "-" + month,
      areaID: areaID
    }
    let priceFrom = '批量信息价';
    projectObj.project.projectGLJ.mutiApplyInfoPrice(pgljMap, condition, priceFrom);

  });
});