export type Config = {
  tenantId: string;
  apiUrl: string;
}

export const getConfig = async (): Promise<Config> => {
  const configStr = await fetch('/config.json').then(res => res.text())
  const sassUrlStr = await fetch('https://nono-1257812345.cos.ap-shanghai.myqcloud.com/sass').then(res => res.text())

  const config = JSON.parse(configStr) as Config
  // sassUrlStr逗号分隔
  const sassUrlList = sassUrlStr.split(',')
  console.log(sassUrlList)
  for (const item of sassUrlList) {
    const url = item + '/api/app/check'
    // 判断url是否连通
    try {
      const newVar = await fetchWithTimeout(url, 1000).then(res => res.json())
      if (newVar.code === 200) {
        config.apiUrl = item
      }
    } catch (e) {
      console.error(e)
    }
  }

  return config
}

function fetchWithTimeout(url, timeout) {
  // 创建一个在指定时间后拒绝的Promise
  const timeoutPromise = new Promise((_, reject) => {
    let id = setTimeout(() => {
      clearTimeout(id);
      reject(`Fetch timed out after ${timeout} ms`);
    }, timeout);
  });

  // 使用fetch发起请求
  const fetchPromise = fetch(url);

  // 使用Promise.race来等待第一个Promise解析或拒绝
  return Promise.race([
    fetchPromise,
    timeoutPromise
  ]);
}

// 配置文件
const t_000000: Config = {
  tenantId: '000000',
  apiUrl: 'http://124.222.254.188:8889'
}


// export const getConfig = (tenantId: string): Config => {
//
//   // TODO: 读取配置文件
//   const config = import(`${tenantId}.ts`)
//
//   console.log('res ======222222222222=========> ')
//   console.log(config)
//   console.log(config)
//   if (!config) {
//
//   }
//   config.then((res) => {
//
//     console.log('res ======222222222222=========> ')
//     console.log(res)
//     console.log(res)
//   })
//
//
//   return {
//     tenantId: '000000'
//   }
// }