import axios from 'axios';
import { merge } from 'lodash-es';
import { Message } from 'element-ui';
// 正常返回
export const CODE_200 = '0';

const instance = axios.create();

const DEFAULT_OPTIONS = {
  baseURL: import.meta.env.VITE_APP_BASE_URL
};

const pendingRequests = {};
const getPendingRequestsKey = (config) => {
  const params = config.method === 'post' ? config.data : config.params;
  const paramsString = params ? `-${JSON.stringify(params)}` : '';
  return `${config.method}-${config.url}${paramsString}`;
};
instance.interceptors.request.use(
  (config) => {
    const key = getPendingRequestsKey(config);

    if (pendingRequests[key]) {
      // 如果请求已经存在，取消当前请求
      return Promise.reject(new axios.Cancel('Duplicate request canceled'));
    }

    // 存储当前请求
    pendingRequests[key] = true;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  (res) => {
    const key = getPendingRequestsKey(res.config);

    // 请求完成，移除记录
    delete pendingRequests[key];
    if (res.status === 200 || res.status === 201) {
      if (res.data.code === CODE_200) {
        return Promise.resolve(res.data);
      } else if (res.data.msg) {
        Message.error(res.data.msg);
      }
      return Promise.reject(res.data);
    } else {
      return Promise.reject(res);
    }
  },
  (err) => {
    return Promise.reject(err);
  }
);

export default function apiAxios(options) {
  /**
   * Content-Type
   * form: application/x-www-form-urlencoded;charset=UTF-8
   * json: application/json;charset=utf-8
   * multipart: multipart/form-data
   * default: application/json;charset=utf-8
   */
  const axiosOptions = merge({}, DEFAULT_OPTIONS, options);
  return instance(axiosOptions);
}
