
import {formatUrl} from "../utils/formatParams"
import {getCurrentPageUrl} from "../utils/getUrl"
import Dialog from '@vant/weapp/dialog/dialog';
import {hostConfig} from "../utils/config"
let isLock=false;
let host=hostConfig().host;
//loding 是否加loading弹窗
function request(url, method, data, loding = false) {
    let whitelist = ["/login/wechat_mobile_login", '/login/mobile_login','/code/phone','/patient/index',"/popup","/sign/im"];//接口白名单;
    if(whitelist.indexOf(url) != -1){
        isLock=false;
    }
   if(isLock) {
       return Promise.reject("请求被lock,正常报错");
   };
  if (loding) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
   let token='';
  const { envVersion } = wx.getAccountInfoSync().miniProgram;
  if(envVersion=='release'){
    token = wx.getStorageSync('AUTH_TOKEN');
  }else{
    token = wx.getStorageSync('DEV_AUTH_TOKEN');
      
  }
  
  if (!token) {
    let freelist = ["/login/wechat_mobile_login", '/login/mobile_login','/code/phone','/patient/index',"/popup","/sign/im"];//接口白名单
    let currentUrl=getCurrentPageUrl();
    if (freelist.indexOf(url) == -1 &&  currentUrl!="/pages/index/index") {
        let redirectUrl=formatUrl();
        // console.log("currentUrl:"+currentUrl);
        // console.log("urlreq"+url);
        // console.log('url----:'+redirectUrl);
        if(!isLock){ 
          isLock=true;
          wx.reLaunch({
            url: '/patient/pages/login/login?redirectUrl='+redirectUrl
          });
        } 
    }
  }
  let header = {
    'content-type': 'application/json',
    'Authorization': 'Bearer ' + token
  }
  return new Promise((resolve, reject) => {
      console.log('1111111111111111111');
      console.log(host + url)
    wx.request({
      url: host + url,
      method: method,
      data: data,
      header: header,
      success: function (res) {
        
        var Authorization_token = res.header.Authorization;
        if (Authorization_token) {
            const { envVersion } = wx.getAccountInfoSync().miniProgram;
            if(envVersion=='release'){
                wx.setStorageSync('AUTH_TOKEN', Authorization_token);
            }else{
                wx.setStorageSync('DEV_AUTH_TOKEN', Authorization_token); 
                
            }
         //当token快过期时，服务器会返回新token，本地刷新
        }
        if (loding) {
          wx.hideLoading()
          wx.stopPullDownRefresh();
        }
        let msgUrl="/patient/message/system/last";
        if (Number(res.data.code) == 200 || Number(res.data.code) == 422) {
          resolve(res.data.data);
         
        }else if(Number(res.data.code) == -1){
          let list = ["/patient/order/inquiry", '/patient/order/product', '/patient/order/prescription','/patient/order/detection'];
          let index=url.lastIndexOf("/");
          let urlString=url.substring(0,index);
          if (list.indexOf(urlString) != -1 && method == "GET") {
              Dialog.confirm({
                title: '温馨提示',
                showCancelButton: false,
                confirmButtonText: "确定",
                message: '订单无法查看，点击前往首页',
              }).then(() => {
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              })
            }else{
              wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000
              })
            }
        }else if(Number(res.data.code) == 406 && msgUrl.indexOf(url)!=-1){
          reject(res.data.data)
        }else if (Number(res.data.code) == 401 || Number(res.data.code) == 403 || Number(res.data.code) == 405 || Number(res.data.code) == 406) {
            let redirectUrl=formatUrl();
            if(!isLock){
                const { envVersion } = wx.getAccountInfoSync().miniProgram;
                if(envVersion=='release'){
                    wx.setStorageSync('AUTH_TOKEN','');
                }else{
                    wx.setStorageSync('DEV_AUTH_TOKEN','');
                    
                }
            //  wx.setStorageSync('AUTH_TOKEN','');
              isLock=true;
              wx.reLaunch({
                url: '/patient/pages/login/login?redirectUrl='+redirectUrl
              });
            }
            reject(res.data);
           
        }else if(Number(res.data.code) == 500){
            reject(res.data);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
        isLock=false;
        reject(res.data);
      },
      fail: function (res) {
        if (loding) {
            wx.hideLoading()
            wx.stopPullDownRefresh();
          }
          console.log(res)
          console.log(2222222222222222);
        // wx.showToast({
        //   title: '网络错误，请稍后再试',
        //   icon: 'none',
        //   duration: 2000
        // })
        // reject(false)
      }
    })
  })
  
}

function uploadFile(url, data) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: host + url,
      formData: data,
      success(res) {
        const result = res.data
        resolve(result)
      },
      // fail(res){
      //   wx.showToast({
      //     title: '网络错误，请稍后再试',
      //     icon: 'none',
      //   })
      //   reject(false)
      // }
    })
  })
}
module.exports = {
  request,
  uploadFile
}