let lossObj = {
  workBook: null,
  workSheet: null,
  currentLossList: [],
  currentLoss: null,
  currentMaxNo: null,
  setting: {
    header: [
      { headerName: "编号", headerWidth: 50, dataCode: "serialNo", dataType: "String", hAlign: "center", vAlign: "center", readOnly: false },
      { headerName: "名称", headerWidth: 200, dataCode: "name", dataType: "String", hAlign: "left", vAlign: "center", readOnly: false },
      { headerName: "损耗率", headerWidth: 150, dataCode: "rate", dataType: "Number", hAlign: "right", vAlign: "center", readOnly: false },
    ]
  },
  buildSheet: function (container) {
    let me = lossObj;
    me.workBook = sheetCommonObj.buildSheet(container, me.setting, 30);
    sheetCommonObj.bindEscKey(me.workBook, [{ sheet: me.workBook.getSheet(0), editStarting: null, editEnded: me.onEditEnded }]);
    me.workSheet = me.workBook.getSheet(0);
    me.workSheet.options.isProtected = true;
    me.onDelOpr(me.workBook, me.setting);
    me.workSheet.bind(GC.Spread.Sheets.Events.SelectionChanged, me.onSelectionChanged);
    me.workSheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
    me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
    me.workBook.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
  },
  onSelectionChanged: function (sender, info) {
    if (info.oldSelections.length === 0 && info.newSelections.length > 0 || info.oldSelections[0].row !== info.newSelections[0].row) {
      const row = info.newSelections[0].row;
      lossObj.lossSelInit(row);
    }
  },
  lossSelInit: function (row) {
    const me = lossObj;
    if (row < me.currentLossList.length) {
      me.currentLoss = me.currentLossList[row];
    } else {
      me.currentLoss = null;
    }
  },
  onEditEnded: function (sender, args) {
    let me = lossObj, addArr = [], updateArr = [], dataCode = me.setting.header[args.col].dataCode;
    if (args.editingText && args.editingText.toString().trim().length > 0) {
      let inputT = args.editingText.toString().trim();
      //update
      if (args.row < me.currentLossList.length) {
        let updateObj = me.currentLossList[args.row];
        if (updateObj[dataCode] != inputT) {
          if (dataCode === 'serialNo') {
            if (me.isInt(inputT) && !me.hasTisNo(me.currentLossList, inputT)) {
              me.currentMaxNo = me.currentMaxNo >= inputT ? me.currentMaxNo : inputT;
              updateObj[dataCode] = inputT;
              updateArr.push(updateObj);
              me.save([], updateArr, [], true);
            }
            else if (!me.isInt(inputT)) {
              alert('编号只能为整数！');
              args.sheet.setValue(args.row, args.col, updateObj[dataCode] + '');
            }
            else if (me.hasTisNo(me.currentLossList, inputT)) {
              alert('该编号已存在！');
              args.sheet.setValue(args.row, args.col, updateObj[dataCode] + '');
            }
          } else if (dataCode === 'rate' && isNaN(inputT)) {
            alert('损耗率只能为数值！');
            args.sheet.setValue(args.row, args.col, updateObj[dataCode] || '');
          }
          else {
            updateObj[dataCode] = inputT;
            updateArr.push(updateObj);
            me.save([], updateArr, [], true);
          }
        }
      }
      //insert
      else {
        let newLoss = {};
        newLoss.libID = pageOprObj.rationLibId;
        if (dataCode === 'serialNo') {
          if (me.isInt(inputT) && !me.hasTisNo(me.currentLossList, inputT)) {
            me.currentMaxNo = me.currentMaxNo >= inputT ? me.currentMaxNo : inputT;
            newLoss[dataCode] = inputT;
            addArr.push(newLoss);
            me.save(addArr, [], [], true, function (result) {
              me.updateCurrentLossList(result);
            });
          }
          else if (!me.isInt(inputT)) {
            args.sheet.setValue(args.row, args.col, '');
            alert('编号只能为整数！');
          }
          else if (me.hasTisNo(me.currentLossList, inputT)) {
            args.sheet.setValue(args.row, args.col, '');
            alert('该编号已存在！');
          }
        }
        else if (dataCode === 'rate' && isNaN(inputT)) {
          args.sheet.setValue(args.row, args.col, updateObj[dataCode] + '');
          alert('损耗率只能为数值！');
        }
        else {
          newLoss.serialNo = ++me.currentMaxNo;
          newLoss[dataCode] = inputT;
          addArr.push(newLoss);
          me.save(addArr, [], [], true, function (result) {
            me.updateCurrentLossList(result);
          });
        }
      }
    }
  },
  onClipboardPasting: function (sender, info) {
    let me = lossObj, maxCol = info.cellRange.col + info.cellRange.colCount - 1;
    if (maxCol > me.setting.header.length) {
      info.cancel = true;
    }
  },
  onClipboardPasted: function (sender, info) {
    debugger;
    let me = lossObj, addArr = [], updateArr = [];
    let items = sheetCommonObj.analyzePasteData(me.setting, info);
    let uniqItems = me.makeUniqItems(items);
    for (let i = 0, len = uniqItems.length; i < len; i++) {
      let row = i + info.cellRange.row;
      //update
      if (row < me.currentLossList.length) {
        let updateObj = me.currentLossList[row];
        for (let attr in uniqItems[i]) {
          if (attr === 'serialNo') {
            if (me.isInt(uniqItems[i][attr]) && !me.hasTisNo(me.currentLossList, uniqItems[i][attr])) {
              me.currentMaxNo = me.currentMaxNo >= uniqItems[i][attr] ? me.currentMaxNo : uniqItems[i][attr];
              updateObj[attr] = uniqItems[i][attr];
            }
          }
          else if (attr !== 'rate' || !isNaN(uniqItems[i][attr])) {
            updateObj[attr] = uniqItems[i][attr];
          }
        }
        updateArr.push(updateObj);
      }
      //insert
      else {
        if (typeof uniqItems[i].serialNo !== 'undefined' && uniqItems[i] && me.isInt(uniqItems[i].serialNo) && !me.hasTisNo(me.currentLossList, uniqItems[i].serialNo)) {
          me.currentMaxNo = me.currentMaxNo >= uniqItems[i].serialNo ? me.currentMaxNo : uniqItems[i].serialNo;
        }
        else {
          uniqItems[i].serialNo = ++me.currentMaxNo;
        }
        if (typeof uniqItems[i].rate !== 'undefined' && isNaN(uniqItems[i].rate)) {
          delete uniqItems[i].rate;
        }
        uniqItems[i].libID = pageOprObj.rationLibId;
        addArr.push(uniqItems[i]);
      }
    }
    if (addArr.length > 0 || updateArr.length > 0) {
      me.save(addArr, updateArr, [], true, function (result) {
        me.updateCurrentLossList(result);
      });
    }
  },
  onDelOpr: function (workBook, setting) {
    let me = lossObj;
    workBook.commandManager().register('coeListDel', function () {
      let deleteArr = [];
      let sheet = workBook.getSheet(0);
      let sels = sheet.getSelections();
      let idx = sels[0].row;
      for (let i = 0, len = sels.length; i < len; i++) {
        if (idx > sels[i].row) {
          idx = sels[i].row;
        }
        if (sels[i].colCount === setting.header.length) {//can del
          for (let r = 0, rLen = sels[i].rowCount; r < rLen; r++) {
            let row = sels[i].row + r;
            if (row < me.currentLossList.length) {
              deleteArr.push({ libID: me.currentLossList[row].libID, ID: me.currentLossList[row].ID });
            }
          }
          me.currentLossList.splice(sels[i].row, sels[i].rowCount);
        }
      }
      if (deleteArr.length > 0) {
        me.save([], [], deleteArr, true);
        me.currentLoss = typeof me.currentLossList[idx] !== 'undefined' ? me.currentLossList[idx] : null;
      }

    });
    workBook.commandManager().setShortcutKey(null, GC.Spread.Commands.Key.del, false, false, false, false);
    workBook.commandManager().setShortcutKey('coeListDel', GC.Spread.Commands.Key.del, false, false, false, false);
  },
  //粘贴的数据，编号唯一化，去除编号重复的项
  makeUniqItems: function (items) {
    let rst = [];
    for (let i = 0, len = items.length; i < len; i++) {
      if (typeof items[i].serialNo !== 'undefined' && items[i].serialNo) {
        if (rst.length === 0) {
          rst.push(items[i]);
        }
        else {
          let isExist = false;
          for (let j = 0, jLen = rst.length; j < jLen; j++) {
            if (items[i].serialNo === rst[j].serialNo) {
              isExist = true;
              break;
            }
          }
          if (!isExist) {
            rst.push(items[i]);
          }
        }
      }
      else {
        rst.push(items[i]);
      }
    }
    return rst;
  },
  isInt: function (num) {
    return !isNaN(num) && num % 1 === 0;
  },
  hasTisNo: function (lossList, newSerialNo) {
    let rst = false;
    for (let i = 0, len = lossList.length; i < len; i++) {
      if (lossList[i].serialNo == newSerialNo) {
        rst = true;
        break;
      }
    }
    return rst;
  },
  updateCurrentLossList: function (newCoeList) {
    let me = lossObj;
    if (newCoeList) {
      me.currentLossList = me.currentLossList.concat(newCoeList);
    }
  },
  sortLossList: function (lossList) {
    lossList.sort(function (a, b) {
      let rst = 0;
      if (a.serialNo > b.serialNo) rst = 1;
      else if (a.serialNo < b.serialNo) rst = -1;
      return rst;
    });
  },
  getLossList: function () {
    let me = lossObj;
    $.ajax({
      type: 'post',
      url: '/rationRepository/api/getLossList',
      data: { libID: pageOprObj.rationLibId },
      dataType: 'json',
      timeout: 20000,
      success: function (result) {
        if (!result.error) {
          me.currentLossList = result.data;
          me.sortLossList(me.currentLossList);
          me.currentMaxNo = me.currentLossList.length > 0 ? me.currentLossList[me.currentLossList.length - 1].serialNo : 0;
          pageObj.showData(me.workSheet, me.setting, me.currentLossList);
          me.workSheet.clearSelection();
        }
      },
      error: function (err) {
        alert("内部程序错误！");
      }
    });
  },
  updateRationGljs: function (updateMap, rationGljs) {
    if (!rationGljs || !rationGljs.length) {
      return;
    }
    rationGljs.forEach(glj => {
      const match = updateMap[glj.lossRateID];
      if (match) {
        glj.lossRateNo = match.serialNo;
        glj.lossRateName = match.name;
        glj.lossRate = match.rate;
      }
    })
  },
  updateRationAndGljCache: function (updateRateData) {
    debugger;
    const updateMap = {};
    updateRateData.forEach(item => {
      updateMap[item.ID] = item;
    });
    const rations = Object.values(rationOprObj.currentRations).flat();
    rations.forEach(ration => {
      lossObj.updateRationGljs(updateMap, ration.rationGljList);
    })
    const rGljList = Object.values(rationGLJOprObj.cache).flat();
    lossObj.updateRationGljs(updateMap, rGljList);
    if (rationGLJOprObj.currentRationItem) {
      rationGLJOprObj.showGljItems(rationGLJOprObj.currentRationItem.ID);
    }
  },
  save: function (addArr, updateArr, deleteArr, refresh, callback) {
    let me = lossObj;
    $.ajax({
      type: "POST",
      url: "api/saveLossList",
      data: { data: JSON.stringify({ addArr: addArr, updateArr: updateArr, deleteArr: deleteArr }) },
      dataType: "json",
      timeout: 5000,
      success: function (result) {
        if (result.error) {
          alert(result.message);
        } else {
          debugger;
          if (updateArr && updateArr.length) {
            lossObj.updateRationAndGljCache(updateArr);
          }
          if (callback) {
            callback(result.data);
          }
          if (refresh) {
            me.sortLossList(me.currentLossList);
            me.currentMaxNo = me.currentLossList.length > 0 ? me.currentLossList[me.currentLossList.length - 1].serialNo : 0;
            pageObj.showData(me.workSheet, me.setting, me.currentLossList);
          }
        }
      },
      error: function (err) {
        alert("内部程序错误！");
      }
    });
  }
}

