const app = getApp()

function getBaseURL() {
  return app.globalData.baseURL || 'http://127.0.0.1:5000/api'
}

function getServerBase() {
  const baseURL = getBaseURL()
  return baseURL.replace('/api', '')
}

function getToken() {
  return app.globalData.token || wx.getStorageSync('token') || ''
}

function request({ url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    const token = getToken()
    const headers = {
      'Content-Type': 'application/json',
      ...header
    }

    if (token) {
      headers.Authorization = `Bearer ${token}`
    }

    wx.request({
      url: `${getBaseURL()}${url}`,
      method,
      data,
      header: headers,
      success: (res) => {
        if (res.statusCode === 401) {
          app.clearAuth()
          wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' })
          setTimeout(() => wx.reLaunch({ url: '/pages/login/index' }), 600)
          reject(new Error('Unauthorized'))
          return
        }

        const body = res.data || {}
        if (body.code === 0) {
          resolve(body.data)
          return
        }

        const message = body.message || '请求失败'
        wx.showToast({ title: message, icon: 'none' })
        reject(new Error(message))
      },
      fail: (err) => {
        const msg = (err && err.errMsg) || '网络异常，请检查后端地址'
        wx.showToast({ title: msg, icon: 'none' })
        reject(err)
      }
    })
  })
}

function uploadFile(filePath) {
  return new Promise((resolve, reject) => {
    const token = getToken()
    wx.uploadFile({
      url: `${getServerBase()}/api/upload/image`,
      filePath,
      name: 'file',
      header: {
        Authorization: token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        const data = JSON.parse(res.data || '{}')
        if (data.code === 0) {
          resolve(data.data)
          return
        }
        const message = data.message || '上传失败'
        wx.showToast({ title: message, icon: 'none' })
        reject(new Error(message))
      },
      fail: (err) => {
        const msg = (err && err.errMsg) || '上传失败'
        wx.showToast({ title: msg, icon: 'none' })
        reject(err)
      }
    })
  })
}

module.exports = {
  request,
  uploadFile
}
