let app = getApp();

class Request {

  /**
   * 基本属性
   */
  constructor() {
    this.options = {
      method: 'GET',
      data: {}
    }
  }

  /**
   * GET、POST请求
   * @param url
   * @param method
   * @param data
   * @returns {Promise}
   */
  ajax({
    url,
    method = this.options.method,
    data = this.options.data
  } = this.options) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        mask: true,
        title: '正在加载'
      })
      wx.request({
        url: app.DOMAIN_NAME + url,
        method: method,
        data: data,
        header: {
          'content-type': 'application/json',
          'Authorization': 'Bearer ' + app.Getopenid()
        },
        success: (res) => {
          let data = res.data
          if (data.code == 0) {
            wx.hideLoading()
            resolve(data)
          } else if (data.code == 401) {
            wx.hideLoading()
            wx.showModal({
              confirmText: '好的',
              content: ret.data.errmsg || '身份已过期,需重登录',
              success: res => {
                wx.removeStorageSync('MemberInfo')
                wx.reLaunch({
                  url: '/pages/login/login',
                })
              }
            })
            reject(res)
          } else if (data.code != 0) {
            wx.hideLoading()
            wx.showModal({
              confirmText: '好的',
              content: ret.data.msg || '服务器开小差去了，请重试',
              showCancel: false
            });
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        },
        complete: (res) => {

        }
      })
    })
  }

  /**
   * GET请求
   * @param url
   * @param data
   * @returns {Promise}
   */
  get(url, data = {}) {
    return this.ajax({
      url,
      data,
      method: 'GET'
    })
  }

  /**
   * POST请求
   * @param url
   * @param data
   * @returns {Promise}
   */
  post(url, data = {}) {
    return this.ajax({
      url,
      data,
      method: 'POST'
    })
  }

}

export default new Request