// 蓝色系列表格样式
import type { TableProps } from 'antd';
import { ConfigProvider, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useEffect, useRef } from 'react';
import styles from './index.less';

export interface BlueTableWithScrollProps extends TableProps<any> {
  serial?: boolean; // 是否开启序列
  serialName?: string; // 序列名
  enableScrollLoading?: boolean; // 是否启用滚动加载
  onTableScroll?: (event: React.UIEvent<HTMLDivElement>) => void; // 滚动回调
  scrollThreshold?: number; // 滚动触发阈值，默认20px
}

export type TableColumnsType = ColumnsType<Record<string, any>>;

const BlueTableWithScroll = (props: BlueTableWithScrollProps) => {
  const { 
    serial, 
    columns, 
    pagination = false, 
    serialName,
    enableScrollLoading = false,
    onTableScroll,
    scrollThreshold = 20,
    ...restProps
  } = props;
  
  const tableContainerRef = useRef<HTMLDivElement>(null);
  
  // 序列号列配置
  const serialOpt = {
    title: serialName ?? '名次',
    dataIndex: 'serialNumber',
    render: (text: number) => <span>{text}</span>,
    width: 80,
    align: 'center',
  };
  
  const resetColumns: any = serial ? [serialOpt, ...columns!] : columns;

  // 处理滚动事件
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (enableScrollLoading && onTableScroll) {
      onTableScroll(e);
    }
  };
  
  // 监听父容器滚动事件
  useEffect(() => {
    const container = tableContainerRef.current;
    if (!container || !enableScrollLoading || !onTableScroll) return;
    
    // 添加滚动监听
    container.addEventListener('scroll', handleScroll as any);
    
    return () => {
      // 移除滚动监听
      container.removeEventListener('scroll', handleScroll as any);
    };
  }, [enableScrollLoading, onTableScroll]);

  return (
    <ConfigProvider
      theme={{
        components: {
          Table: {
            headerBg: 'transparent', // 表头背景
            colorBgContainer: 'transparent',
            headerColor: '#6A738E',
            rowHoverBg: 'rgba(57, 122, 183, 0.2)', // 移入背景
            borderColor: 'rgba(57, 122, 183, 0.2)', // 边框颜色
            headerSplitColor: 'rgba(57, 122, 183, 0.2)', // 分割线颜色
            cellFontSize: 16,
            cellFontSizeSM: 16,
            headerBorderRadius: 20,
          },
        },
      }}
    >
      <div 
        ref={tableContainerRef}
        style={{ overflow: 'auto', maxWidth: '100%', height: '100%'}} 
        onScroll={enableScrollLoading ? handleScroll : undefined}
      >
        <Table
          className={styles.tablewrap}
          bordered={false}
          rowClassName={styles.tablerow}
          columns={resetColumns}
          pagination={pagination}
          {...restProps}
        />
      </div>
    </ConfigProvider>
  );
};

export default BlueTableWithScroll;
