import Service from "./request/index";
import { getAuthToken } from "~/utils/auth";

import { router } from "~/router"

import { showFailToast } from "vant"

const global = window as any;
const service = new Service({
  baseURL: 'http://stocknew.test241.wanyuhengtong.com/',
  timeout: 5000,
  interceptors: {
    requestInterceptor(config) {
      const token = getAuthToken()
      if(token && config.data){ config.data.token = token }
      return config;
    },
    responseInterceptor(response) {
      const { code, data, message } = response.data as any;

      if (code >=100 && code <= 104) {
        // TODO: 登出
        showFailToast('登录失效')
        router.push('/login')
      } else if(code != 0){
        showFailToast(message)
      }

      return response;
    },
    responseInterceptorCatch(error) {
      const status = error.response?.status;
      switch (status) {
        case 401:
          global.$message.error("服务器出错!");
          break;
      }
      return error;
    },
  },
});

export default service;
