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

export interface ResopnseType<T> {
  reason: string
  message: string
  data: T
  ts: string
}
// export const YCODE_BASEURL: string = import.meta.env.VITE_YCODE_BASEURL;

// https://custom-chart-pre-api.shiyue.com

export const YCODE_BASEURL: string = 'https://custom-chart-pre-api.shiyue.com'

const requestType  = {
  base: YCODE_BASEURL,
};

const baseAxios: AxiosInstance = axios.create({
  baseURL: '',
  timeout: 100000,
  withCredentials: true,
});

const errorHandle = (error: AxiosError) => {
  if (error.response) {
    const status = error.response?.status;
    switch (status) {
      case 401:
        message.warning('请先登录');
        window.location.href = `${YCODE_BASEURL}/login?redirect=${encodeURIComponent(window.location.href)}`;
        break;
      case 403:
        message.warning('权限不足');
        break;
      case 500:
        message.warning('服务器出错了……  (>_<)');
        break;
      default:
        message.warning('服务器出错了……  (>_<)');
        break;
    }
    return Promise.reject(error);
  }
  message.error(error.message);
  return Promise.reject(error);
};
//响应拦截器
baseAxios.interceptors.response.use((response: AxiosResponse) => {
  const { data, status } = response;

  if (status !== 200) {
    return Promise.reject(data);
  }
  if (data.code) {
    if (data.code === 200) {
      return data;
    } else {
      message.warning(data.message);
      return Promise.reject(data);
    }
  }
}, errorHandle);

type RequestConfig =  Omit<AxiosRequestConfig, 'baseURL'> & { baseURL?: keyof typeof requestType }
const request = <T = any>(config: RequestConfig) => {
  const host = requestType[config.baseURL || 'base'];
  return new Promise<T>((resolve, reject) => {
    baseAxios
      .request<any, T>({ ...config, baseURL: host })
      .then((res: T) => {
        resolve(res);
      })
      .catch((err: unknown) => {
        reject(err);
      });
  });
};

const get = <T = any>(config?: RequestConfig) => {
  return request<ResopnseType<T>>({
    ...config,
    method: 'GET',
  });
};

const post = <T = any>(config?: RequestConfig) =>
  request<ResopnseType<T>>({
    ...config,
    method: 'POST',
  });

const put = <T = any>(config?: RequestConfig) =>
  request<ResopnseType<T>>({
    ...config,
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
  });

const del = <T = any>(config?: { url: string }) => request<ResopnseType<T>>({ ...config, method: 'DELETE' });

export { get, post, del, put, request };
