// 地区表
const AREA_BOOK = (() => {
  const cache = areaList;
  const setting = {
    header: [
      { headerName: '序号', headerWidth: 60, dataCode: 'serialNo', dataType: 'Number', hAlign: 'center', vAlign: 'center' },
      { headerName: '地区', headerWidth: $('#area-spread').width() - 80, dataCode: 'name', dataType: 'String', hAlign: 'center', vAlign: 'center' },
    ]
  };
  // 初始化表格
  const workBook = initSheet($('#area-spread')[0], setting);
  lockUtil.lockSpreads([workBook], locked);
  workBook.options.allowExtendPasteRange = false;
  workBook.options.allowUserDragDrop = true;
  workBook.options.allowUserDragFill = true;
  const sheet = workBook.getSheet(0);

  // 排序显示
  cache.sort((a, b) => a.serialNo - b.serialNo);

  // 显示数据
  showData(sheet, cache, setting.header);

  // 编辑处理
  async function handleEdit(changedCells) {
    const updateData = [];
    let reSort = false;
    changedCells.forEach(({ row, col }) => {
      const field = setting.header[col].dataCode;
      let value = sheet.getValue(row, col);
      if (field === 'serialNo') {
        reSort = true;
        value = +value;
      }
      updateData.push({
        row,
        field,
        value,
        ID: cache[row].ID,
      });
    });
    try {
      await ajaxPost('/priceInfo/editArea', { updateData }, TIME_OUT);
      updateData.forEach(({ row, field, value }) => cache[row][field] = value);
      if (reSort) {
        cache.sort((a, b) => a.serialNo - b.serialNo);
        showData(sheet, cache, setting.header);
      }
    } catch (err) {
      // 恢复各单元格数据
      sheetCommonObj.renderSheetFunc(sheet, () => {
        changedCells.forEach(({ row, col, field }) => {
          sheet.setValue(row, col, cache[row][field]);
        });
      });
    }
  }
  sheet.bind(GC.Spread.Sheets.Events.ValueChanged, function (e, info) {
    const changedCells = [{ row: info.row, col: info.col }];
    handleEdit(changedCells);
  });
  sheet.bind(GC.Spread.Sheets.Events.RangeChanged, function (e, info) {
    handleEdit(info.changedCells);
  });

  const curArea = { ID: null, name: '' };
  // 焦点变更处理
  const debounceSelectionChanged = _.debounce(function (e, info) {
    const row = info.newSelections && info.newSelections[0] ? info.newSelections[0].row : 0;
    handleSelectionChanged(row);
  }, DEBOUNCE_TIME, { leading: true }); // leading = true : 先触发再延迟
  function handleSelectionChanged(row) {
    const areaItem = cache[row];
    curArea.ID = areaItem && areaItem.ID || null;
    curArea.name = areaItem && areaItem.name || '';
    CLASS_BOOK.initData(libID, curArea.ID);
  }
  sheet.bind(GC.Spread.Sheets.Events.SelectionChanged, debounceSelectionChanged);

  // 新增
  async function insert() {
    const data = {
      compilationID,
      ID: uuid.v1(),
      name: '',
    };
    try {
      $.bootstrapLoading.start();
      await ajaxPost('/priceInfo/insertArea', { insertData: [data] });
      // 新增的数据总是添加在最后
      sheet.addRows(cache.length, 1);
      cache.push(data);
      const lastRow = cache.length - 1;
      sheet.setSelection(lastRow, 0, 1, 1);
      sheet.showRow(lastRow, GC.Spread.Sheets.VerticalPosition.top);
      handleSelectionChanged(lastRow);
    } catch (err) {
      alert(err);
    } finally {
      $.bootstrapLoading.end();
    }
  }

  // 删除
  async function del() {
    try {
      $.bootstrapLoading.start();
      await ajaxPost('/priceInfo/deleteArea', { deleteData: [curArea.ID] });
      const index = cache.findIndex(item => item.ID === curArea.ID);
      sheet.deleteRows(index, 1);
      cache.splice(index, 1);
      const row = sheet.getActiveRowIndex();
      handleSelectionChanged(row);
    } catch (err) {
      alert(err);
    } finally {
      $.bootstrapLoading.end();
    }
  }

  // 右键功能
  function buildContextMenu() {
    $.contextMenu({
      selector: '#area-spread',
      build: function ($triggerElement, e) {
        // 控制允许右键菜单在哪个位置出现
        const offset = $('#area-spread').offset();
        const x = e.pageX - offset.left;
        const y = e.pageY - offset.top;
        const target = sheet.hitTest(x, y);
        if (target.hitTestType === 3) { // 在表格内
          const sel = sheet.getSelections()[0];
          if (sel && sel.rowCount === 1 && typeof target.row !== 'undefined') {
            const orgRow = sheet.getActiveRowIndex();
            if (orgRow !== target.row) {
              sheet.setActiveCell(target.row, target.col);
              handleSelectionChanged(target.row);
            }
          }
          return {
            items: {
              insert: {
                name: '新增',
                icon: "fa-arrow-left",
                disabled: function () {
                  return locked;
                },
                callback: function (key, opt) {
                  insert();
                }
              },
              del: {
                name: '删除',
                icon: "fa-arrow-left",
                disabled: function () {
                  return locked || !cache[target.row];
                },
                callback: function (key, opt) {
                  del();
                }
              },
            }
          };
        }
        else {
          return false;
        }
      }
    });
  }
  buildContextMenu();

  return {
    handleSelectionChanged,
    curArea,
    cache,
  }

})();