import appConfig from '@/static/config/index.js';
import User from '@/request/user';
export function getBaseUrl() {
  if (process.env.NODE_ENV === 'development') {
    return appConfig.devApi;
  } else {
    return appConfig.prodApi;
  }
}
module.exports = (vm) => {
  uni.$u.http.setConfig((config) => {
    config.baseURL = getBaseUrl();
    // showLoading: process.env.NODE_ENV === 'development',
    config.method = 'POST';
    // 设置为json,返回后会对数据进行一次JSON.parse()
    config.dataType = 'json';
    config.timeout = 3000; // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
    // 配置请求头信息
    config.header = {
      'Content-Type': 'application/json', // 'application/x-www-form-urlencoded'
    };
    return config;
  });
  // 请求拦截
  uni.$u.http.interceptors.request.use(
    (config) => {
      // 可使用async await 做异步操作
      uni.showLoading({
        title: '加载中',
        mask: true,
      });
      let Authorization = uni.getStorageSync(`Authorization`);
      const configUrl = [
        '/weixin/login',
        '/weixin/getShop',
        '/weixin/infoByShop',
        '/application/getData',
        '/weixin/getArea',
      ];
      if (Authorization && configUrl.indexOf(config.url) == -1) {
        config.header.Authorization = Authorization;
      }
      return config;
    },
    (config) => {
      // 可使用async await 做异步操作
      return Promise.reject(config);
    }
  );
  // 响应拦截
  uni.$u.http.interceptors.response.use(
    (response) => {
      uni.hideLoading();

      /* 对响应成功做点什么 可使用async await 做异步操作*/
      if (response.data.code !== 200) {
        const phoneNumber = uni.getStorageSync('phoneNumber');
        if (response.data.code == 401 && phoneNumber) {
          User.getAuthorization(phoneNumber);
        }
        uni.showToast({
          title: response.data.msg,
          icon: 'none',
          duration: 2000,
        });
        return Promise.reject(response);
      } // return Promise.reject 可使promise状态进入catch

      return response;
    },
    (response) => {
      uni.hideLoading();
      /*  对响应错误做点什么 (statusCode !== 200)*/
      return Promise.reject(response);
    }
  );
};