/**
 * Created by zhang on 2019/5/15.
 */
let materialAdjustObj = {
  spread: null,
  priceInfoSheet: null,
  priceCoeSheet: null,
  priceInfoDatas: [],
  priceCoeDatas: [],
  priceInfoSetting: {
    header: [{
        headerName: "关联",
        headerWidth: 80,
        dataCode: "is_related",
        dataType: "String",
        cellType: 'checkBox'
      },
      {
        headerName: "材料号",
        headerWidth: 80,
        dataCode: "code",
        dataType: "String"
      },
      {
        headerName: "材料名称",
        headerWidth: 160,
        dataCode: "name",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "规格型号",
        headerWidth: 120,
        dataCode: "specs",
        hAlign: "left",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "单位",
        headerWidth: 45,
        dataCode: "unit",
        hAlign: "center",
        dataType: "String"
      },
      {
        headerName: "数量",
        headerWidth: 90,
        dataCode: "quantity",
        hAlign: "right",
        dataType: "Number",
        decimalField: 'glj.quantity'
      },
      {
        headerName: "风险系数%",
        headerWidth: 80,
        dataCode: "riskCoe",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "基准单价",
        headerWidth: 70,
        dataCode: "standardPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "投标单价",
        headerWidth: 70,
        dataCode: "marketPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "合价",
        headerWidth: 90,
        dataCode: "totalPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number",
        decimalField: 'bills.totalPrice'
      },
      {
        headerName: "供货方式",
        headerWidth: 70,
        dataCode: "supply",
        hAlign: "center",
        dataType: "String",
        cellType: 'comboBox',
        editorValueType: true,
        options: supplyComboMap
      },
      {
        headerName: "备注",
        headerWidth: 100,
        dataCode: "remark",
        hAlign: "left",
        dataType: "String"
      }
    ],
    view: {
      lockColumns: ["is_related", "quantity", "totalPrice", "originPlace", "vender", "supply"]
    }
  },
  priceCoeSetting: {
    header: [{
        headerName: "关联",
        headerWidth: 80,
        dataCode: "is_related",
        dataType: "String",
        cellType: 'checkBox'
      },
      {
        headerName: "材料号",
        headerWidth: 80,
        dataCode: "code",
        dataType: "String"
      },
      {
        headerName: "材料名称",
        headerWidth: 160,
        dataCode: "name",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "规格型号",
        headerWidth: 120,
        dataCode: "specs",
        hAlign: "left",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "单位",
        headerWidth: 45,
        dataCode: "unit",
        hAlign: "center",
        dataType: "String"
      },
      {
        headerName: "变值权重B",
        headerWidth: 90,
        dataCode: "varWeight",
        hAlign: "right",
        dataType: "Number",
        validator: "number",
        formatter: "0.00"
      },
      {
        headerName: "基本价格指数F0",
        headerWidth: 70,
        dataCode: "FO",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "现行价格指数Ft",
        headerWidth: 70,
        dataCode: "FI",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "数量",
        headerWidth: 90,
        dataCode: "quantity",
        hAlign: "right",
        dataType: "Number",
        decimalField: 'glj.quantity'
      },
      {
        headerName: "单价",
        headerWidth: 70,
        dataCode: "marketPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      },
      {
        headerName: "合价",
        headerWidth: 90,
        dataCode: "totalPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number",
        decimalField: 'bills.totalPrice'
      },
      {
        headerName: "供货方式",
        headerWidth: 70,
        dataCode: "supply",
        hAlign: "center",
        dataType: "String",
        cellType: 'comboBox',
        editorValueType: true,
        options: supplyComboMap
      },
      {
        headerName: "备注",
        headerWidth: 100,
        dataCode: "remark",
        hAlign: "left",
        dataType: "String"
      }
    ],
    view: {
      lockColumns: ["is_related", "quantity", "totalPrice", "originPlace", "varWeight", "vender", "supply"]
    }
  },
  refreshSheetDatas: function () {
    //读项目属性的值，若没有则默认为造价信息差额调整法
    let adjustType = $('#adjustType').val();
    if (adjustType === 'priceInfo') {
      materialAdjustObj.showPriceInfoDatas();
    } else {
      materialAdjustObj.showPriceCoeDatas();
    }
    configMaterialObj.showEvaluateRelateDatas();
  },
  getSheetDatas: function () {
    let adjustType = $('#adjustType').val();
    return adjustType === 'priceInfo' ? this.priceInfoDatas : this.priceCoeDatas;
  },
  getSheet: function () {
    let adjustType = $('#adjustType').val();
    return adjustType === 'priceInfo' ? this.priceInfoSheet : this.priceCoeSheet;
  },
  initPriceInfoSheet: function () {
    this.priceInfoSheet = configMaterialObj.configSpread.getSheet(2);
    sheetCommonObj.initSheet(this.priceInfoSheet, this.priceInfoSetting, 30);
    this.priceInfoSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onSheetValueChange);
    this.priceInfoSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onSelectionChange);
    this.priceInfoSheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onPriceInfoEditString);
    this.priceInfoSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onSheetRangeChange);
    this.priceInfoSheet.name('priceInfoSheet');
    this.priceInfoSheet.setRowHeight(0, 36, 1);
  },
  initPriceCoeSheet: function () {
    this.priceCoeSheet = configMaterialObj.configSpread.getSheet(3);
    sheetCommonObj.initSheet(this.priceCoeSheet, this.priceCoeSetting, 30);
    this.priceCoeSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onSheetValueChange);
    this.priceCoeSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, this.onSelectionChange);
    this.priceCoeSheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onPriceInfoEditString);
    this.priceCoeSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onSheetRangeChange);
    this.priceCoeSheet.name('priceCoeSheet');
    this.priceCoeSheet.setRowHeight(0, 36, 1);
  },
  onSelectionChange: function (sender, args) {
    let me = configMaterialObj;
    let newSel = args.newSelections[0];
    let oldSel = args.oldSelections ? args.oldSelections[0] : {};
    if (newSel.row != oldSel.row) {
      me.showEvaluateRelateDatas();
      me.relateFilterAgain = false;
    }
  },
  onSheetRangeChange: function (a, args) {
    let me = materialAdjustObj,
      updateMap = {},
      tasks = [];
    let projectGLJ = projectObj.project.projectGLJ;
    let setting = $("#adjustType").val() == "priceInfo" ? me.priceInfoSetting : me.priceCoeSetting;
    let datas = $("#adjustType").val() == "priceInfo" ? me.priceInfoDatas : me.priceCoeDatas;
    for (let c of args.changedCells) {
      let dataCode = setting.header[c.col].dataCode;
      let value = args.sheet.getCell(c.row, c.col).text();
      let recode = datas[c.row];
      if (dataCode == "unit" && recode.is_related) {
        me.refreshSheetDatas();
        return;
      }
      if (value && !sheetCommonObj.checkData(c.col, setting, value)) {
        alert('输入的数据类型不对，请重新输入!');
        me.refreshSheetDatas();
        return;
      }
      if (dataCode == 'marketPrice') {
        dataCode = 'market_price';
        if (recode.is_related) { //关联的情况下，直接修改工料机价格
          return projectGLJ.updatePrice(recode, dataCode, value, 'rg', null, projectGljObject.refreshViewsData);
        }
      } else {
        let tem = updateMap[recode.ID] ? updateMap[recode.ID] : {};
        if (value && dataCode == "standardPrice") value = scMathUtil.roundForObj(value, getDecimal('glj.unitPrice')) + "";
        if (value == recode[dataCode]) continue;
        tem[dataCode] = value;
        updateMap[recode.ID] = tem;
      }
    }
    for (let ID in updateMap) {
      let edata = {
        type: "contractor_list",
        doc: updateMap[ID],
        action: "update",
        ID: ID
      };
      tasks.push(edata);
    }
    if (tasks.length > 0) configMaterialObj.updateEvaluateMaterial(tasks, false);


  },
  onPriceInfoEditString: function (a, args) {
    let me = materialAdjustObj;
    let setting = $("#adjustType").val() == "priceInfo" ? me.priceInfoSetting : me.priceCoeSetting;
    let datas = $("#adjustType").val() == "priceInfo" ? me.priceInfoDatas : me.priceCoeDatas;
    let dataCode = setting.header[args.col].dataCode;
    let recorde = datas[args.row];
    if (recorde) {
      if (recorde.is_related && dataCode == "unit") args.cancel = true;
    }
  },

  onSheetValueChange: function (a, args) {
    let me = materialAdjustObj,
      row = args.row,
      col = args.col;
    let setting = $("#adjustType").val() == "priceInfo" ? me.priceInfoSetting : me.priceCoeSetting;
    let datas = $("#adjustType").val() == "priceInfo" ? me.priceInfoDatas : me.priceCoeDatas;
    let dataCode = setting.header[col].dataCode;
    let evaluate = datas[row];
    let value = args.newValue;
    if (value && !sheetCommonObj.checkData(col, setting, value)) {
      alert('输入的数据类型不对，请重新输入!');
      return me.refreshSheetDatas();
    }
    if (dataCode == 'marketPrice') {
      dataCode = 'market_price';
      if (evaluate.is_evaluate == 1) {
        alert("当前材料市场价已被锁定，修改请先返回人材机汇总界面解除锁定。");
        return me.refreshSheetDatas();
      }
      if (evaluate.is_related) { //关联的情况下，直接修改工料机价格
        return projectObj.project.projectGLJ.updatePrice(evaluate, dataCode, value, 'rg', null, projectGljObject.refreshViewsData);
      }
    }
    if (dataCode == "standardPrice") value = scMathUtil.roundForObj(value, getDecimal('glj.unitPrice')) + "";
    let edata = {
      type: 'contractor_list',
      doc: {},
      action: "update",
      ID: evaluate.ID
    };
    if (evaluate[dataCode] == value) return me.refreshSheetDatas();
    edata.doc[dataCode] = value;
    configMaterialObj.updateEvaluateMaterial([edata], false);
  },
  deleteAdjust: function () {
    let me = this,
      updateMap = {};
    let projectGLJ = projectObj.project.projectGLJ;
    let datas = $("#adjustType").val() == "priceInfo" ? me.priceInfoDatas : me.priceCoeDatas;
    let sels = this.spread.getActiveSheet().getSelections();
    let select = sels.length > 0 ? sels[0] : null;
    if (!select) return;
    for (let i = 0; i < select.rowCount; i++) {
      let recode = datas[select.row + i];
      if (recode) updateMap[recode.id] = {
        is_info_adjust: 0,
        is_coe_adjust: 0
      };
    }
    if (_.isEmpty(updateMap)) return;
    projectGLJ.batchUpdateGLJProperty(updateMap, materialAdjustObj.refreshSheetDatas);

  },
  showPriceInfoDatas: function () {
    configMaterialObj.configSpread.setActiveSheetIndex(2);
    let sel = this.priceInfoSheet.getSelections()[0];
    let oldData = sel.row < this.priceInfoDatas.length ? this.priceInfoDatas[sel.row] : "";
    this.priceInfoDatas = this.getPirceInfoDatas();
    sheetCommonObj.showData(this.priceInfoSheet, this.priceInfoSetting, this.priceInfoDatas);
    this.priceInfoSheet.setRowCount(this.priceInfoDatas.length);
    sel.row = oldData ? _.findIndex(this.priceInfoDatas, {
      'ID': oldData.ID
    }) : '';
    this.priceInfoSheet.setSelection(sel.row == -1 ? 0 : sel.row, sel.col, sel.rowCount, sel.colCount);
  },
  showPriceCoeDatas: function () {
    configMaterialObj.configSpread.setActiveSheetIndex(3);
    let sel = this.priceCoeSheet.getSelections()[0];
    let oldData = sel.row < this.priceCoeDatas.length ? this.priceCoeDatas[sel.row] : "";
    this.priceCoeDatas = this.getPriceCoeDatas();
    sheetCommonObj.showData(this.priceCoeSheet, this.priceCoeSetting, this.priceCoeDatas);
    this.priceCoeSheet.setRowCount(this.priceCoeDatas.length);
    sel.row = oldData ? _.findIndex(this.priceCoeDatas, {
      'ID': oldData.ID
    }) : '';
    this.priceCoeSheet.setSelection(sel.row == -1 ? 0 : sel.row, sel.col, sel.rowCount, sel.colCount);
  },
  getPirceInfoDatas: function (projectGLJList, contractor_list, decimalObj) {
    let datas = [];
    let pgljList = projectGLJList ? projectGLJList : projectObj.project.projectGLJ.datas.gljList;
    let contractorList = contractor_list ? contractor_list : projectObj.project.contractor_list.datas;
    let billsDecimal = decimalObj ? decimalObj.bills.totalPrice : getDecimal('bills.totalPrice');
    let gljMap = _.indexBy(pgljList, 'id');
    for (let e of contractorList) {
      let t = {
        ID: e.ID,
        projectID: e.projectID,
        is_related: e.is_related, //关联，1关，0不关
        projectGLJID: e.projectGLJID, //关联工料机ID
        seq: e.seq, //序号
        code: e.code,
        name: e.name,
        specs: e.specs,
        unit: e.unit,
        type: e.type,
        marketPrice: e.market_price,
        quantity: e.quantity,
        remark: e.remark,
        supply: e.supply,
        riskCoe: e.riskCoe,
        is_evaluate: 0,
        standardPrice: e.standardPrice
      };
      let pglj = gljMap[e.projectGLJID];
      if (e.is_related && pglj) {
        gljOprObj.setGLJPrice(t, pglj);
        t.vender = pglj.vender;
        t.supply = pglj.supply;
        t.is_evaluate = pglj.is_evaluate;
        t.quantity = pglj.quantity;
      }
      t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice), billsDecimal);
      datas.push(t);
    }
    return _.sortByAll(datas, 'code');
  },
  getPriceCoeDatas: function (projectGLJList, contractor_list, totalFee, projectProperty) {
    let pgljList = projectGLJList ? projectGLJList : projectObj.project.projectGLJ.datas.gljList;
    let contractorList = contractor_list ? contractor_list : projectObj.project.contractor_list.datas;
    let tprojectProperty = projectProperty?projectProperty:projectObj.project.projectInfo.property;
    if (!gljUtil.isDef(totalFee)) {
      let node = projectObj.project.Bills.getEngineeringCostNode(projectObj.mainController);
      totalFee = node && node.data.feesIndex && node.data.feesIndex.common ? node.data.feesIndex.common.totalFee : 0;
    }
    return gljUtil.getPriceCoeDatas(pgljList, contractorList, totalFee, tprojectProperty,_,scMathUtil)

    /* for (let e of contractorList) {
      let t = {
        ID: e.ID,
        projectID: e.projectID,
        is_related: e.is_related, //关联，1关，0不关
        projectGLJID: e.projectGLJID, //关联工料机ID
        seq: e.seq, //序号
        code: e.code,
        name: e.name,
        specs: e.specs,
        unit: e.unit,
        type: e.type,
        marketPrice: e.market_price,
        quantity: e.quantity,
        remark: e.remark,
        supply: e.supply,
        is_evaluate: 0,
        FO: e.FO,
        FI: e.FI
      };
      let pglj = gljMap[e.projectGLJID];
      if (e.is_related && pglj) {
        gljOprObj.setGLJPrice(t, pglj);
        t.vender = pglj.vender;
        t.supply = pglj.supply;
        t.quantity = pglj.quantity;
        t.is_evaluate = pglj.is_evaluate;
      }
      t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice), billsDecimal);
      if (totalFee !== 0) t.varWeight = scMathUtil.roundForObj(t.totalPrice / totalFee, 2);
      datas.push(t);
    }
    return _.sortByAll(datas, 'code'); */
  },
  getCommonObject: function (glj) {
    let data = {
      select: 0,
      id: glj.id,
      code: glj.code,
      name: glj.name,
      specs: glj.specs,
      unit: glj.unit,
      type: glj.type,
      quantity: glj.quantity,
      supply: glj.supply,
      originPlace: glj.originPlace,
      vender: glj.vender,
      brand: glj.brand,
      remark: glj.remark
    };
    gljOprObj.setGLJPrice(data, glj);
    return data;
  },
  checkedDefualtOption: function (className) {
    for (let a of $("." + className)) {
      if (className == "pglj_sel_input" || a.id == "glj_sel_material" || a.id == "glj_sel_main" || a.id == "glj_sel_eqp") $(a).prop("checked", true)
    }
  },
  insertEmptyRow: function () {
    let ndata = {
      type: "contractor_list",
      doc: {},
      action: "add"
    };
    ndata.doc['ID'] = uuid.v1();
    ndata.doc['is_related'] = 0;
    ndata.doc['seq'] = "";
    ndata.doc['projectID'] = projectObj.project.ID();
    ndata.doc['code'] = "";
    ndata.doc['name'] = "";
    ndata.doc['unit'] = "";
    ndata.doc['originPlace'] = "";
    ndata.doc['vender'] = "";
    ndata.doc['remark'] = "";
    ndata.doc['supply'] = "";
    ndata.doc['riskCoe'] = "";
    ndata.doc['standardPrice'] = "";
    ndata.doc['FO'] = "";
    ndata.doc['FI'] = "";
    configMaterialObj.updateEvaluateMaterial([ndata], false);
  }
};

