/**
 * Created by chen on 2017/7/25.
 */

var gljContextMenu = {
  selectedRow: null,
  selectedCol: null,
  clipboard: null,
  loadGLJSpreadContextMenu: function () {
    $.contextMenu({
      selector: "#subSpread",
      build: this.onbuild,
      items: {
        replace_glj: {
          name: "替换",
          icon: "fa-sign-in",
          disabled: function () {
            var sheetData = gljOprObj.sheetData;
            if (gljOprObj.isInstallationNode(projectObj.project.mainTree.selected)) {
              return true;
            }
            if (subSpread.getActiveSheetIndex() == 0 && sheetData != null && sheetData.length > 0 && gljContextMenu.selectedRow < sheetData.length) {
              if (sheetData[gljContextMenu.selectedRow].isMixRatio == true) {
                return true;
              }
              return false;
            }
            return true;
          },
          callback: function () {
            getGLJData("replace");
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "ration_glj";
          },
        },
        add_glj: {
          name: "添加",
          icon: "fa-sign-in",
          disabled: function () {
            var selected = projectObj.project.mainTree.selected;
            var sheetData = gljOprObj.sheetData;
            if (selected) {
              if (selected.sourceType != ModuleNames.ration) {
                return true;
              } else if (selected.data.type != rationType.ration) {
                return true;
              }
            }
            if (subSpread.getActiveSheetIndex() == 0 && sheetData != null && sheetData.length > 0 && gljContextMenu.selectedRow < sheetData.length) {
              if (sheetData[gljContextMenu.selectedRow].isMixRatio == true) {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            getGLJData("add");
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "ration_glj";
          },
        },
        delete_glj: {
          name: "删除",
          icon: "fa-remove",
          disabled: function () {
            var sheetData = gljOprObj.sheetData;
            if (gljOprObj.isInstallationNode(projectObj.project.mainTree.selected)) {
              return true;
            }
            if (subSpread.getActiveSheetIndex() == 0 && sheetData != null && sheetData.length > 0 && gljContextMenu.selectedRow < sheetData.length) {
              if (sheetData[gljContextMenu.selectedRow].isMixRatio == true) {
                return true;
              }
              return false;
            } else {
              return true;
            }
          },
          callback: function () {
            var sheetData = gljOprObj.sheetData;
            var deleteRow = sheetData[gljContextMenu.selectedRow];
            projectObj.project.ration_glj.updataOrdelete(deleteRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "ration_glj";
          },
        },
        m_replace_glj: {
          name: "批量替换",
          icon: "fa-sign-in",
          disabled: function () {
            let sheetData = gljOprObj.sheetData;
            if (gljOprObj.isInstallationNode(projectObj.project.mainTree.selected)) {
              return true;
            }
            if (subSpread.getActiveSheetIndex() == 0 && sheetData != null && sheetData.length > 0 && gljContextMenu.selectedRow < sheetData.length) {
              if (sheetData[gljContextMenu.selectedRow].isMixRatio == true) {
                return true;
              }
              return false;
            }
            return true;
          },
          callback: function () {
            getGLJData("m_replace");
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "ration_glj";
          },
        },
        add_to_lib: {
          name: "保存到我的人材机库",
          icon: "fa-sign-in",
          disabled: function () {
            var sheetData = gljOprObj.sheetData;
            if (gljOprObj.isInstallationNode(projectObj.project.mainTree.selected)) {
              return true;
            }
            if (subSpread.getActiveSheetIndex() == 0 && sheetData != null && sheetData.length > 0 && gljContextMenu.selectedRow < sheetData.length) {
              var recode = sheetData[gljContextMenu.selectedRow];
              if (!(recode.isMixRatio != true && recode.isAdd == true)) {
                return true;
              }
              return false;
              //  disable= recode.isMixRatio!=true&&recode.isAdd==true?false:true
            }
            return true;
          },
          callback: function () {
            var sheetData = gljOprObj.sheetData;
            var recode = sheetData[gljContextMenu.selectedRow];
            showGLJClassTree(recode);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "ration_glj";
          },
        },
        insert_detail: {
          name: "插入行",
          icon: "fa-sign-in",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              var sheetData = gljOprObj.detailData;
              if (gljOprObj.detailSheetReadonly()) {
                return true;
              } else {
                return gljContextMenu.selectedRow > sheetData.length;
              }
            }
            return false;
          },
          callback: function () {
            projectObj.project.quantity_detail.insertQuantityDetail(gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        delete_detail: {
          name: "删除行",
          icon: "fa-remove",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              var sheetData = gljOprObj.detailData;
              return gljContextMenu.selectedRow > sheetData.length - 1;
            }
            return false;
          },
          callback: function () {
            projectObj.project.quantity_detail.deleteQuantityDetail(gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        move_up: {
          name: "上移",
          icon: "fa-arrow-up",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              var sheetData = gljOprObj.detailData;
              return gljContextMenu.selectedRow == 0 || gljContextMenu.selectedRow > sheetData.length - 1;
            }
            return false;
          },
          callback: function () {
            projectObj.project.quantity_detail.moveUp(gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        move_down: {
          name: "下移",
          icon: "fa-arrow-down",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              var sheetData = gljOprObj.detailData;
              return gljContextMenu.selectedRow > sheetData.length - 2;
            }
            return false;
          },
          callback: function () {
            projectObj.project.quantity_detail.moveDown(gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        copy: {
          name: "复制",
          icon: "fa-files-o",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              let sheet = subSpread.getActiveSheet();
              let sheetData = gljOprObj.detailData;
              let value = sheet.getCell(gljContextMenu.selectedRow, gljContextMenu.selectedCol).value();
              if (gljContextMenu.selectedRow > sheetData.length - 1 || value == null) {
                return true;
              }
              if (gljOprObj.detailSetting.header[gljContextMenu.selectedCol].dataCode == "isSummation") {
                //累加列恢显
                return true;
              }
            }
            return false;
          },
          callback: function () {
            gljContextMenu.clipboard = {
              row: gljContextMenu.selectedRow,
              col: gljContextMenu.selectedCol,
            };
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        paste: {
          name: "粘贴",
          icon: "fa-clipboard",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "quantity_detail") {
              let sheetData = gljOprObj.detailData;
              let dataCode = gljOprObj.detailSetting.header[gljContextMenu.selectedCol].dataCode;
              if (gljContextMenu.selectedRow > sheetData.length || gljContextMenu.clipboard == null) {
                return true;
              }
              //结果列和累加列灰显
              if (dataCode == "result" || dataCode == "isSummation") {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            var sheet = subSpread.getActiveSheet();
            var c = gljContextMenu.clipboard;
            console.log(sheet.getCell(c.row, c.col).value());
            var args = {
              row: gljContextMenu.selectedRow,
              col: gljContextMenu.selectedCol,
              editingText: sheet.getCell(c.row, c.col).value(),
            };
            gljOprObj.onEditDetailSheet(args);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "quantity_detail";
          },
        },
        modify_rule: {
          name: "修改规则",
          icon: "fa-sign-in",
          disabled: function () {
            //当选中空行或者ruleID为空的情况下，灰显
            if (subSpread.getActiveSheet().name() == "rationInstallSheet") {
              let sheetData = installationFeeObj.rationInstallData;
              if (gljContextMenu.selectedRow > sheetData.length - 1) {
                return true;
              }
              let ri = sheetData[gljContextMenu.selectedRow];
              if (!ri.ruleId || ri.ruleId == "") {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            $("#modify_feeRule").modal({ show: true });
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "rationInstallSheet";
          },
        },
        apply_to_FX: {
          name: "应用到当前分项",
          icon: "fa-sign-in",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "rationInstallSheet") {
              let sheetData = installationFeeObj.rationInstallData;
              if (gljContextMenu.selectedRow > sheetData.length - 1) {
                return true;
              }
              if (sheetData[gljContextMenu.selectedRow].unifiedSetting == 1) {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            installationFeeObj.applyRuleTo("FX", gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "rationInstallSheet";
          },
        },
        apply_to_FB: {
          name: "应用到当前分部",
          icon: "fa-sign-in",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "rationInstallSheet") {
              let sheetData = installationFeeObj.rationInstallData;
              if (gljContextMenu.selectedRow > sheetData.length - 1) {
                return true;
              }
              if (sheetData[gljContextMenu.selectedRow].unifiedSetting == 1) {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            installationFeeObj.applyRuleTo("FB", gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "rationInstallSheet";
          },
        },
        apply_to_PRO: {
          name: "应用到当前项目",
          icon: "fa-sign-in",
          disabled: function () {
            if (subSpread.getActiveSheet().name() == "rationInstallSheet") {
              let sheetData = installationFeeObj.rationInstallData;
              if (gljContextMenu.selectedRow > sheetData.length - 1) {
                return true;
              }
              if (sheetData[gljContextMenu.selectedRow].unifiedSetting == 1) {
                return true;
              }
            }
            return false;
          },
          callback: function () {
            installationFeeObj.applyRuleTo("PJ", gljContextMenu.selectedRow);
          },
          visible: function (key, opt) {
            return subSpread.getActiveSheet().name() == "rationInstallSheet";
          },
        },
      },
    });
  },
  onbuild: function ($trigger, e) {
    var target = SheetDataHelper.safeRightClickSelection($trigger, e, subSpread);
    gljContextMenu.selectedRow = target.row;
    gljContextMenu.selectedCol = target.col;
    if (subSpread.getActiveSheet().name() == "ration_glj") {
      gljOprObj.sheetInitSelection({ row: target.row, col: target.col });
    }
    //controller.setTreeSelected(controller.tree.items[target.row]);
    return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
  },
  initGLJSelectView: function () {
    if (gljOprObj.gljLibSpresd == undefined) {
      gljOprObj.gljLibSpresd = sheetCommonObj.buildSheet(
        $("#gljLibSheet")[0],
        gljOprObj.gljLibSheetSetting,
        gljOprObj.stdGLJ.length + gljOprObj.complementaryGLJs.length
      );
      sheetCommonObj.spreadDefaultStyle(gljOprObj.gljLibSpresd);
      gljOprObj.gljLibSpresd.bind(GC.Spread.Sheets.Events.ButtonClicked, gljOprObj.onButtonClick);
      gljOprObj.gljLibSheet = gljOprObj.gljLibSpresd.getSheet(0);
      gljOprObj.gljLibSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, gljOprObj.onSelectionChanged);
      gljOprObj.gljLibSheet.setColumnWidth(0, 20, GC.Spread.Sheets.SheetArea.rowHeader);
      gljOprObj.gljLibSheet.options.isProtected = true;
      gljOprObj.gljLibSheet.name("glj_lib");
    }
    gljOprObj.gljLibSheetData = gljOprObj.AllRecode;
    let gljClass = 0,
      selectMap = {};
    if ($("#actionType").val() == "add" || $("#actionType").val() == "insert" || $("#actionType").val() == "insertEquipment") {
      //插入，添加
      gljOprObj.GLJSelection = [];
    } else if ($("#actionType").val() == "m_replace" || $("#actionType").val() == "replace") {
      //替换、批量替换
      let selected = gljOprObj.sheetData[gljContextMenu.selectedRow];
      let connect_key = gljOprObj.getIndex(selected, gljKeyArray);
      gljOprObj.GLJSelection = [connect_key];
      selectMap[connect_key] = true;
      gljOprObj.filterLibGLJByType();
    } else if ($("#actionType").val() == "addMix" || $("#actionType").val() == "unitPriceAddMix") {
      //添加组成物
      gljOprObj.GLJSelection = [];
      projectGljObject.filterLibGLJForMixRatio();
    }
    for (let item of gljOprObj.gljLibSheetData) {
      let item_key = gljOprObj.getIndex(item, gljLibKeyArray);
      if (selectMap[item_key]) {
        item.select = 1;
        gljClass = item.gljClass;
      } else {
        item.select = 0;
      }
    }
    //替换，焦点定位至当前选中人材机
    if ($("#actionType").val() == "m_replace" || $("#actionType").val() == "replace") {
      gljOprObj.locateZTree(gljClass);
      let selected = gljOprObj.sheetData[gljContextMenu.selectedRow];
      let index = _.findIndex(gljOprObj.gljLibSheetData, { code: selected.code });
      gljOprObj.gljLibSheet.showRow(index, GC.Spread.Sheets.VerticalPosition.center);
      gljOprObj.gljLibSheet.setActiveCell(index, 0);
      gljOprObj.initSelection({ row: index });
      gljOprObj.gljLibSpresd.focus(true);
    } else if ($("#actionType").val() === "insertEquipment") {
      //右键插入设备，人材机选择窗口，应默认固定到分类"养护管理设备"。
      let locateClass = gljOprObj.treeData.std.find(function (stdClass) {
        return stdClass.Name === "养护管理设备";
      });
      if (locateClass) {
        gljClass = locateClass.ID;
        gljOprObj.locateZTree(gljClass);
        gljOprObj.gljLibSheet.showRow(0, GC.Spread.Sheets.VerticalPosition.top);
        gljOprObj.gljLibSheet.setActiveCell(0, 0);
        gljOprObj.initSelection({ row: 0 });
      }
    } else if ($("#actionType").val() === "add") {
      gljOprObj.locateZTree(null);
      gljOprObj.gljLibSheet.showRow(0, GC.Spread.Sheets.VerticalPosition.top);
      gljOprObj.gljLibSheet.setActiveCell(0, 0);
      gljOprObj.initSelection({ row: 0 });
    } else {
      gljOprObj.showLibGLJSheetData();
    }
  },
};

function initLibOptions(libData) {
  const html = libData.reduce((acc, lib) => (acc += `<option ${lib.isDefault ? 'selected="selected"' : ""} value="${lib.gljLibId}">${lib.name}</option>`), "");
  $("#glj-lib-select").html(html);
}

function getActionUrl(actionType) {
  const rootUrl = `/rationGlj/getGLJData/${commonConstants.COMPILATION}`;
  switch (actionType) {
    case "add":
    case "addMix":
    case "insert":
    case "unitPriceAddMix":
    case "insertEquipment":
      return `${rootUrl}/0/true`;
    case "replace":
    case "m_replace":
      const selected = gljOprObj.sheetData[gljContextMenu.selectedRow];
      const cptLibID = selected.fromUser ? `${commonConstants.COMPLEMENTARY_LIB}*${selected.fromUser}` : commonConstants.COMPLEMENTARY_LIB;
      const gljLibId = selected.repositoryId || cptLibID;
      return `${rootUrl}/${gljLibId}/true`;
    case "change": // 更改选择库
      const selectGLJLibID = $("#glj-lib-select").val();
      return `${rootUrl}/${selectGLJLibID}/false`;
  }
}

function getGLJData(actionType, isInitial = true, getLibFunc) {
  const url = getActionUrl(actionType);
  if (actionType === "change") {
    actionType = $("#actionType").val();
  }
  $("#actionType").val(actionType);
  $.bootstrapLoading.start();
  if (!getLibFunc) getLibFunc = projectObj.project.ration_glj.getGLJData;
  getLibFunc(url, function (result) {
    // 目前只有浙江2015 湖南 - 山东 需要特殊处理处理
    if (gljOprObj.sortSelectViewGLJ) {
      gljOprObj.sortSelectViewGLJ(result.datas.stdGLJ);
      gljOprObj.sortSelectViewGLJ(result.datas.complementaryGLJs);
    } else {
      result.datas.stdGLJ = _.sortBy(result.datas.stdGLJ, "code");
      result.datas.complementaryGLJs = _.sortBy(result.datas.complementaryGLJs, "code");
    }
    gljOprObj.stdGLJ = result.datas.stdGLJ;
    gljOprObj.complementaryGLJs = result.datas.complementaryGLJs;
    for (let compleGlj of gljOprObj.complementaryGLJs) {
      //是否新增
      compleGlj.isComplementary = true;
    }
    gljOprObj.AllRecode = gljOprObj.stdGLJ.concat(gljOprObj.complementaryGLJs);
    //gljOprObj.AllRecode=gljOprObj.stdGLJ;
    gljOprObj.distTypeTree = gljOprObj.getComboData(result.datas.distTypeTree);
    gljOprObj.treeData = result.datas.treeData;
    if (gljOprObj.treeData.std.length) {
      gljOprObj.initClassTree("std", gljOprObj.treeData.std, !isInitial);
    } else if (gljOprObj.treeData.comple.length) {
      gljOprObj.initClassTree("comple", gljOprObj.treeData.comple, !isInitial);
    }
    if (isInitial) {
      initLibOptions(result.datas.libData);
      $("#modalCon").width($(window).width() * 0.5);
      if (actionType == "m_replace") {
        $("#glj_selected_conf").hide();
        $("#replace_next_btn").show();
      } else {
        $("#glj_selected_conf").show();
        $("#replace_next_btn").hide();
      }
      $("#glj_tree_div").modal({ show: true });
      setTimeout(function () {
        gljOprObj.gljLibSpresd ? gljOprObj.gljLibSpresd.refresh() : "";
      }, 200);
    } else {
      gljContextMenu.initGLJSelectView();
    }
    $.bootstrapLoading.end();
  });
}

function showGLJClassTree(record) {
  let engineerID = projectObj.project.projectInfo.property.engineering_id;
  CommonAjax.post("/rationGlj/getGLJClass/" + engineerID, record, function (data) {
    if (data.exist == true) {
      alert("当前人材机已存在。");
    } else {
      gljOprObj.selectedGLJClass = record;
      $("#glj_class_div").modal({ show: true });
      zTreeHelper.createTree(data.items, gljOprObj.gljTreeSetting, "classTree", gljOprObj);
    }
  });
}
