import env from '../config/env'

const BASE_URL = env.API_BASE

function request(options) {
  const token = uni.getStorageSync('admin_token')

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? 'Bearer ' + token : '',
        ...options.header
      },
      success(res) {
        if (res.data && res.data.code === 0) {
          resolve(res.data.data)
        } else if (res.data && (res.data.code === 1001 || res.data.code === 1002)) {
          uni.removeStorageSync('admin_token')
          uni.removeStorageSync('admin_token_expiry')
          uni.reLaunch({ url: '/pages/login/index' })
          reject(res.data)
        } else {
          reject(res.data || { code: -1, message: '请求失败' })
        }
      },
      fail(err) {
        reject({ code: -1, message: err.errMsg || '网络异常' })
      }
    })
  })
}

function get(url, data) {
  return request({ url, method: 'GET', data })
}

function post(url, data) {
  return request({ url, method: 'POST', data })
}

function put(url, data) {
  return request({ url, method: 'PUT', data })
}

export { request, get, post, put, BASE_URL }
