// import { useCacheState } from '@/hooks/pageCacheState';
import {
  getExpEvaluateInfosReq,
  getExpMetricsReq,
  getExpTrainInfosReq,
} from '@/services/experiment';
import { to } from '@/utils/promise';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { useSearchParams } from '@umijs/max';
import { App, Button, Table, /* TablePaginationConfig,*/ TableProps, Tooltip } from 'antd';
import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import ExperimentStatusCell from '../components/ExperimentStatusCell';
import { ComparisonType, comparisonConfig } from './config';
import styles from './index.less';

type TableData = {
  experiment_ins_id: number;
  run_id: string;
  dataset: string[];
  start_time: string;
  status: string;
  metrics_names: string[];
  metrics: Record<string, number>;
  params_names: string[];
  params: Record<string, number>;
};

function ExperimentComparison() {
  const [searchParams] = useSearchParams();
  const comparisonType = searchParams.get('type') as ComparisonType;
  const experimentId = searchParams.get('id');
  const [tableData, setTableData] = useState<TableData[]>([]);
  // const [cacheState, setCacheState] = useCacheState();
  // const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // const [loading, setLoading] = useState(false);
  const { message } = App.useApp();
  const config = useMemo(() => comparisonConfig[comparisonType], [comparisonType]);
  // const [pagination, setPagination] = useState<TablePaginationConfig>(
  //   cacheState?.pagination ?? {
  //     current: 1,
  //     pageSize: 10,
  //   },
  // );

  useEffect(() => {
    getComparisonData();
  }, [experimentId]);

  // 获取对比数据列表
  const getComparisonData = async () => {
    // setLoading(true);
    const request =
      comparisonType === ComparisonType.Train ? getExpTrainInfosReq : getExpEvaluateInfosReq;
    const [res] = await to(request(experimentId, { offset: '', limit: 50 }));
    // setLoading(false);
    if (res && res.data) {
      // const { content = [], totalElements = 0 } = res.data;
      setTableData(res.data);
      // setTotal(totalElements);
    }
  };

  // 获取对比 url
  const getExpMetrics = async () => {
    const [res] = await to(getExpMetricsReq(selectedRowKeys));
    if (res && res.data) {
      const url = res.data;
      window.open(url, '_blank');
    }
  };

  // 对比按钮 click
  const hanldeComparisonClick = () => {
    if (selectedRowKeys.length < 2) {
      message.error('请至少选择两项进行对比');
      return;
    }
    getExpMetrics();
  };

  // 分页切换
  // const handleTableChange: TableProps['onChange'] = (pagination, filters, sorter, { action }) => {
  //   if (action === 'paginate') {
  //     setPagination(pagination);
  //   }
  //   // console.log(pagination, filters, sorter, action);
  // };

  // 选择行
  const rowSelection: TableProps['rowSelection'] = {
    type: 'checkbox',
    fixed: 'left',
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  const columns: TableProps<TableData>['columns'] = useMemo(() => {
    const first: TableData | undefined = tableData[0];
    return [
      {
        title: '基本信息',
        align: 'center',
        children: [
          {
            title: '实例 ID',
            dataIndex: 'experiment_ins_id',
            key: 'experiment_ins_id',
            width: 100,
            fixed: 'left',
            align: 'center',
            render: tableCellRender(),
          },
          {
            title: '运行时间',
            dataIndex: 'start_time',
            key: 'start_time',
            width: 180,
            fixed: 'left',
            align: 'center',
            render: tableCellRender(false, TableCellValueType.Date),
          },
          {
            title: '运行状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            fixed: 'left',
            // align: 'center',
            render: ExperimentStatusCell,
          },
          {
            title: `${config.title}数据集`,
            dataIndex: 'dataset',
            key: 'dataset',
            width: 180,
            fixed: 'left',
            align: 'center',
            render: tableCellRender(true, TableCellValueType.Array),
            ellipsis: { showTitle: false },
          },
        ],
      },
      {
        title: `${config.title}参数`,
        align: 'center',
        children: first?.params_names.map((name) => ({
          title: (
            <Tooltip title={name}>
              <span>{name}</span>
            </Tooltip>
          ),
          dataIndex: ['params', name],
          key: name,
          width: 120,
          align: 'center',
          render: tableCellRender(true),
          ellipsis: { showTitle: false },
          sorter: (a, b) => a.params[name] - b.params[name],
          showSorterTooltip: false,
        })),
      },
      {
        title: `${config.title}指标`,
        align: 'center',
        children: first?.metrics_names.map((name) => ({
          title: (
            <Tooltip title={name}>
              <span>{name}</span>
            </Tooltip>
          ),
          dataIndex: ['metrics', name],
          key: name,
          width: 120,
          align: 'center',
          render: tableCellRender(true),
          ellipsis: { showTitle: false },
          sorter: (a, b) => a.metrics[name] - b.metrics[name],
          showSorterTooltip: false,
        })),
      },
    ];
  }, [tableData]);

  return (
    <div className={styles['experiment-comparison']}>
      <div className={styles['experiment-comparison__header']}>
        <Button type="default" onClick={hanldeComparisonClick}>
          可视化对比
        </Button>
      </div>
      <div
        className={classNames(
          'vertical-scroll-table-no-page',
          styles['experiment-comparison__table'],
        )}
      >
        <Table
          dataSource={tableData}
          columns={columns}
          rowSelection={rowSelection}
          scroll={{ y: 'calc(100% - 110px)', x: '100%' }}
          pagination={false}
          bordered={true}
          virtual
          // onScroll={handleTableScroll}
          // loading={loading}
          // pagination={{
          //   ...pagination,
          //   total: total,
          //   showSizeChanger: true,
          //   showQuickJumper: true,
          // }}
          // onChange={handleTableChange}
          rowKey="run_id"
        />
      </div>
    </div>
  );
}

export default ExperimentComparison;
