import React from 'react';
import { Table } from 'antd';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';

const SortableItem = SortableElement((props: any) => <tr {...props} />);
const NewSortableContainer = SortableContainer((props: any) => (
  <tbody {...props} />
));

export interface IProps {
  tablesize?: any;
  tableConfig?: any;
  draggable?: boolean | (() => boolean);
  handleOnSortEnd?: (oldIndex: number, newIndex: number) => void;
}

const Tables: React.FC<IProps> = (props: IProps) => {
  let { handleOnSortEnd, tablesize, tableConfig, draggable } = props;

  const onSortEnd = (props: any) => {
    const { oldIndex, newIndex } = props;
    if (handleOnSortEnd && oldIndex !== newIndex)
      handleOnSortEnd(oldIndex, newIndex);
  };

  const DragHandle = SortableHandle(() => (
    <i
      className="iconfont icon-Drag"
      style={{ color: '#999', cursor: 'all-scroll' }}
    />
  ));

  const DraggableContainer = (props: any) => {
    return (
      <NewSortableContainer
        useDragHandle
        disableAutoscroll
        helperClass="row-dragging"
        onSortEnd={onSortEnd}
        {...props}
      />
    );
  };

  const DraggableBodyRow = (props: any) => {
    const { style, ...restProps } = props;
    const { dataSource } = tableConfig;
    const index = dataSource.findIndex(
      (x: any) => x.key === restProps['data-row-key'],
    );
    return <SortableItem index={index} {...restProps} />;
  };

  if (draggable) {
    tableConfig = {
      ...tableConfig,
      columns: [
        {
          title: '',
          dataIndex: 'sort',
          width: 48,
          className: 'drag-visible',
          render: () => <DragHandle />,
        },
        ...tableConfig.columns.filter(
          (item: any) => item.filterType && item.filterType === true,
        ),
      ],
      components: {
        body: {
          wrapper: DraggableContainer,
          row: DraggableBodyRow,
        },
      },
    };
  }

  return <Table {...tableConfig} size={tablesize} />;
};

export default Tables;
