// wx.request封装
const app = getApp()
const request = async (url, options, contentType) => {
  let openId;
  await new Promise(resolve => {
    let tiems = setInterval(() => {
      // 如果此时openid已被赋值
      openId = app.globalData.openid; // data里要固定添加openid（项目需要）
      if (!!app.globalData.openid) { 
        clearInterval(tiems)
        resolve()
      }
    }, 500);
  })
  !!contentType?contentType:contentType="application/json"
  return new Promise( (resolve, reject) => {
    wx.request({
      url: `${app.mangerUrl}${url}?openId=${openId}`,//获取域名接口地址
      method: options.method, //配置method方法
      data:options.data, 
      //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
      header: {
        'Content-Type': contentType,
        'Cookie':wx.getStorageSync('cookieKey')||''                     
      },
      success(request) {
        if (request && request.header && request.header['Set-Cookie']) {
          if(request.header['Set-Cookie'].indexOf("SESSION")==0){
            wx.setStorageSync('cookieKey', request.header['Set-Cookie']); //保存Cookie到Storage
          }
        }
        //监听成功后的操作
        resolve(request.data)
      },
      fail(error) {
      //返回失败也同样传入reject()方法
        reject(error.data)
      }
    })
  })
}
//封装get方法
const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}
//封装post方法
const post = (url, options,contentType) => {
  return request(url, {
    method: 'POST',
    data: options
  },contentType)
}
//封装put方法
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}
//封装remove方法
// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}
//抛出wx.request的post,get,put,remove方法
module.exports = {
  get,
  post,
  put,
  remove
}