/*
 * @Author: 赵伟
 * @Date: 2024-09-02 08:42:57
 * @Description: 可视化
 */

import IframePage, { IframePageType } from '@/components/IFramePage';
import KFEmpty, { EmptyType } from '@/components/KFEmpty';
import KFSpin from '@/components/KFSpin';
import { TensorBoardStatus } from '@/enums';
import { getTensorBoardStatusReq, runTensorBoardReq } from '@/services/experiment/index.js';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import { LoadingOutlined } from '@ant-design/icons';
import { useCallback, useEffect, useState } from 'react';
import styles from './index.less';

type TensorBoardProps = {
  namespace?: string;
  path?: string;
};

function ExperimentVisualResult({ namespace, path }: TensorBoardProps) {
  const [tensorboardUrl, setTensorboardUrl] = useState<string | undefined | null>(undefined);
  const [status, setStatus] = useState<TensorBoardStatus | undefined>(undefined);

  // 获取 TensorBoard 状态
  const getTensorBoardStatus = useCallback(async () => {
    const params = {
      namespace: namespace,
      path: path,
    };
    const [res] = await to(getTensorBoardStatusReq(params));
    if (res && res.data) {
      const status = res.data.status as TensorBoardStatus | undefined;
      setStatus(res.data.status);
      if (!status || status === TensorBoardStatus.Pending) {
        setTimeout(() => {
          getTensorBoardStatus();
        }, 5000);
      }
    }
  }, [namespace, path]);

  // 运行 TensorBoard
  const runTensorBoard = useCallback(async () => {
    const params = {
      namespace: namespace,
      path: path,
    };
    const [res] = await to(runTensorBoardReq(params));
    if (res && res.data) {
      const url = res.data;
      SessionStorage.setItem(SessionStorage.tensorBoardUrlKey, url);
      setTensorboardUrl(url);
      getTensorBoardStatus();
    } else {
      setTensorboardUrl(null);
    }
  }, [namespace, path, getTensorBoardStatus]);

  useEffect(() => {
    if (namespace && path) {
      runTensorBoard();
    }
  }, [namespace, path, runTensorBoard]);

  if (tensorboardUrl === null || status === TensorBoardStatus.Failed) {
    return (
      <div className={styles['experiment-visual']}>
        <KFEmpty
          className={styles['experiment-visual__empty']}
          type={EmptyType.NoData}
          title="运行可视化失败"
          buttonTitle="重新运行"
          onButtonClick={runTensorBoard}
        />
      </div>
    );
  } else if (status === TensorBoardStatus.Pending) {
    return (
      <div className={styles['experiment-visual']}>
        <KFSpin indicator={<LoadingOutlined spin />} size="large" />
      </div>
    );
  } else if (status === TensorBoardStatus.Running) {
    return (
      <div className={styles['experiment-visual']}>
        <IframePage type={IframePageType.TensorBoard}></IframePage>
      </div>
    );
  }
}

export default ExperimentVisualResult;