$(document).ready(function () {
  //设置水平拖动条的宽度
  //@param {Object dom}resize滚动条
  function setResizeWidth(resize) {
    const fixedWidth = 10;
    //跟滚动条同层的其他节点
    let bros = resize.parent().children();
    //滚动条节点 及 同层非滚动条节点的索引
    let index = bros.index(resize),
      otherIndex = index ? 0 : 2;
    const other = resize.parent().children(`:eq(${otherIndex})`);
    let resizeParentWidth = resize.parent().width();
    let resizeDecimalWidth = fixedWidth / resizeParentWidth,
      otherDecimalWidth = 1 - resizeDecimalWidth;
    let resizePercentWidth = resizeDecimalWidth * 100 + '%',
      otherPercentWidth = otherDecimalWidth * 100 + '%';
    resize.css('width', resizePercentWidth);
    other.css('width', otherPercentWidth);
  }
  function refreshAfterShow(visible) {
    const min = 20;
    //宽度比例localstorage key
    let leftContentKey = `${moduleName}${$('#leftContent').attr('id')}Width`,
      mainContentKey = `${moduleName}${$('#mainContent').attr('id')}Width`,
      lossContentKey = `${moduleName}${$('#rightContent').attr('id')}Width`;
    let lossWidth = getLocalCache(lossContentKey) ? getLocalCache(lossContentKey) : $('#rightContent')[0].style.width,
      mainContentWidth = $('#mainContent')[0].style.width,
      leftContentWidth;
    lossWidth = parseFloat(lossWidth.replace('%', ''));
    mainContentWidth = parseFloat(mainContentWidth.replace('%', ''));
    if (visible) {
      mainContentWidth = mainContentWidth - lossWidth / 2 < min ? min : mainContentWidth - lossWidth / 2;
      if (100 - mainContentWidth - lossWidth < min) {
        leftContentWidth = min;
        lossWidth = 100 - mainContentWidth - leftContentWidth;
      } else {
        leftContentWidth = 100 - mainContentWidth - lossWidth;
      }
    } else {
      mainContentWidth += lossWidth / 2;
      leftContentWidth = 100 - mainContentWidth;
    }
    $('#leftContent').css('width', `${leftContentWidth}%`);
    setLocalCache(leftContentKey, `${leftContentWidth}%`);
    $('#mainContent').css('width', `${mainContentWidth}%`);
    setLocalCache(mainContentKey, `${mainContentWidth}%`);
    $('#rightContent').css('width', `${lossWidth}%`);
    setLocalCache(lossContentKey, `${lossWidth}%`);
    let resizes = [$('#slideResizeLeft'), $('#slideResizeRight')];
    for (let resize of resizes) {
      setResizeWidth(resize);
    }
    sectionTreeObj.loadRateWidth();
  }
  $('#loss').click(function () {
    if (!$(this).hasClass('active')) {
      $('#zmhs').removeClass('active');
      $(this).addClass('active');
      refreshAfterShow(true);
      $('#lossWrap').show();
      $('#zmhsWrap').hide();
      $('#rightContent').show();
      if (!lossObj.workBook) {
        pageObj.initPage();
      }
      refreshALlWorkBook();
    } else {
      $(this).removeClass('active');
      refreshAfterShow(false);
      $('#rightContent').hide();
      $('#zmhsWrap').hide();
      $('#lossWrap').hide();
      refreshALlWorkBook();
    }
  });

  var pageObj = {
    initPage: function () {
      lossObj.buildSheet($('#lossSpread')[0]);
      lossObj.getLossList();
      lockUtil.lockSpreads([lossObj.workBook], locked);
    },
    showData: function (sheet, setting, data) {
      let me = pageObj, ch = GC.Spread.Sheets.SheetArea.viewport;
      sheet.suspendPaint();
      sheet.suspendEvent();
      sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount(), GC.Spread.Sheets.SheetArea.viewport, GC.Spread.Sheets.StorageType.data);
      sheet.setRowCount(data.length + 3);
      for (let col = 0; col < setting.header.length; col++) {
        var hAlign = "left", vAlign = "center";
        if (setting.header[col].hAlign) {
          hAlign = setting.header[col].hAlign;
        } else if (setting.header[col].dataType !== "String") {
          hAlign = "right";
        }
        if (setting.header[col].readOnly) {
          sheet.getRange(-1, col, -1, 1).locked(true);
        }
        else {
          sheet.getRange(-1, col, -1, 1).locked(false);
        }
        vAlign = setting.header[col].vAlign ? setting.header[col].vAlign : vAlign;
        sheetCommonObj.setAreaAlign(sheet.getRange(-1, col, -1, 1), hAlign, vAlign);
        if (setting.header[col].formatter) {
          sheet.setFormatter(-1, col, setting.header[col].formatter, GC.Spread.Sheets.SheetArea.viewport);
        }
        for (let row = 0; row < data.length; row++) {
          let val = data[row][setting.header[col].dataCode];
          sheet.setValue(row, col, val, ch);
        }
      }
      sheet.resumeEvent();
      sheet.resumePaint();
    }
  };
});