import FullScreenFrame from '@/components/FullScreenFrame';
import KFSpin from '@/components/KFSpin';
import { getLabelStudioUrl } from '@/services/developmentEnvironment';
import { generateSign } from '@/utils';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import { useModel } from '@umijs/max';
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',
}

const getRequestAPI = (type: IframePageType, loginName: string): (() => Promise<any>) => {
  switch (type) {
    case IframePageType.DatasetAnnotation:
      return getLabelStudioUrl;
    case IframePageType.AppDevelopment: {
      // return () => Promise.resolve({ code: 200, data: 'http://172.20.32.185:30080/' });
      const sign = generateSign(loginName);

      return () =>
        Promise.resolve({
          code: 200,
          data: `http://10.43.107.27:24078/uap/nudt/sso/login?name=${loginName}&sign=${sign}`,
        });
    }
    case IframePageType.DevEnv:
      return () =>
        Promise.resolve({
          code: 200,
          data: SessionStorage.getItem(SessionStorage.editorUrlKey) || '',
        });
    case IframePageType.GitLink:
      return () => Promise.resolve({ code: 200, data: 'http://172.20.32.201:4000' });
  }
};

type IframePageProps = {
  type: IframePageType;
  className?: string;
  style?: React.CSSProperties;
};

function IframePage({ type, className, style }: IframePageProps) {
  const [iframeUrl, setIframeUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  useEffect(() => {
    requestIframeUrl();
    return () => {
      if (type === IframePageType.DevEnv) {
        SessionStorage.removeItem(SessionStorage.editorUrlKey);
      }
    };
  }, []);
  const requestIframeUrl = async () => {
    setLoading(true);
    const [res] = await to(getRequestAPI(type, currentUser?.userName || '')());
    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;
