import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from './auth'
import { useUserStore } from '@/store/user'
import type { BaseResponse } from '@/types'

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<BaseResponse>) => {
    const res = response.data

    // 二进制数据直接返回
    if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
      return response.data
    }

    // 新响应格式：使用 success 字段判断
    if (res.success === false) {
      // 认证失败
      if (res.errCode === 'UNAUTHORIZED' || res.errCode === '401') {
        const userStore = useUserStore()
        userStore.resetToken()
        ElMessage.warning('登录已过期，请重新登录')
        location.href = '/login'
        return Promise.reject(new Error('登录已过期'))
      }

      // 其他错误：不在拦截器中显示消息，由调用方处理
      // 直接返回响应，让调用方根据 success 判断
    }

    return res as any
  },
  (error) => {
    // HTTP 401 状态码处理
    if (error.response?.status === 401) {
      const userStore = useUserStore()
      userStore.resetToken()
      ElMessage.warning('登录已过期，请重新登录')
      location.href = '/login'
      return Promise.reject(new Error('登录已过期'))
    }

    let { message } = error
    if (message === 'Network Error') {
      message = '网络连接异常'
    } else if (message.includes('timeout')) {
      message = '请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`
    }
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export function get<T = any>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {
  return service.get(url, { params, ...config })
}

export function post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
  return service.post(url, data, config)
}

export function put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
  return service.put(url, data, config)
}

export function del<T = any>(url: string, params?: object, config?: AxiosRequestConfig): Promise<T> {
  return service.delete(url, { params, ...config })
}

export default service
