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', 'token':  ''+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 == 0){
          res(obj);
        }else if(obj.data.code == -5){
          res(obj);
        }else if(obj.data.code == -3){
          wx.navigateTo({
            url: '../login/login'
          })
          return false;
        }else{
          wx.showToast({
            title: obj.data.msg,
            icon: 'none',
          })
        }
      },
      fail(err){
        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 + '/file/uploadImg', //开发者服务器地址
      header: {
        "Content-Type": "multipart/form-data",
        "token": token
      },
      filePath: data.file,//要上传文件资源的路径
      name: "files",//文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
      success: (obj) => {
        var list = JSON.parse(obj.data);
        res(list.data);
        // this.setData({
        //   updateFile: res.data.data
        // })
      },
      fail(err){
        rej(err);
      }
    })
  })
}

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

