import { Hot } from '@/types/components';
import { on, parse, query, style } from '@/utils/frontend/dom';

type Callback = (...args: any) => void;
type GetValue = (...args: any) => any;
export default function getButtonRender(callback: Callback, getValue?: GetValue) {
  const buttonRender = (
    instance: Handsontable,
    td: HTMLElement,
    row: number,
    col: number,
    prop: string | number,
    value: any,
    cellProperties: Hot.IColumnMeta
  ): void => {
    const data: any = instance.getSourceDataAtRow(row);
    const className = (cellProperties.className as string) || 'htRight htMiddle wcSingleLine';
    value = getValue ? getValue(data) : value;
    if (cellProperties.readOnly && cellProperties.showButton !== true) {
      td.innerHTML = `${value || ''}`;
    } else {
      td.innerHTML = '';

      const div = parse(`<div class="${className}">${value || ''}</div>`) as HTMLElement;
      const button = parse(
        `<button class="custom-button el-button el-button--primary is-circle "> <i class="iconfont dsk-more" style="font-size:14px"></i></button>`
      ) as HTMLElement;

      let transX = 3;
      const transY = value ? -3 : -12;
      if (cellProperties.className && typeof cellProperties.className === 'string') {
        if (cellProperties.className.indexOf('htLeft') !== -1) transX = instance.getColWidth(col) - 5; // 默认右对齐，左对齐时要调整偏移量
        if (cellProperties.className.indexOf('htCenter') !== -1) transX = instance.getColWidth(col) / 2 - 3; // 居中对齐，偏移一半
      }
      style(button, { transform: `translate(${transX}px,${transY}px`, position: 'absolute' });

      td.appendChild(button);
      td.appendChild(div);

      on(button, 'click', () => callback(data, instance));

      // 双击进入编辑状态时，hot用一个输入框覆盖在TD上面，这时候button还是显示状态，要手动移除（不能用display node, button本身是隐藏的，通过 &.current选中状态时显示的）
      if (!cellProperties.readOnly) on(div, 'dblclick', () => td.removeChild(button)); // 对于只读的单元格，双击不移除按钮

      // 如果被 上一个 'dblclick' 事件进入编辑状态执行了移除按钮操作，在单元格内容不改变的情况下退出编辑状态，这时候单元格不会重新render，所以要把被移除的button添加回来
      on(div, 'click', () => {
        const tem = query(td, 'custom-button');
        if (!tem) td.insertBefore(button, div);
      });
    }

    td.className = className;
  };
  return buttonRender;
}