let gljFromObj = {
  spread: null,
  sheet: null,
  datas: [],
  setting: {
    header: [{
        headerName: "选择",
        headerWidth: 45,
        dataCode: "select",
        hAlign: "center",
        dataType: "String",
        cellType: 'checkBox'
      },
      {
        headerName: "编码",
        headerWidth: 80,
        dataCode: "code",
        dataType: "String"
      },
      {
        headerName: "类型",
        headerWidth: 30,
        dataCode: "short_name",
        hAlign: "center",
        dataType: "String"
      },
      {
        headerName: "名称",
        headerWidth: 160,
        dataCode: "name",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "规格型号",
        headerWidth: 100,
        dataCode: "specs",
        hAlign: "left",
        dataType: "String",
        cellType: 'tipsCell'
      },
      {
        headerName: "单位",
        headerWidth: 45,
        dataCode: "unit",
        hAlign: "center",
        dataType: "String"
      },
      {
        headerName: "总消耗量",
        headerWidth: 90,
        dataCode: "quantity",
        hAlign: "right",
        dataType: "Number",
        decimalField: 'glj.quantity'
      },
      {
        headerName: "市场价",
        headerWidth: 70,
        dataCode: "marketPrice",
        hAlign: "right",
        dataType: "Number",
        validator: "number"
      }, //,decimalField:"glj.unitPrice"
      {
        headerName: "供货方式",
        headerWidth: 70,
        dataCode: "supply",
        hAlign: "center",
        dataType: "String",
        cellType: 'comboBox',
        editorValueType: true,
        options: supplyComboMap
      },
      {
        headerName: "暂估",
        headerWidth: 45,
        dataCode: "is_evaluate",
        hAlign: "center",
        dataType: "String",
        cellType: 'checkBox'
      },
      {
        headerName: "产地",
        headerWidth: 80,
        dataCode: "originPlace",
        hAlign: "left",
        dataType: "String"
      },
      {
        headerName: "厂家",
        headerWidth: 80,
        dataCode: "vender",
        hAlign: "left",
        dataType: "String"
      },
      {
        headerName: "备注",
        headerWidth: 100,
        dataCode: "remark",
        hAlign: "left",
        dataType: "String"
      }
    ],
    view: {
      lockColumns: ["is_evaluate"]
    }
  },
  checkType: "取消", //记住点击过的按钮的text
  initSpread: function () {
    if (!this.spread) {
      this.spread = SheetDataHelper.createNewSpread($("#glj_from_sheet")[0]);
      sheetCommonObj.spreadDefaultStyle(this.spread);
    } else {
      this.spread.refresh();
    }
    this.sheet = this.spread.getSheet(0);
    sheetCommonObj.initSheet(this.sheet, this.setting);
    this.sheet.bind(GC.Spread.Sheets.Events.EditStarting, this.onEditStarting);
    this.sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, this.onClipboardPasting);
    this.sheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onValueChanged);
    this.sheet.setRowHeight(0, 36, 1);
    disableRightMenu("glj_from_sheet", this.spread);
  },
  onEditStarting: function (e, args) {
    args.cancel = true;
  },
  onClipboardPasting: function (e, args) {
    args.cancel = true;
  },
  onValueChanged: function (e, args) {
    let me = gljFromObj;
    let value = args.newValue;
    value = value == true ? 1 : 0;
    me.datas[args.row].select = value;
  },
  showDatas: function () {
    this.datas = [];
    let gljList = projectObj.project.projectGLJ.datas.gljList;
    gljList = this.filterGLJ(gljList);
    gljList = sortProjectGLJ(gljList);
    for (let glj of gljList) {
      this.datas.push(this.getSheetDatas(glj));
    }
    this.refreshDatas();
  },
  filterGLJ: function (gljList) {
    let typeMap = {};
    for (let ch of $(".glj_sel_input:checked")) {
      typeMap[$(ch).val()] = true;
    }
    let inputV = $("#glj_sel_input").val();
    return _.filter(gljList, function (item) {
      if (item.quantity === 0 || item.quantity === '0') return false;
      if (!typeMap[0]) { //如果没有勾选所有，下面再细分
        let firstS = (item.type + "").substring(0, 1);
        if (!typeMap[firstS]) return false
      }
      if (inputV != "") { //输入的关键字过滤
        if (item.code.indexOf(inputV) == -1 && item.name.indexOf(inputV) == -1) return false
      }
      return true;
    });
  },
  refreshDatas: function () {
    this.checkByType(this.checkType);
    sheetCommonObj.showData(this.sheet, this.setting, this.datas);
    this.sheet.setRowCount(this.datas.length);
  },
  getSheetDatas(glj) {
    let projectGLJ = projectObj.project.projectGLJ;
    let materialIdList = projectGLJ.datas.constData.materialIdList;
    let data = materialAdjustObj.getCommonObject(glj);
    data.select = 0;
    data.short_name = projectGLJ.getShortNameByID(glj.type);
    // 只有材料才显示是否暂估
    if (materialIdList.indexOf(glj.type) >= 0) data.is_evaluate = glj.is_evaluate;
    data.from = glj;
    data.is_contractor_material = glj.is_contractor_material;
    return data;
  },
  checkByType: function (type) {
    for (let d of this.datas) {
      d.select = 0;
      switch (type) {
        case "全选":
          d.select = 1;
          break;
        case "全选主材":
          if (d.type == 4) d.select = 1;
          break;
        case "全选设备":
          if (d.type == 5) d.select = 1;
          break;
        case "取消":
          d.select = d.is_contractor_material ? 1 : 0;
          break;
      }
    }
  },
  confirmSelect: function () {
    let tasks = [];
    let datas = projectObj.project.contractor_list.datas,
      modelType = 'contractor_list',
      field = 'is_contractor_material';
    let evaluateMap = _.indexBy(datas, "projectGLJID");
    let evaluateKeyMap = {}; //关键字映射表
    for (let e of datas) {
      let eIndex = gljUtil.getIndex(e, gljUtil.materialKeyArray);
      evaluateKeyMap[eIndex] = e;
    }
    for (let d of this.datas) {
      if (d.select == 1) { //如果是选中状态
        if (d[field] == 1) { //如果已经标记为承包人材料
          let evl = evaluateMap[d.id];
          if (evl) {
            //这里应该是错误检查的保证，按正常是不应该出现这种情况的
            if (evl.is_related != 1) tasks.push({
              type: modelType,
              doc: {
                projectGLJID: d.id,
                is_related: 1
              },
              action: "update",
              ID: evl.ID
            });
          } else {
            tasks.push(getNewEval(d, modelType))
          }
        } else { //如果不是暂估，要改成暂估
          let pdata = {
            id: d.id,
            doc: {},
            action: 'update',
            type: "glj_list"
          };
          pdata.doc[field] = 1;
          tasks.push(pdata);
          let evaluate = evaluateKeyMap[gljUtil.getIndex(d, gljUtil.materialKeyArray)];
          if (evaluate) { //如果已经存在5个关键字相同的暂估材料，则自动关联起来
            let edata = {
              type: modelType,
              doc: {
                projectGLJID: d.id,
                is_related: 1
              },
              action: "update",
              ID: evaluate.ID
            };
            tasks.push(edata);
          } else { //如果不存在，则生成一条新的
            tasks.push(getNewEval(d, modelType));
          }
        }
      } else { //未选中状态的，检查一下是否存在关联的情况，取消关联
        let tdoc = {};
        tdoc[field] = 0;
        if (d[field] == 1) tasks.push({
          id: d.id,
          doc: tdoc,
          action: 'update',
          type: "glj_list"
        });
        let evl = evaluateMap[d.id];
        if (evl) {
          if (evl.is_related == 1) tasks.push({
            type: modelType,
            doc: {
              is_related: 0
            },
            action: "update",
            ID: evl.ID
          });
        }
        let evaluate = evaluateKeyMap[gljUtil.getIndex(d, gljUtil.materialKeyArray)];
        if (evaluate) {
          if (evaluate.is_related == 1) tasks.push({
            type: modelType,
            doc: {
              is_related: 0
            },
            action: "update",
            ID: evaluate.ID
          });
        }
      }
    }
    if (tasks.length > 0) configMaterialObj.updateEvaluateMaterial(tasks);


    function getNewEval(d, m_t) {
      let ndata = {
        type: m_t,
        doc: {},
        action: "add"
      };
      ndata.doc['ID'] = uuid.v1();
      ndata.doc['projectGLJID'] = d.id;
      ndata.doc['is_related'] = 1;
      ndata.doc['seq'] = d.code;
      ndata.doc['projectID'] = d.from.project_id;
      ndata.doc['code'] = d.code;
      ndata.doc['name'] = d.name;
      ndata.doc['specs'] = d.specs;
      ndata.doc['unit'] = d.unit;
      ndata.doc['quantity'] = d.quantity;
      ndata.doc['type'] = d.type;
      ndata.doc['market_price'] = d.from.unit_price.market_price;
      ndata.doc['originPlace'] = d.originPlace;
      ndata.doc['vender'] = d.vender;
      ndata.doc['remark'] = d.remark;
      ndata.doc['supply'] = d.supply;
      ndata.doc['riskCoe'] = "";
      ndata.doc['standardPrice'] = d.from.unit_price.market_price;
      ndata.doc['FO'] = "";
      ndata.doc['FI'] = "";
      return ndata;
    }
  }
};


