import React, {useEffect, useState, useRef} from 'react';
import {Table} from 'antd';
// @ts-ignore
import {Resizable} from 'react-resizable';
// @ts-ignore
import classNames from 'classnames';
import './index.less';

const ResizableTitle = (props: any) => {
  const {onResize, width, ...restProps} = props;
  // 添加偏移量
  const [offset, setOffset] = useState(0);
  if (!width) {
    return <th {...restProps} />;
  }
  return (
      <Resizable
          width={width + offset}
          height={0}
          handle={
            <span
                className={classNames(['reactResizableHandle', offset && 'active'])}
                style={{transform: `translateX(${offset}px)`}}
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                }}
            />
          }
          onResize={(_e: any, {size}: any) => {
            // 这里只更新偏移量，数据列表其实并没有伸缩
            setOffset(size.width - width);
          }}
          // 拖拽结束更新
          onResizeStop={(...arg: any) => {
            // 拖拽结束以后偏移量归零
            setOffset(0);
            onResize(...arg);
          }}
          draggableOpts={{enableUserSelectHack: false}}
      >
        <th {...restProps} />
      </Resizable>
  );
};

const GTable: React.FC<any> = (props) => {
  const {columns, resizable, virtual, ...restProps} = props;
  const [mergedColumns, setMergedColumns] = useState<any[]>([]);
  const columnsWidthRef = useRef<any>({});
  const columnsRef = useRef<any>([]);
  const handleResize = (index: number) => (_e: any, {size}: any) => {
    const nextColumns = [...columnsRef.current];
    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width,
    };
    const tempContainer = {...columnsWidthRef.current};
    const name = nextColumns[index].dataIndex || '';
    tempContainer[name] = size.width;
    columnsWidthRef.current = tempContainer;
    setMergedColumns(nextColumns);
  };
  useEffect(() => {
    columnsRef.current = mergedColumns;
  }, [mergedColumns]);

  const mergeColumns = () => {
    const list = columns.map((x: any, index: number) => {
      const obj = {...x};
      // 拖拽拉伸
      if (resizable && !obj.onHeaderCell) {
        const width = columnsWidthRef.current[obj.dataIndex];
        if (width) {
          obj.width = width;
        }
        obj.onHeaderCell = (column: any) => ({
          width: column.width,
          onResize: handleResize(index),
        });
      }
      const {ellipsis} = obj;
      if (ellipsis !== false) {
        obj.ellipsis = true;
      }
      return obj;
    });
    setMergedColumns(list);
  };
  useEffect(() => {
    if (columns.length > 0) {
      mergeColumns();
    }
  }, [columns]);
  const components = {
    header: {
      cell: ResizableTitle,
    },
  };
  return (
      <div>
        {mergedColumns.length > 0 ? (
            <Table
                rowClassName={(_record: any, index: number) => {
                  let className = '';
                  if (index % 2 === 1) className = 'darkRow';
                  return className;
                }}
                size="small"
                {...restProps}
                columns={mergedColumns}
                components={components}
            />
        ) : null}
      </div>
  );
};

export default GTable;
