import FullScreenFrame from '@/components/FullScreenFrame';
import KFSpin from '@/components/KFSpin';
import { getLabelStudioUrl } from '@/services/developmentEnvironment';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import './index.less';

export enum IframePageType {
  DatasetAnnotation = 'DatasetAnnotation', // 数据标注
  AppDevelopment = 'AppDevelopment', // 应用开发
  DevEnv = 'DevEnv', // 开发环境
  GitLink = 'GitLink', // git link
}

const getRequestAPI = (type: IframePageType): (() => Promise<any>) => {
  switch (type) {
    case IframePageType.DatasetAnnotation: // 数据标注
      return getLabelStudioUrl;
    case IframePageType.AppDevelopment: // 应用开发
      return () => Promise.resolve({ code: 200, data: 'http://172.20.32.185:30080/' });
    case IframePageType.DevEnv: // 开发环境
      return () =>
        Promise.resolve({
          code: 200,
          data: SessionStorage.getItem(SessionStorage.editorUrlKey) || '',
        });
    case IframePageType.GitLink: // git link
      return () => Promise.resolve({ code: 200, data: 'http://172.20.32.201:4000' });
  }
};

type IframePageProps = {
  /** 子系统 */
  type: IframePageType;
  /** 自定义样式类名 */
  className?: string;
  /** 自定义样式 */
  style?: React.CSSProperties;
};

/** 系统内嵌 iframe，目前系统有数据标注、应用开发、开发环境、GitLink 四个子系统，使用时可以添加其他子系统 */
function IframePage({ type, className, style }: IframePageProps) {
  const [iframeUrl, setIframeUrl] = useState('');
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    requestIframeUrl();
    return () => {
      if (type === IframePageType.DevEnv) {
        SessionStorage.removeItem(SessionStorage.editorUrlKey);
      }
    };
  }, []);
  const requestIframeUrl = async () => {
    setLoading(true);
    const [res] = await to(getRequestAPI(type)());
    if (res && res.data) {
      setIframeUrl(res.data);
    } else {
      setLoading(false);
    }
  };

  const hideLoading = () => {
    setLoading(false);
  };

  return (
    <div className={classNames('kf-iframe-page', className)} style={style}>
      {loading && createPortal(<KFSpin size="large" />, document.body)}
      <FullScreenFrame url={iframeUrl} onLoad={hideLoading} onError={hideLoading} />
    </div>
  );
}

export default IframePage;
