// vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
const install = (Vue, vm) => {
  Vue.prototype.$u.http.setConfig({
    baseUrl: vm.config.baseUrl,
    loadingText: '努力加载中~',
    loadingTime: 800
  });
  // 请求拦截,配置Token等参数
  Vue.prototype.$u.http.interceptor.request = (config) => {
    if (vm.vuex_token) {
      config.header.Authorization = `Bearer ${vm.vuex_token}`;
    }
    // 请求地址加时间戳
    config.url = config.url + '?t=' + Date.now();
    let noTokenList = [
      '/client/wechat/h5/code/',
      '/client/auth/sendSmsCodeV2',
      '/client/auth/verifyCodeV2',
      '/client/auth/loginToWxOpenId',
      '/client/auth/sendSmsCodeV3',
      '/client/auth/loginToMobile'
    ];
    if (noTokenList.includes(config.url)) config.header.noToken = true;
    return config;
  };
  // 响应拦截,判断状态码是否通过
  Vue.prototype.$u.http.interceptor.response = (res) => {
    if (res.code == 200) {
      return res;
    } else if (res.code == 401 || res.code == 400) {
      const backUrl = location.href,
        openidPage = vm.config.onlyWxLogin, // 只需要传openid的页面集合
        needValidPage = openidPage.filter((item) => backUrl.indexOf(item) > -1); // 是否为需要验证的页面集合
      // 判断浏览器
      const ua = window.navigator.userAgent.toLowerCase();
      // 微信中打开
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        // 防止重复跳转
        if (backUrl.indexOf('backUrl') === -1) {
          vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl: encodeURIComponent(backUrl), loginType: needValidPage.length ? 2 : 1 });
        }
      } else {
        // 普通浏览器中打开
        if (backUrl.indexOf('backUrl') === -1) {
          localStorage.setItem('backUrl', encodeURIComponent(backUrl));
        }
        uni.showModal({
          title: '提示',
          content: '未查询到登录信息或信息已失效, 请重新登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              localStorage.removeItem('lifeData');
              uni.redirectTo({
                url: '/pages/center/phoneLogin/phoneLogin'
              });
            }
          }
        });
      }
      return false;
    } else {
      // 用来判断时候需要使用当前提示框
      const noTipMsg = ['无任何订单'];
      const index = noTipMsg.findIndex((item) => res?.msg.indexOf(item) > -1);
      if (index < 0) {
        uni.showToast({
          title: res.msg || '程序错误!',
          duration: 2000,
          icon: 'none'
        });
      }
      return false;
    }
  };
};

export default {
  install
};