import axios from 'axios'
import { getToken, clearAuth } from '@/utils/auth'

const BASE_URL = '/api'

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 30000
})

instance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

function handleUnauthorized(url) {
  console.warn('[auth] 登录已过期，自动退出登录', url || '')
  clearAuth()
  setTimeout(() => {
    if (location.hash !== '#/login') {
      location.hash = '#/login'
    }
  }, 200)
}

instance.interceptors.response.use(
  (response) => response,
  (err) => {
    if (err && err.response && err.response.status === 401) {
      handleUnauthorized(err.config && err.config.url)
    }
    return Promise.reject(err)
  }
)

export function request({ url, method = 'GET', data, params, headers, responseType } = {}) {
  return new Promise((resolve, reject) => {
    instance({ url, method, data, params, headers, responseType })
      .then((res) => {
        if (responseType === 'blob' || responseType === 'arraybuffer') {
          resolve(res)
          return
        }

        const body = res.data || {}
        if (body.code === 0) {
          resolve(body.data)
          return
        }

        const message = body.message || '请求失败'
        console.error('[request]', method, url, '业务失败:', message, body)
        reject(new Error(message))
      })
      .catch((err) => {
        if (err && err.response && err.response.status === 401) {
          reject(new Error('Unauthorized'))
          return
        }
        const msg = (err && err.message) || '网络异常'
        console.error('[request]', method, url, '请求异常:', msg, err)
        reject(err)
      })
  })
}

export function uploadFile(file) {
  const formData = new FormData()
  formData.append('file', file)
  return new Promise((resolve, reject) => {
    instance({
      url: '/upload/image',
      method: 'POST',
      data: formData,
      headers: { 'Content-Type': 'multipart/form-data' }
    })
      .then((res) => {
        const body = res.data || {}
        if (body.code === 0) {
          resolve(body.data)
          return
        }
        const message = body.message || '上传失败'
        console.error('[upload] 业务失败:', message, body)
        reject(new Error(message))
      })
      .catch((err) => {
        if (err && err.response && err.response.status === 401) {
          reject(new Error('Unauthorized'))
          return
        }
        const msg = (err && err.message) || '上传失败'
        console.error('[upload] 请求异常:', msg, err)
        reject(err)
      })
  })
}

export function downloadBlob({ url, method = 'POST', data, filename }) {
  return request({ url, method, data, responseType: 'blob' }).then((res) => {
    const blob = new Blob([res.data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename || 'download'
    document.body.appendChild(link)
    link.click()
    setTimeout(() => {
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    }, 0)
  })
}

export function getServerBase() {
  return ''
}

export default instance
