import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage  } from 'element-plus'

const baseAxios = axios.create({
  baseURL: '/proxyApi/v1',
})

/* 异常处理 */
baseAxios.interceptors.response.use(
  (baseRet: AxiosResponse) => {
    const ret = baseRet.data as iRet
    if (ret.code !== 200) {
      ElMessage.error(ret.msg)
    } 
    return baseRet.data
  },
  (error) => {
    ElMessage.error(error.message)
    throw new Error(error)
  },
)

export interface iRet<T = any> {
  code: number
  data: T
  msg: string
}

export default <T = any>(config: AxiosRequestConfig) => {
  return (baseAxios({
    ...config,
  }) as unknown) as Promise<{
    code: number
    data: T
    msg: string
  }>
}
