import axios from 'axios'
import router from '../router'
import { getToken, removeToken } from './auth'
import { resetScreenAutoLoginState } from './screenAutoLogin'
import { tansParams } from './ruoyi'

/** 避免多个接口同时 401 重复跳转登录 */
let isRedirectingLogin = false

function redirectToLogin() {
  if (isRedirectingLogin) return
  if (router.currentRoute.value.path === '/login') return
  isRedirectingLogin = true
  removeToken()
  resetScreenAutoLoginState()
  const redirect = router.currentRoute.value.fullPath
  router
    .replace({
      path: '/login',
      query: redirect && redirect !== '/login' ? { redirect } : {}
    })
    .finally(() => {
      isRedirectingLogin = false
    })
}

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 60000
})

service.interceptors.request.use((config) => {
  const token = getToken()
  if (token && config.headers?.isToken !== false) {
    config.headers.Authorization = `Bearer ${token}`
  }
  if (config.method === 'get' && config.params) {
    let url = `${config.url}?${tansParams(config.params)}`
    url = url.slice(0, -1)
    config.params = {}
    config.url = url
  }
  return config
})

service.interceptors.response.use(
  (res) => {
    const code = res.data?.code ?? 200
    if (code === 401) {
      redirectToLogin()
      return Promise.reject(new Error('未登录或会话已过期，请重新登录'))
    }
    if (code !== 200) {
      const msg = res.data?.msg || '请求失败'
      return Promise.reject(new Error(msg))
    }
    return res.data
  },
  (error) => {
    const status = error.response?.status
    const bizCode = error.response?.data?.code
    if (status === 401 || bizCode === 401) {
      redirectToLogin()
      return Promise.reject(new Error('未登录或会话已过期，请重新登录'))
    }
    let message = error.message || '网络异常'
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '接口请求超时'
    }
    console.error('[ruoyi-screen]', message)
    return Promise.reject(error)
  }
)

export default service