$(function () {
  $("#adjustType").change(function () {
    materialAdjustObj.refreshSheetDatas();
    let val = $(this).val();
    let mixDatas = {
      projectID: projectObj.project.projectInfo.ID,
      updateType: 'update',
      properties: {
        'property.gljAdjustType': val
      },
      options: {},
      labourCoes: {},
      rations: [],
      bills: []
    };
    CommonAjax.post('/pm/api/updateMixDatas', {
      user_id: userID,
      mixDataArr: mixDatas
    }, function (rstData) {
      projectObj.project.projectInfo.property.gljAdjustType = val;
    });
  });
  $('#selectFromGLJ').on('shown.bs.modal', function (e) {
    gljFromObj.checkType = "取消";
    gljFromObj.initSpread();
    gljFromObj.showDatas();
  });
  $(".glj_sel_input").change(function () {
    let check = $(this).prop("checked");
    if ($(this).val() == 0) { //勾选的是全选，其它的勾选项跟着改变
      for (let a of $(".glj_sel_input")) {
        $(a).prop("checked", check)
      }
    } else { //勾选其它选项
      let a_checked = true;
      for (let o of $(".glj_sel_input_other")) { //如果其它的有一个不勾选，则所有项也不打勾
        if ($(o).prop("checked") === false) {
          a_checked = false;
          break;
        }
      }
      $("#glj_sel_all").prop("checked", a_checked);
    }

    gljFromObj.showDatas();
  });

  $("#glj_sel_btn_find").click(function () {
    gljFromObj.showDatas();
  });

  $(".glj_sel_check_btn").click(function () {
    gljFromObj.checkType = $(this).text();
    gljFromObj.refreshDatas();
  })

  $("#glj_sel_confirm").click(function () {
    gljFromObj.confirmSelect();
  })
});