import {DragMoveEvent} from '@dnd-kit/core';
import {
  createColumnHelper,
  useReactTable,
  getCoreRowModel,
} from '@tanstack/react-table';
import {ColumnType} from 'antd/es/table';
import {useRef, useState} from 'react';

function parseColumn<T>(columns: ColumnType<T>[]) {
  const hepler = createColumnHelper<Record<string, any>>();

  const tableColumns = columns.map(function (val) {
    const {dataIndex, title, render, align} = val;
    if (render) {
      return hepler.display({
        id: dataIndex?.toString() ?? 'id',
        header: title?.toString(),
        cell(props) {
          return render(
            props.getValue(),
            props.row.original as T,
            props.row.index,
          );
        },
        meta: {align},
      });
    }

    return hepler.accessor(dataIndex!.toString(), {
      header: title?.toString(),
      cell: props => props.getValue(),
      minSize: 0,
      meta: {align},
    });
  });

  tableColumns.unshift(
    hepler.display({
      header: '序号',
      id: 'no',
      cell({row}) {
        return row.index;
      },
      meta: {align: 'center'},
    }),
  );

  return tableColumns;
}

export function useTable<T extends Record<string, any>>(
  columns: ColumnType<T>[],
  data: T[],
) {
  const columnList = useRef(parseColumn(columns));

  const [columnSizing, setColumnSizing] = useState(function () {
    const obj: Record<string, number> = {no: 64};

    columns.forEach(function ({dataIndex, width}) {
      if (dataIndex && width) {
        obj[dataIndex.toString()] = Number(width);
      }
    });

    return obj;
  });

  const [columnOrder, setColumnOrder] = useState(function () {
    const nextList = columns.map(val => val.dataIndex!.toString());

    return ['no', ...nextList];
  });

  const table = useReactTable({
    data,
    columns: columnList.current,
    state: {
      columnSizing,
      columnOrder,
    },
    getCoreRowModel: getCoreRowModel(),
    onColumnSizingChange: setColumnSizing,
    columnResizeMode: 'onChange',
    onColumnOrderChange: setColumnOrder,
  });

  return [{...table}, setColumnOrder] as const;
}
