import { storage } from './storage.js'

export const showLoading = (title = '加载中') => {
  uni.showLoading({ title, mask: true })
}

export const hideLoading = () => {
  uni.hideLoading()
}

export const showToast = (title, icon = 'none', duration = 2000) => {
  uni.showToast({ title, icon, duration })
}

export const getHeaders = () => {
  const token = storage.get('token')
  const headers = { 'Content-Type': 'application/json' }
  if (token) headers['accessToken'] = token
  return headers
}

export const request = (config) => {
  const { url, method = 'GET', data = {}, showLoad = true } = config

  if (showLoad) showLoading()

  const baseApi = import.meta.env.VITE_BASE_API || 'https://cloud.yeswash.cn/admin'
  const fullUrl = `${baseApi}${url}`

  const requestConfig = { url: fullUrl, method, header: getHeaders() }

  if (method === 'GET' && Object.keys(data).length > 0) {
    requestConfig.data = data
  } else if (method !== 'GET') {
    requestConfig.data = data
  }

  return new Promise((resolve, reject) => {
    uni.request({
      ...requestConfig,
      success: (res) => {
        if (showLoad) hideLoading()
        const { statusCode, data } = res
        if (statusCode === 200) {
          if (url === '/admin-user/login' && data.code === 200) {
            storage.set('token', data.data.accessToken)
          }
          if (data.code === 200) {
            resolve(data)
          } else {
            // 登录接口的错误由 login.vue 自行处理，不在此处提示
            if (url !== '/admin-user/login') {
              showToast(data.msg || data.message || '请求失败')
            }
            reject(data)
          }
        } else if (statusCode === 401) {
          showToast('登录已过期，请重新登录')
          storage.remove('token')
          uni.navigateTo({ url: '/pages/login/login' })
          reject(data)
        } else {
          showToast(`请求失败(${statusCode})`)
          reject(data)
        }
      },
      fail: (err) => {
        if (showLoad) hideLoading()
        showToast('网络请求失败，请检查网络连接')
        reject(err)
      }
    })
  })
}

export const get = (url, data = {}, showLoad = true) => {
  return request({ url, method: 'GET', data, showLoad })
}

export const post = (url, data = {}, showLoad = true) => {
  return request({ url, method: 'POST', data, showLoad })
}
