import router from '@/router'
import { deleteUserMsg, getUserMsg } from '@/utils/userMsg'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { Toast } from 'vant'

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

baseAxios.interceptors.response.use(
  (baseRet: AxiosResponse) => {
    const ret = baseRet.data as iRet
    if ([504, 503].includes(ret.code)) {
      Toast.fail(ret.msg)
      deleteUserMsg()
      router.push({
        name: 'Login',
      })
    } else if (ret.code === 1000) {
      Toast('您好，非常抱歉，该网点暂无营业人员。')
    } else if (ret.code !== 200) {
      // console.log(baseRet, 'show baseret');
      if (baseRet.config.url === '/staff/enable_live') return baseRet.data
      Toast.fail(ret.msg)
    }
    return baseRet.data
  },
  (error) => {
    Toast.fail(error.message)
    throw new Error(error)
  },
)

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

export default <T = any>(config: AxiosRequestConfig) => {
  const token = getUserMsg()?.token
  return (baseAxios({
    ...config,
    headers: {
      ...config.headers,
      Authorization: 'Bearer ' + token,
    },
  }) as unknown) as Promise<{
    code: number
    data: T
    msg: string
  }>
}
