// 推荐相似材料
const RECOMMEND_BOOK = (() => {
  const setting = {
    header: [
      { headerName: '主从对应码', headerWidth: 100, dataCode: 'code', dataType: 'String', hAlign: 'left', vAlign: 'center', formatter: "@" },
      { headerName: '别名编码', headerWidth: 70, dataCode: 'classCode', dataType: 'String', hAlign: 'left', vAlign: 'center', formatter: "@" },
      { headerName: '计算式', headerWidth: 100, dataCode: 'expString', dataType: 'String', hAlign: 'left', vAlign: 'center' },
      { headerName: '材料名称', headerWidth: 275, dataCode: 'name', dataType: 'String', hAlign: 'left', vAlign: 'center' },
      { headerName: '规格型号', headerWidth: 180, dataCode: 'specs', dataType: 'String', hAlign: 'left', vAlign: 'center' },
      { headerName: '单位', headerWidth: 80, dataCode: 'unit', dataType: 'String', hAlign: 'center', vAlign: 'center' },
    ],
  };
  // 初始化表格
  // 初始化表格
  const workBookObj = {
    book: null,
    sheet: null,
  };
  const buildWorkBook = () => {
    workBookObj.book = initSheet($('.recommend-spread')[0], setting);
    workBookObj.book.options.allowUserDragDrop = true;
    workBookObj.book.options.allowUserDragFill = true;
    workBookObj.book.options.allowExtendPasteRange = false;
    lockUtil.lockSpreads([workBookObj.book], true);
    workBookObj.sheet = workBookObj.book.getSheet(0);
  }

  // 表格显示的数据
  const cache = [];

  // 清空
  function clear() {
    cache.length = 0;
    workBookObj.sheet.setRowCount(0);
  }
  // 初始化数据
  async function loadRecommendData(keyword) {
    clear();
    $.bootstrapLoading.start();
    try {
      const items = await ajaxPost('/priceInfo/getRecommendPriceSummaryData', { keyword }, 1000 * 60 * 5);
      cache.push(...items);
      showData(workBookObj.sheet, cache, setting.header);
    } catch (err) {
      clear();
      alert(err);
    } finally {
      $.bootstrapLoading.end();
    }
  }

  // 双击更新空表编码和别名编码
  const handleDbClick = (sender, args) => {
    const item = cache[args.row];
    if (item) {
      // 只有珠海才更新计算式
      //const expString = /珠海/.test(AREA_BOOK.curArea.name || '') ? item.expString : undefined;
      EMPTY_BOOK.updateRowCode(item.code || '', item.classCode || '', item.expString || '');
    }
  }

  const bindEvent = () => {
    workBookObj.book.bind(GC.Spread.Sheets.Events.CellDoubleClick, handleDbClick)
  }


  return {
    buildWorkBook,
    bindEvent,
    clear,
    loadRecommendData,
    workBookObj,
  }
})();

$(document).ready(() => {
  $('#empty-area').on('shown.bs.modal', function () {
    // 生成表格
    if (!RECOMMEND_BOOK.workBookObj.book) {
      RECOMMEND_BOOK.buildWorkBook();
      RECOMMEND_BOOK.bindEvent();
    }
  });

  $('#empty-area').on('hidden.bs.modal', function () {
    RECOMMEND_BOOK.clear();
  });

  // 回车搜索分词
  $('#recommend-search').bind('keydown', function (event) {
    if (event.keyCode === 13) {
      const searchStr = $(this).val();
      RECOMMEND_BOOK.loadRecommendData(searchStr);
    }
  })
});