import { isWithoutToken } from './help'
import { getUserInfo, signoutRedirect } from '@/utils/oidc/index.js'

export function setupInterceptor(service) {
  service.interceptors.request.use(
    async(config) => {
      // 防止缓存，给get请求加上时间戳
      if (config.method === 'get') {
        config.params = { ...config.params, t: new Date().getTime() }
      }
      // 处理不需要token的请求
      if (isWithoutToken(config)) {
        return config
      } else {
        const userInfo = await getUserInfo()
        if (userInfo) {
          const { token_type, access_token } = userInfo
          config.headers.Authorization = `${token_type} ${access_token}`
          const { VITE_CLIENT_ID } = import.meta.env
          config.headers['Client-Id'] = VITE_CLIENT_ID
          return config
        } else {
          signoutRedirect()
          return Promise.reject({ response: { status: 401, message: '未登录' }})
        }
      }
    },
    (error) => Promise.reject(error)
  )

  service.interceptors.response.use(
    (response) => {
      const { method } = response?.config
      const { code } = response?.data
      switch (code) {
        case 0:
          if (method !== 'get') {
            $message.success(response.data.msg)
          }
          break
        case -1:
          $message.error(response.data.msg)
          break
        case 401:
          // 未登录（可能是token过期或者无效了）
          signoutRedirect()
          break
        default:
          break
      }
      return response?.data
    },
    (error) => {
      const { status } = error.response
      if (status === 401) {
        signoutRedirect()
      } else if (status === 403) {
        $message.error('暂无权限访问，请联系管理员')
        return Promise.reject(error)
      } else {
        return Promise.reject(error)
      }
    }
  )
}
