import { baseUrl } from '../config/config'

const $request = (url, params, method) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url,
      data: params,
      enableCache: true,
      enableHttp2: true,
      enableQuic: true,
      method,
      timeout: 0,
      success: (result) => {
        console.log(result.data);
        let { status, msg, data } = result.data;
        if (status === 10000) {
          resolve({ data, msg })
        } else {
          wx.showToast({
            title: msg,
            icon: 'error',
            duration: 3000
          })
          reject(null)
        }
      },
      fail: (res) => {
        console.log(res)
        if (res.errMsg === 'request:fail ') {
          wx.showToast({
            title: '网络请求失败',
            icon: 'error',
            duration: 3000
          })
        }
        reject(res)
      },
      complete: () => {
        // wx.hideLoading()
      }
    })
  })
}

const $get = (url, params) => {
  return $request(baseUrl + url, params, 'GET')
}

const $post = (url, params) => {
  return $request(baseUrl + url, params, 'POST')
}

module.exports = {
  $get,
  $post
}