import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
import { nextTick } from 'vue'
import router from '@/router/index';
import i18n from '@/utils/i18n'
// 创建 axios 实例
const service: AxiosInstance = axios.create({
  timeout: 5000,  // 设置请求超时
});

// 跳转处理方法
const redirectTo = (path: string) => {
  nextTick(() => {
      router.push(path);
  });
};

// 设置请求头的 token
const setAuthHeader = (config: InternalAxiosRequestConfig) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['token'] = token;
  }
  return config;
};

// 将数据转换为 x-www-form-urlencoded 格式
const convertToFormData = (data: any) => {
  const formData = new URLSearchParams();
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      formData.append(key, data[key]);
    }
  }
  return formData;
};

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加 Authorization 头
    setAuthHeader(config);

    // 如果是 POST 请求且数据需要以 x-www-form-urlencoded 发送
    if (config.method === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded' && config.data) {
      config.data = convertToFormData(config.data);  // 将数据转换为 x-www-form-urlencoded 格式
    }

    return config;
  },
  (error: AxiosError) => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code === 1002) {
      localStorage.removeItem('token');
      ElMessage.error(response.data.message);
      redirectTo('/login');
    } else if (response.data.code !== 200) {
      console.error('Request failed:', response.data.message);
      ElMessage.error(response.data.message);
    }
    return response;
  },
  (error: AxiosError) => {
    const status = error.response?.status;

    // 统一错误处理
    const handleError = (message: string, path?: string) => {
      ElMessage.error(i18n.global.t(message));
      if (path) {
        redirectTo(path);
      }
    };

    if (status === 403) {
      handleError('Permission', '/403');
    } else if (status === 401) {
      handleError('authorization', '/login');
    } else if (status >= 500) {
      handleError('serverError');
    }

    return Promise.reject(error);
  }
);

async function request(
  method: 'get' | 'post' | 'put',
  url: string,
  params = {},
  contentType: 'application/json' | 'application/x-www-form-urlencoded' = 'application/json'
) {
  try {
    let response: AxiosResponse;

    const headers = {
      'Content-Type': contentType,
    };

    if (method === 'get') {
      response = await service.get(url, { params, headers });
    }
    else if (method === 'post') {
      response = await service.post(url, params, { headers });
    } 
    else if (method === 'put') {
      response = await service.put(url, params, { headers });
    } else {
      throw new Error(`Unsupported request method: ${method}`);
    }

    return response.data;
  } catch (error) {
    console.error('Request failed:', error);
    throw error; 
  }
}

export default request;