import { ResourceType } from '@/pages/Dataset/config';
import { getNodeResult } from '@/services/experiment/index.js';
import { downLoadZip } from '@/utils/downloadfile';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { App, Button } from 'antd';
import { useEffect, useState } from 'react';
import ExportModelModal from '../ExportModelModal';
import styles from './index.less';

type ExperimentResultProps = {
  pipelineId: number; // 流水线 id
  experimentId: number; // 实验 id
  experimentName: string; // 实验 name
  experimentInsId: number; // 实验实例 id
  pipelineNodeId: string; // 流水线节点 id
};

type ExperimentResultData = {
  name: string;
  path: string;
  type: string;
  value: {
    name: string;
    size: string;
  }[];
};

function ExperimentResult({
  pipelineId,
  experimentId,
  experimentName,
  experimentInsId,
  pipelineNodeId,
}: ExperimentResultProps) {
  const { message } = App.useApp();
  const [experimentResults, setExperimentResults] = useState<ExperimentResultData[]>([]);
  const resourceType: ResourceType | undefined = pipelineNodeId.startsWith('general-data-process')
    ? ResourceType.Dataset
    : pipelineNodeId.startsWith('model-train') ||
      pipelineNodeId.startsWith('distributed-model-train')
    ? ResourceType.Model
    : undefined;

  useEffect(() => {
    // 获取实验结果
    const getExperimentResult = async (params: any) => {
      const [res] = await to(getNodeResult(params));
      if (res && res.data && Array.isArray(res.data)) {
        const data = res.data.filter((item: ExperimentResultData) => item.value.length > 0);
        setExperimentResults(data);
      } else {
        setExperimentResults([]);
      }
    };
    getExperimentResult({ id: `${experimentInsId}`, node_id: pipelineNodeId });
  }, [experimentInsId, pipelineNodeId]);

  // 下载
  const download = (path: string) => {
    downLoadZip(`/api/mmp/minioStorage/download`, { path });
  };

  // 导出到数据集、模型
  const exportToResource = (path: string) => {
    const { close } = openAntdModal(ExportModelModal, {
      resourceType: resourceType!,
      pipelineId,
      experimentId,
      experimentName,
      experimentInsId,
      pipelineNodeId,
      path,
      onOk: () => {
        message.success('导出成功');
        close();
      },
    });
  };

  return (
    <div className={styles['experiment-result']}>
      <div className={styles['experiment-result__content']}>
        {experimentResults.length > 0 ? (
          experimentResults.map((item) => (
            <div key={item.name || item.path} className={styles['experiment-result__item']}>
              <div className={styles['experiment-result__item__name']}>
                <span>{item.name}</span>
                <Button
                  size="small"
                  type="link"
                  style={{ marginLeft: 'auto' }}
                  onClick={() => {
                    download(item.path);
                  }}
                >
                  下载
                </Button>
                {resourceType && (
                  <Button
                    size="small"
                    type="link"
                    onClick={() => {
                      exportToResource(item.path);
                    }}
                  >
                    导出到{resourceType === ResourceType.Model ? '模型' : '数据集'}
                  </Button>
                )}
              </div>
              <div style={{ margin: '15px 0' }} className={styles['experiment-result__item__file']}>
                <span>文件名称</span>
                <span>文件大小</span>
              </div>
              {item.value?.map((ele) => (
                <div className={styles['experiment-result__item__file']} key={ele.name}>
                  <span>{ele.name}</span>
                  <span>{ele.size}</span>
                </div>
              ))}
            </div>
          ))
        ) : (
          <div className={styles['experiment-result__empty']}>暂无结果</div>
        )}
      </div>
    </div>
  );
}

export default ExperimentResult;
