import storage from '../storage/index.js';
//把配置项单独处理
let server_url = ' '; // 请求地址
let token = ' '; // 凭证

server_url = import.meta.env.VITE_APP_BASE_API; //环境配置
function service(options = {}) {
  storage.get('token') && (token = storage.get('token'));
  options.url = `${server_url}${options.url}`;
  if (!options.noToken) {
    if (!token.trim()) {
      uni.redirectTo({
        url: '/pages/login/login'
      });
    } else {
      options.header = {
        Authorization: `Bearer ${token}`
      };
    }
  }
  return new Promise((resolved, rejected) => {
    //成功
    options.success = res => {
      if (res.data.code == 'E403') {
        // 未登录
        uni.showToast({
          title: res.data.message,
          icon: 'none'
        });
        uni.redirectTo({
          url: '/pages/login/login'
        });
        //请求成功
        resolved(res.data);
      } else {
        //请求成功
        resolved(res.data);
      }
    };
    //错误
    options.fail = err => {
      rejected(err); //错误
    };
    uni.request(options);
  });
}
export default service;
