import Handsontable, { GridSettings, cellTypes } from '@sc/handsontable';

import { hover, parse, empty } from '@/utils/frontend/dom';
import { TreeNode } from '@sc/tree';
import { bindPopover } from '@/components/popover/composables/usePopover';

type callback = (...args: any) => string;

export default function getPopoverRenderer(callback: callback) {
  const popoverRender = (
    instance: Handsontable,
    td: HTMLElement,
    row: number,
    col: number,
    prop: string | number,
    value: any,
    cellProperties: GridSettings
  ): HTMLElement => {
    cellTypes.text.renderer(instance, td, row, col, prop, value, cellProperties);
    // 当前行的源数据
    empty(td); // 先清空数据，多次刷新时会出现两行的问题
    const rowSourceData = instance.getSourceDataAtRow(row) as TreeNode;
    const template = `<div>${value}</div>`;
    const container = parse(template) as HTMLElement;
    if (td.childNodes[0]) {
      td.removeChild(td.childNodes[0]);
    }
    if (value) {
      td.appendChild(container);
    }
    const content = callback(rowSourceData, td);

    if (content && value) bindPopover(td, container, content);

    return td;
  };
  return popoverRender;
}
