import axios from 'axios';
import router from '@/router';
import { getToken } from '@/utils/auth';
import { Modal, notification } from 'ant-design-vue';
import type { AxiosRequestConfig } from "axios";
import type { ApiResponse } from "@/api/common/model";

const errCodeMap: { [key: string]: string } = {
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
};

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers = config.headers || {};
    config.headers['Accept-Language'] = 'zh-CN';

    const token = getToken();
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log(response);
    const code = response.data.code || 200;
    const data = response.data;

    switch (code) {
      case 200:
        return data ?? response;
      case 401:
        Modal.error({
          title: '系统提示',
          content: '登录状态已过期，请重新登录',
          onOk: () => {
            router.push('/login')
          }
        })
        return Promise.reject(data);
      default:
        const errMsg = errCodeMap[code] || data.msg || errCodeMap['default'];
        notification.error({
          message: '请求错误',
          description: errMsg,
        });
        return Promise.reject(data);
    }
  },
  error => {
    error.message = error.code === "ECONNABORTED" ? '请求超时，请稍后重试' : error.message;

    // 网络/服务器错误统一处理
    notification.error({
      message: "网络错误",
      description: error.message,
    });
    return Promise.reject(error);
  }
);

// 类型检查
function request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service(config) as unknown as Promise<ApiResponse<T>>;
}

export default request;
// export default service;