//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    this.changeToken();
    // 获取用户信息
  },
  changeToken() {
    let url = '/api/user/codeToToken', t = this;
    wx.login({
      success: function (res) {
        console.log(res)
        t.post(url, { code: res.code }).then((r) => {
          wx.setStorageSync('token', r.userInfo.token)
        })
      }
    })
  },
  post: function (url, data, showLoad) {
    /** 
  * 自定义post函数,返回Promise
  * +-------------------
  * @param {String}      url 接口网址
  * @param {arrayObject} data 要传的数组对象 like: {name: 'name', age: 32}
  * +-------------------
  * @return {Promise}    promise 返回promise供后续操作
  */
    if (showLoad == undefined || showLoad){
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.showNavigationBarLoading()
    var promise = new Promise((resolve, reject) => {
      //init
      let that = this,token=wx.getStorageSync('token'),header={
        'content-type': 'application/x-www-form-urlencoded'
      },postData;
      data.header ? (token ? (header['token'] = token, delete data.header):setTimeout(()=>{
        wx.navigateTo({
          url: '/pages/register/register',
        })
      },1100)):""
      //网络请求  
      console.log(header)
      wx.request({
        url: this.globalData.baseUrl + url,
        data: data,
        method: 'POST',
        header: header,
        success: function (res) {//返回取得的数据
          if (res.data.code == '1') {
            resolve(res.data.data);
          } else if (res.data.code == '201') {
            resolve(res.data);
          } else {
            wx.showToast({
              title: res.data.msg,
              icon:'none',
              duration: 1200
            })
            reject(res.data)
          }
          (showLoad || showLoad == undefined) ? wx.hideLoading() : "";
          wx.hideNavigationBarLoading()
        },
        fail: function (e) {
          reject('网络出错');
          (showLoad || showLoad == undefined) ? wx.hideLoading() : "";
          wx.hideNavigationBarLoading()
        }
      })
    });
    return promise;
  },
  globalData: {
    userInfo: null,
    baseUrl:'http://lqz.w.brotop.cn'
  }
})