import Handsontable from '@sc/handsontable';
import useVerticalScroll from './useVerticalScroll';
import useGroupingHeaders from './useGroupingHeaders';

export default function useInstance(tableWrapper: HTMLElement, settings: any) {
  
  // 注册垂直滚动监听器（用于大数据量快速滚动导致错位的问题：停止后，手动触发滚动1px）
  const { registerVerticalScroll } = useVerticalScroll(tableWrapper);
  if (settings.cellGrid) {
    settings.viewportColumnRenderingOffset = Number.MAX_SAFE_INTEGER;
  }

  return new Handsontable(tableWrapper, {
    rowHeaders: true,
    manualColumnResize: true,
    manualRowResize: true,
    currentRowClassName: 'current-row',
    // currentColClassName: 'current-col',
    // 水平垂直居中，默认单行
    className: 'htCenter htMiddle wcSingleLine',
    renderAllRows: false,
    autoColumnSize: false, // 提升性能
    autoRowSize: false,

    // 视口之外预渲染 1 行 此处设为 0 会导致树结构展开收起失效
    viewportRowRenderingOffset: 30,
    // 视口之外预渲染 1 列 此处设为 0 会导致树结构展开收起失效
    viewportColumnRenderingOffset: 2,

    selectionMode: 'range',
    /*  rowHeights: 23, */
    outsideClickDeselects: false, // 点击其它位置或表格，不清空表格的选中状态
    afterRender() {
      // if (settings.fixedColumnsLeft) registerFixedLeftScroll();
      if (settings.cellGrid) {
        const { generateGroupHeaders } = useGroupingHeaders(tableWrapper, settings.cellGrid, settings.fixedColumnsLeft);
        generateGroupHeaders();
      }
      // registerHover();
      registerVerticalScroll();
    },
    ...settings,
  });
}
