import axios from 'axios';
import { store } from '@/store/index';
import router from '@/router';
import { show_message } from './tdesign_tool';
const mode = import.meta.env.MODE;
const getBaseUrl = () => {
  if (mode == 'app') {
    return 'http://video_publish.test';
  } else {
    // 打包
    return '';
  }
};
const instance = axios.create({
  baseURL: getBaseUrl(),
  timeout: 60000,
  // withCredentials: mode == 'development' ? false : true,
  withCredentials: mode == 'app' ? false : true,
});
// 请求头
instance.interceptors.request.use((config: any) => {
  const lang = store.getters['language/getLang'];
  config.headers['lang'] = lang;
  return config;
});

instance.defaults.timeout = 60000;

instance.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.code === 0 || data.code == 201) {
      return data;
    } else {
      show_message(data.msg || '请求错误', 'error');
      return Promise.reject(data.msg);
    }
  },
  (err) => {
    if ('response' in err) {
      const { message: msg, status_code } = err.response.data;
      if (status_code == 403) {
        show_message('请登录');
        router.replace({
          path: '/login',
        });
        return;
      }
      show_message(msg || '请求错误', 'error');
      return err.response;
    }
  }
);

export default instance;
