import { getFileReq } from '@/services/file';
import { to } from '@/utils/promise';
import tableCellRender from '@/utils/table';
import { Table, type TableProps } from 'antd';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import TrialStatusCell from '../TrialStatusCell';
import styles from './index.less';

type ExperimentHistoryProps = {
  calcMetrics?: string; // 计算指标
  fileUrl?: string; // 文件url
  isClassification: boolean; // 是否是分类
};

type TableData = {
  id?: string;
  accuracy?: number;
  duration?: number;
  train_loss?: number;
  status?: string;
  feature?: string;
  althorithm?: string;
};

function ExperimentHistory({ calcMetrics, fileUrl, isClassification }: ExperimentHistoryProps) {
  const [tableData, setTableData] = useState<TableData[]>([]);
  useEffect(() => {
    // 获取实验运行历史记录
    const getHistoryFile = async () => {
      const [res] = await to(getFileReq(fileUrl));
      if (res) {
        const data: any[] = res.data;
        const list: TableData[] = data.map((item) => {
          return {
            id: item[0]?.[0],
            accuracy: calcMetrics ? item[1]?.[5]?.[calcMetrics] : undefined,
            duration: item[1]?.[5]?.duration,
            train_loss: item[1]?.[5]?.train_loss,
            status: item[1]?.[2]?.['__enum__']?.split('.')?.[1],
          };
        });
        list.forEach((item) => {
          if (!item.id) return;
          const config = (res as any).configs?.[item.id];
          item.feature = config?.['feature_preprocessor:__choice__'];
          item.althorithm = isClassification
            ? config?.['classifier:__choice__']
            : config?.['regressor:__choice__'];
        });
        setTableData(list);
      }
    };

    if (fileUrl) {
      getHistoryFile();
    }
  }, [fileUrl, isClassification, calcMetrics]);

  const columns: TableProps<TableData>['columns'] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: tableCellRender(false),
    },
    {
      title: '耗时',
      dataIndex: 'duration',
      key: 'duration',
      render: tableCellRender(true),
    },
    {
      title: '训练损失',
      dataIndex: 'train_loss',
      key: 'train_loss',
      render: tableCellRender(true),
    },
    {
      title: '特征处理',
      dataIndex: 'feature',
      key: 'feature',
      render: tableCellRender(true),
    },
    {
      title: '算法',
      dataIndex: 'althorithm',
      key: 'althorithm',
      render: tableCellRender(true),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: TrialStatusCell,
    },
  ];

  if (calcMetrics) {
    columns.splice(0, 0, {
      title: `指标：${calcMetrics}`,
      dataIndex: 'accuracy',
      key: 'accuracy',
      render: tableCellRender(true),
    });
  }

  return (
    <div className={styles['experiment-history']}>
      <div className={styles['experiment-history__content']}>
        <div
          className={classNames(
            'vertical-scroll-table-no-page',
            styles['experiment-history__content__table'],
          )}
        >
          <Table
            dataSource={tableData}
            columns={columns}
            pagination={false}
            scroll={{ y: 'calc(100% - 55px)' }}
            rowKey="id"
          />
        </div>
      </div>
    </div>
  );
}

export default ExperimentHistory;
