import React from "react";
import { TableAddon } from "../../TableProps";
import { noop } from "../../../_util/noop";

import { DraggableTable, DraggableTableBody } from "./DraggableTable";

/**
 * `columnsDraggable` 插件用于支持表格列拖拽排序操作。
 */
export interface ColumnsDraggableOptions<Column = any> {
  /**
   * 拖拽完成回调
   */
  onDragEnd?: (columns: Column[]) => void;

  /**
   * 可拖拽的列, 默认所有列
   * @default all
   */
  draggableColumns?: string[] | "all";
}

export function columnsDraggable({
  onDragEnd = noop,
  draggableColumns = "all",
}: ColumnsDraggableOptions): TableAddon {
  return {
    onInjectProps: props => {
      return {
        ...props,
        columnsDraggable: true,
        draggableColumns,
      };
    },
    onInjectTable: render => props => {
      const table = render(props);
      const { columns } = props;
      const newColumns = columns.filter((column: any) => !column.ignore);
      return (
        <DraggableTable
          table={table}
          draggableColumns={draggableColumns}
          onDragEnd={onDragEnd}
          columns={newColumns}
        />
      );
    },
    onInjectBody: render => (records, columns, topTip, bottomTip) => {
      const body = render(records, columns, topTip, bottomTip);
      return (
        <DraggableTableBody
          body={body}
          onDragEnd={onDragEnd}
          draggableColumns={draggableColumns}
        />
      );
    },
  };
}
