import InfoGroup from '@/components/InfoGroup';
import { AutoMLType } from '@/enums';
import { type HyperParameterFile } from '@/pages/AutoML/types';
import TrialFileTree from '@/pages/HyperParameter/components/TrialFileTree';
import { getFileReq } from '@/services/file';
import { to } from '@/utils/promise';
import { Button, Image } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import styles from './index.less';

type ExperimentResultProps = {
  fileUrl?: string;
  imageUrl?: string;
  modelPath?: string;
  type?: string;
  file?: HyperParameterFile;
};

function ExperimentResult({ fileUrl, imageUrl, modelPath, type, file }: ExperimentResultProps) {
  const [result, setResult] = useState<string | undefined>('');

  const images = useMemo(() => {
    if (imageUrl) {
      return imageUrl.split(',').map((item) => item.trim());
    }
    return [];
  }, [imageUrl]);

  useEffect(() => {
    // 获取实验运行历史记录
    const getResultFile = async () => {
      const [res] = await to(getFileReq(fileUrl));
      if (res) {
        setResult(res as any as string);
      }
    };

    if (fileUrl && type !== AutoMLType.Video) {
      getResultFile();
    }
  }, [fileUrl, type]);

  return (
    <div className={styles['experiment-result']}>
      {type === AutoMLType.Video ? (
        <TrialFileTree
          file={file}
          title="实验结果"
          classname={styles['experiment-result__file']}
        ></TrialFileTree>
      ) : (
        <InfoGroup title="实验结果" height={420}>
          <div className={styles['experiment-result__text']}>{result}</div>
        </InfoGroup>
      )}

      {type === AutoMLType.Table && (
        <InfoGroup title="可视化结果" style={{ margin: '16px 0' }}>
          <div className={styles['experiment-result__images']}>
            <Image.PreviewGroup
              preview={{
                onChange: (current, prev) =>
                  console.log(`current index: ${current}, prev index: ${prev}`),
              }}
            >
              {images.map((item) => (
                <Image
                  key={item}
                  className={styles['experiment-result__images__item']}
                  src={item}
                  height={248}
                  draggable={false}
                  alt=""
                />
              ))}
            </Image.PreviewGroup>
          </div>
        </InfoGroup>
      )}

      {modelPath && (
        <div className={styles['experiment-result__download']}>
          <span style={{ marginRight: '12px', color: '#606b7a' }}>文件名</span>
          <span>{modelPath.split('/').pop()} </span>
          <Button
            type="primary"
            className={styles['experiment-result__download__btn']}
            onClick={() => {
              window.location.href = modelPath;
            }}
          >
            模型下载
          </Button>
        </div>
      )}
    </div>
  );
}

export default ExperimentResult;
