import axios from 'axios';
import { generateSign } from '@/utils/hmac';
import { showMessage } from '@/utils/common';

// 创建 axios 实例
const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_API || '/api', // 根据环境变量配置
  timeout: 100000 // 超时时间
});

// 请求拦截器
http.interceptors.request.use(
  async (config) => {
    const { url } = config;
    const extendParams = {
      msgId: '730d7bbaf1914e8ba60e9c922d58a8c8',
      url: url as string,
      nonce: Date.now().toString()
    };
    const signature = generateSign(extendParams);
    Object.assign(config.headers, extendParams, { signature });
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response: any) => {
    const res = response.data;
    // 你可以根据后端约定的 code 来处理
    if (res.state !== 200) {
      // showMessage({
      //   type: 'error',
      //   message: response.msg || '请求失败'
      // });
      return Promise.reject(res.msg);
    }
    return response.data; // 正常返回数据
  },
  (error) => {
    let message: string = '';
    if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 401:
          message = '没有权限';
          break;
        case 404:
          message = '接口不存在';
          break;
        case 500:
          message = '服务器错误';
          break;
        default:
          message = error.message;
      }
    } else {
      message = '本月次数已用完';
    }
    showMessage({
      type: 'warning',
      message
    });
    return Promise.reject(error);
  }
);

export function uploadFile(file: File, extraData: Record<string, any> = {}) {
  const formData = new FormData();
  formData.append('file', file);

  // 如果还要附带额外参数
  Object.keys(extraData).forEach((key) => {
    formData.append(key, extraData[key]);
  });

  return http.post('/v3/oss/common/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

export default http;
