/*
 * @Descripttion:
 * @Author: zenghua.wang
 * @Date: 2022-02-23 21:12:37
 * @LastEditors: zenghua.wang
 * @LastEditTime: 2025-02-18 09:47:41
 */
import axios from 'axios';
import { ElNotification } from 'element-plus';
import router from '@/router';
import { isEmpty } from '@/utils';
import { useUserStore } from '@/store/modules/user';

const { VITE_APP_BASE_API, VITE_APP_UPLOAD_API, VITE_APP_DICDATA_API } = import.meta.env;

/**
 * 创建axios实例
 */
const publicAxios = axios.create({
  baseURL: VITE_APP_BASE_API, // API请求的默认前缀
  timeout: 30000,
});
/**
 * 异常拦截处理器
 * @param error
 * @returns
 */
const errorHandler = async (error) => {
  const { response } = error;
  const UserStore = useUserStore();
  if (response && response.status) {
    switch (response.status) {
      case 401:
        await UserStore.logout();
        router.push('/login');
        break;
      default:
        break;
    }
  }
  return Promise.reject(error?.response?.data);
};
/**
 * 请求拦截器
 */
publicAxios.interceptors.request.use(async (config) => {
  const UserStore = useUserStore();
  switch (config.apisType) {
    case 'upload': {
      config.baseURL = VITE_APP_UPLOAD_API;
      config.headers['Content-Type'] = config.uploadType;
      break;
    }
    case 'dicData': {
      config.baseURL = VITE_APP_DICDATA_API;
      break;
    }
    default: {
      config.baseURL = VITE_APP_BASE_API;
    }
  }
  if (UserStore.hasToken()) {
    config.headers['authorization'] = config.headers['authorization'] ?? UserStore.token;
    config.headers['cache-control'] = 'no-cache';
    config.headers.Pragma = 'no-cache';
  }
  if (config.method === 'POST' || config.method === 'DELETE') {
    config.headers.Accept = 'application/json';
  }
  return config;
}, errorHandler);

/**
 * 返回结果处理
 * @param res
 * @returns
 */
const formatResult = async (res) => {
  const code = res.data.code || res.status;
  // console.info('formatResult', code)
  const UserStore = useUserStore();
  switch (code) {
    case 200:
    case 0:
      // code === 0 或 200 代表没有错误
      return res.data || res.data.data || res;
    case 500:
    case 1:
      // code === 1 或 500 代表存在错误
      ElNotification.error(res.data.msg);
      break;
    case 401:
      // code === 401 代表登录过期
      await UserStore.logout();
      router.push('/login');
      break;
    default:
      ElNotification.error(res.data.msg);
      break;
  }
};
/**
 * 响应拦截器
 */
publicAxios.interceptors.response.use((response) => {
  const { config } = response;
  // console.info('响应拦截器', response);
  if (config?.responseType) {
    return response;
  }
  const token = response?.headers['authorization'];
  if (!isEmpty(token)) {
    const UserStore = useUserStore();
    UserStore.setToken(token);
  }
  const result = formatResult(response);
  if (result) {
    return result;
  }
  throw new Error(response.data.msg);
}, errorHandler);

export default publicAxios;
