import config from '../config/config'

export const api = (url, method = 'GET', params = {}, type = 'data') => {
  return new Promise((resolve, reject) => {
    wx.request({
      method: method,
      url: url.startsWith("http") ? url : config.baseUrl + url,
      data: params,
      timeout: 60000 * 5,
      header: {
        ...config.baseHeader,
        "id": wx.getStorageSync('id'),
        "sessionKey": wx.getStorageSync("sessionKey"),
        "wt": wx.getStorageSync('token'),
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'content-type': type === 'json' ? 'application/json' : 'application/x-www-form-urlencoded'
      },
      success: (result) => {
        // 请求成功，就将成功的数据返回出去
        if (result.statusCode == 200) {
          if (result.data.code === 401 || result.data.msg.indexOf('token 无效') > -1) {
            wx.showModal({
              title: '提示',
              content: '登录过期，请重新登陆',
              confirmText: '去登录',
              complete: (res) => {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../login/index',
                  })
                }
              }
            })
          } else {
            resolve(result.data)
          }
        } else {
          wx.showModal({
            content: result.data.msg
          })

        }

      },
      fail: (err) => {
        reject(err)
      },
      // 不管请求成功还是失败，都会触发
      complete: () => {
        wx.hideLoading()
      }
    });
  });
}