const ui = require('./ui');
 const BASE_URL = 'https://www.dghdwy.cn/monitor/api/erp1/we'
  // const BASE_URL = 'http://119.29.97.109:8080/monitor/api/erp1/we' 


function request(obj) {
    return new Promise(function(resolve, reject) {
      if(obj.showLoading){
        ui.showLoading(obj.message? obj.message : '加载中...');
      } 
      var data = {};
      if(obj.data) {
        data = obj.data;
      }
      var contentType = 'application/json';
      if(obj.contentType){
        contentType = obj.contentType;
      } 
  
      var method = 'post';
      if(obj.method){
        method = obj.method;
      }
  
      wx.request({
        url: BASE_URL + obj.url,
        data: data,
        method: method,
        //添加请求头
        // header: {
        //   'Content-Type': contentType ,
        //   'token': wx.getStorageSync('token') //获取保存的token
        // },
        //请求成功
        success: function(res) {
          if (res.statusCode == 200) {
            resolve(res);
          } else if (res.statusCode == 500) {//授权失效
            reject("登录已过期");
            jumpToLogin();//跳转到登录页
          } else {
            //请求失败
            reject("请求失败：" + res.statusCode)
          }
        },
        fail: function(err) {
          reject("服务器连接异常，请检查网络再试");
        },
        complete: function() {
          ui.hideLoading();
        }
      })
    });
  }
  
 
  //跳转到登录页
  function jumpToLogin(){
    wx.reLaunch({
      url: '/pages/index/index',
    })
  }
  
  module.exports = {
    request,
  }