import router from '@/router'
import Axios from 'axios'
import { showError } from '@/utils/ui.ts'

const axios = Axios.create({
  baseURL: import.meta.env.VITE_API_BASE,
  timeout: 300000, //凯哥让改的超时时间
})

const TOKEN_KEY = 'token'

export function setToken(token: string) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

axios.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers['jwt-token'] = token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)
axios.interceptors.response.use(
  (response) => {
    // 1. 判断响应码
    const data = response.data

    if (data && typeof data === 'object' && typeof data.code === 'number') {
      // token 过期
      if (data.code === 403) {
        router.replace({ path: '/user/login' })
        return Promise.reject(data)
      }
      if (data.code !== 200) {
        showError(data.message)
        return Promise.reject(data)
      }
    }
    return data
  },
  (error) => {
    showError(error.message)
    return Promise.reject(error)
  },
)
export function getFilePath() {
  if (!/(http|https):\/\/([^/]+)/i.test(import.meta.env.BASE_URL)) {
    return location.origin + import.meta.env.VITE_API_BASE_UPLOAD_URL
  }
  return (
    import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_API_BASE_UPLOAD_URL
  )
}
export function getFileCnPath() {
  if (!/(http|https):\/\/([^/]+)/i.test(import.meta.env.BASE_URL)) {
    return location.origin
  }
  return import.meta.env.VITE_API_BASE_URL
}
export function getWsUrl() {
  if (location.protocol === 'https:') {
    return 'wss://' + location.host
  } else {
    return 'ws://' + location.host
  }
}
export const filePath = getFilePath()
export const FileCnPath = getFileCnPath()

export default axios
