import { message } from 'ant-design-vue';
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';

// 创建HTTP实例
const http: HttpInstance = axios.create({
  baseURL: import.meta.env.ENV_HTTP_BASE,
  adapter: 'fetch',
  timeout: 30_000,
});
export default http;

// 添加请求拦截器
http.interceptors.request.use(
  async (config) => {
    try {
      let token = '';
      let tenantId = '';

      // 开发环境处理逻辑
      if (import.meta.env.DEV) {
        try {
          token = import.meta.env.ENV_DEV_TOKEN;
          tenantId = import.meta.env.ENV_DEV_TENANT_ID;
        } catch (error) {
          console.error('获取开发环境token失败:', error);
        }
      } else {
        // 生产环境直接从localStorage获取
        const localStorageData = JSON.parse(
          localStorage.getItem('VWED_AMR调度系统__PRODUCTION__3.7.1__COMMON__LOCAL__KEY__') || '{}',
        );
        token = localStorageData?.value?.TOKEN__?.value || '';
        tenantId = localStorageData?.value?.TENANT_ID?.value || '';
      }

      config.headers['x-access-token'] = token;
      config.headers['x-tenant-id'] = tenantId;
      console.log(config);
    } catch (error) {
      console.error(error);
    }
    return config;
  },
  (error) => Promise.reject(error.message),
);

// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    const res = <CommonRes>response.data;
    if (res?.success) return <never>res.result;
    const hint = res?.message ?? '未知异常';
    message.error(hint);
    return Promise.reject(hint);
  },
  (error) => {
    const hint = error.response.data?.message || error.message;
    message.error(hint ?? '未知异常');
    return Promise.reject(hint);
  },
);

type HttpInstance = Omit<AxiosInstance, 'get' | 'post'> & {
  get: <D = void>(url: string, config?: AxiosRequestConfig) => Promise<D | undefined>;
  post: <D = void, B = unknown>(url: string, body?: B, config?: AxiosRequestConfig<B>) => Promise<D | undefined>;
};

type CommonRes<T = void> = {
  code: number;
  success: boolean;
  result: T | undefined;
  message: string;
};
