import { ILoginConfig, LoginSource } from './types';
import { Router } from './router';

/**
 * 判断是否在企微内部打开
 */
export const inWxWork = () => {
  const ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf('wxwork') !== -1) {
    return true;
  }
  return false;
};

export async function getJson(url: string, data = {}) {
  const response = await fetch(url, data);
  return await response.json();
}

export async function getConfig(router: Router) {
  const source = router.getUrlParams('source');
  const staticOrigin = getStaticOrigin(router);
  try {
    let config: ILoginConfig;
    if (source === LoginSource.PORTAL) {
      // const systemConfig = await getJson(`${staticOrigin}/adminportal/systemConfig.json`);
      // config = formatPortalConfig(systemConfig[getPortalEnvType()]);
    } else if (source === LoginSource.APIS) {
      // config = APIS_CONFIG;
    } else {
      const version = router.getUrlParams('config_version') || '';
      const hashVersion = version.split('_')[0];
      const path = `${router.getUrlParams('app_id')}/${getConfigName(version)}.json`;
      if (hashVersion === 'v1') {
        config = await getJson(`${staticOrigin}/__auth/app/${path}`);
      } else {
        // 兼容老版本配置存储规则
        config = await getJson(`${staticOrigin}/${path}`);
      }
      return config;
    }
    throw new Error(`加载配置失败 source error ${source}`);
  } catch (e) {
    throw new Error('加载配置失败');
  }
}

let staticOrigin: string;
export function getStaticOrigin(router) {
  if (!staticOrigin) {
    staticOrigin = location.origin;
    try {
      if (router.getUrlParams('s_domain')) {
        const url = new URL(`https://${router.getUrlParams('s_domain')}`);
        if (url.origin.endsWith('.tcloudbaseapp.com') || url.origin === '127.0.0.1') {
          staticOrigin = url.origin;
        }
      }
    } catch (e) {
      throw new Error('s_domain参数错误');
    }
  }
  return staticOrigin;
}

export function getConfigName(version) {
  return `login.config${version ? `.${version}` : ''}`;
}
