const install = (Vue, vm) => {
  const httpConfig = {
    baseUrl: vm.config.baseUrl,
    loadingText: '努力加载中~',
    loadingTime: 800,
    originalData: true,
    dataType: 'text'
  };

  Vue.prototype.$u.http.setConfig(httpConfig);

  let isRefreshing = false;

  Vue.prototype.$u.http.interceptor.request = (config) => {
    const { url } = config;
    const { vuex_token } = vm;

    if (vuex_token) {
      config.header.Authorization = `Bearer ${vuex_token}`;
    }

    config.url = `${url}?t=${Date.now()}`;

    const noTokenList = [
      '/client/wechat/h5/code/',
      '/client/auth/sendSmsCodeV2',
      '/client/auth/verifyCodeV2',
      '/client/auth/loginToWxOpenId',
      '/client/auth/sendSmsCodeV3',
      '/client/auth/loginToMobile'
    ];

    if (noTokenList.includes(url)) {
      config.header.noToken = true;
    }

    return config;
  };

  Vue.prototype.$u.http.interceptor.response = (res) => {
    const { data } = res;

    if (data) {
      const jsonBigint = require('json-bigint')({ storeAsString: true });
      res = jsonBigint.parse(data);
      const { code, msg } = res;

      if (code === 200) {
        return res;
      } else if (code === 401 || (code === 400 && msg === '令牌不能为空')) {
        if (!isRefreshing) {
          login(vm);
          isRefreshing = true;
        }
        return false;
      } else {
        const noTipMsg = ['无任何订单'];
        const index = noTipMsg.findIndex((item) => msg?.indexOf(item) > -1);

        if (index < 0) {
          uni.showToast({
            title: res.msg || '程序错误!',
            duration: 2000,
            icon: 'none'
          });
        }

        return false;
      }
    } else {
      uni.showToast({
        title: '程序错误!',
        duration: 2000,
        icon: 'error'
      });

      return false;
    }
  };
};

const login = (vm) => {
  const backUrl = location.href;
  const openidPage = vm.config.onlyWxLogin;
  const needValidPage = openidPage.filter((item) => backUrl.includes(item));

  const ua = window.navigator.userAgent.toLowerCase();

  if (ua.includes('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'
          });
        }
      }
    });
  }
};

export default {
  install
};