const app = getApp()
const myRequest = (url,data,method,header='') =>{
  var baseUrl = app.globalData.url;
  var data = data || {};
  var token =wx.getStorageSync("token")||'';
  header = header == '' ?
   { 
     'content-type': 'application/json', 
     'Authorization':  'Bearer '+token
    } 
   : header;
  if (token == undefined) {
    wx.navigateTo({
      url: '../login/login'
    })
    return false;
  }
  if (method == 'get' && Object.keys(data).length != 0) {
    var prame = Object.keys(data).map(key => {
      return encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
    }).join('&')
    url = url + '?' + prame;
  }
  return new Promise((res,rej) => {
    wx.request({
      url: baseUrl+'/'+url,
      method:method,
      data,
      header: header,
      success(obj){
        if (obj.data.code == 200){
          res(obj.data);
        }else if(obj.data.code == 401){
          wx.reLaunch({
            url: '../login/index'
          })
          return false;
        }else{
          wx.showToast({
            title: obj.data.msg,
            icon: 'none',
          })
        }
      },
      fail(err){
        wx.reLaunch({
          url: '../login/index'
        })
        rej(err);
      }
    })
  })
}
function isLogin(){
  if (!wx.getStorageSync("token")) {
    wx.navigateTo({
      url: '../login/login'
    })
    return false;
  }
}

const updateImg = (data) =>{
  var baseUrl = app.globalData.url;
  var token = wx.getStorageSync("token");
  if (token == undefined) {
    wx.navigateTo({
      url: '../login/login'
    })
    return false;
  }
  return new Promise((res,rej) => {
    wx.uploadFile({
      url: baseUrl + '/wx/oss/upload', //开发者服务器地址
      header: {
        "Content-Type": "multipart/form-data",
        'Authorization':  'Bearer '+token
      },
      filePath: data.file,//要上传文件资源的路径
      name: "file",//文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
      success: (obj) => {
        var list = JSON.parse(obj.data);
        res(list.data);
   
      },
      fail(err){
        rej(err);
      }
    })
  })
}

module.exports = {
  myRequest:myRequest,
  isLogin:isLogin,
  updateImg:updateImg
}

