import { Table } from '@easyv/antd';
import { TableProps } from '@easyv/antd/lib/table';
import classNames from 'classnames';
import React, { CSSProperties, useMemo } from 'react';
import styles from './style.less';
import emptyText from '../../../images/emptyText.png';

interface Props extends TableProps<any> {
  pageSize?: number;
  className?: string;
  rowHeight?: CSSProperties['height'];
  openSelect?: boolean;
  rowKey?: string | ((record: any) => string);
  dataSource: any[];
  selectedRowKeys?: (number | string)[];
  onRowSelectChange?: (selectedRowKeys: (number | string)[]) => void;
}
const EmptyText = () => {
  return (
    <div className={styles.emptyText}>
      <img src={emptyText} alt="" />
      <span>暂无数据</span>
    </div>
  );
};
const EasyvTable = React.memo((props: Props) => {
  const {
    className,
    pageSize = 10,
    openSelect = true,
    rowKey = 'id',
    selectedRowKeys = [],
    dataSource = [],
    onRowSelectChange,
    ...otherProps
  } = props;

  const rowSelection = useMemo<TableProps<any>['rowSelection']>(
    () => ({
      columnWidth: 60,
      selectedRowKeys,
      onSelect: (record, selected) => {
        const currentRowKey = typeof rowKey === 'string' ? record[rowKey] : rowKey(record);
        if (selected) {
          onRowSelectChange?.(selectedRowKeys.concat(currentRowKey));
        } else {
          onRowSelectChange?.(selectedRowKeys.filter((d) => d !== currentRowKey));
        }
      },
      onSelectAll: (selected) => {
        if (selected) {
          const selectedRowKeys =
            typeof rowKey === 'string'
              ? dataSource.map((record) => record[rowKey])
              : dataSource.map(rowKey);
          onRowSelectChange?.(selectedRowKeys);
        } else {
          onRowSelectChange?.([]);
        }
      },
      onSelectInvert: () => {
        onRowSelectChange?.([]);
      },
    }),
    [openSelect, selectedRowKeys, dataSource, rowKey],
  );

  return (
    <Table
      id="easyvTable"
      className={classNames(styles.tableWrapper, className)}
      dataSource={dataSource}
      rowKey={rowKey}
      locale={{
        emptyText: <EmptyText />,
      }}
      pagination={{
        total: props.dataSource?.length,
        pageSize: pageSize,
        showTotal: (total) => (
          <span className={styles.pageText}>
            共<span className={styles.count}>{total}</span>
            条数据，每页显示：<span className={styles.count}>{pageSize}</span>条
          </span>
        ),
        showSizeChanger: false,
      }}
      rowSelection={openSelect ? rowSelection : undefined}
      {...otherProps}
      getPopupContainer={(node) => {
        return document.getElementById('easyvTable') || document.body;
      }}
    />
  );
});

export default EasyvTable;
