// api/index.js
import http from './http.js'
import utils from '../utils/utils.js'
import config from './config.js'

const limit = new Map()
const debounce = new Map()



// 动态导入 models
const modules = import.meta.glob('./model/*.js', { eager: true })
Object.entries(modules).forEach(([path, mod]) => {
  const model = mod.default || mod
  const key = path.match(/\/([^/]+)\.js$/)[1]
  for (const k in model) {
    if (config[k]) {
      console.error(`重名api------model=${key},key=${k}`)
      // 这里建议用全局弹窗或通知
      continue
    }
    config[k] = model[k]
  }
})

/**
 * 通用API请求
 * @param {string} key
 * @param {object} data
 * @param {function} [callback]
 * @param {string} [loadingTitle]
 * @returns {Promise}
 */
export function api(key, data = {}, callback, loadingTitle) {
  const req = config[key]

  if (!req) {
    console.error('无效key: ' + key)
    return Promise.reject(new Error('无效key'))
  }

  // 参数重载
  if (typeof callback === 'string') {
    loadingTitle = callback
    callback = undefined
  }
  if (typeof data === 'function') {
    callback = data
    data = {}
  }

  // 限流
  if (req.limit) {
    const last = limit.get(req.url)
    if (last && Date.now() - last < req.limit) {
      return Promise.reject(new Error('请求过于频繁'))
    }
    limit.set(req.url, Date.now())
  }
  // console.log(!uni.getStorageSync('token'),'status');
  // 必须登录
  if (req.auth && !uni.getStorageSync('token')) {
    // utils.toLogin()
    return Promise.reject(new Error('需要登录'))
  }

  // 防抖
  if (req.debounce) {
    const prev = debounce.get(req.url)
    if (prev) clearTimeout(prev)
    debounce.set(
      req.url,
      setTimeout(() => {
        debounce.delete(req.url)
        http.http(
          req.url,
          data,
          callback,
          req.method,
          loadingTitle || req.showLoading,
          loadingTitle || req.loadingTitle
        )
      }, req.debounce)
    )
    return Promise.reject(new Error('请求防抖中'))
  }

  // 正常请求

  return http.http(
    req.url,
    data,
    callback,
    req.method,
    loadingTitle || req.showLoading,
    loadingTitle || req.loadingTitle
  )
}

export default api