import axios from 'axios'
import { message } from 'ant-design-vue'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { mockAPI } from './mockData'
import { createMockWrapper } from '@/config/mock'

// API基础配置 - 修改为本地测试地址
const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3200/api/v1'
const timeout = parseInt(import.meta.env.VITE_API_TIMEOUT || '10000')

// 检查是否使用模拟数据（注释掉未使用的变量）
// const useMock = import.meta.env.VITE_USE_MOCK === 'true' || (!baseURL || baseURL.includes('localhost')) && import.meta.env.DEV

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL,
  timeout,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('admin_token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 记录请求日志（开发环境）
    if (import.meta.env.DEV) {
      console.log('🚀 API请求:', config.method?.toUpperCase(), config.url)
    }
    
    return config
  },
  (error) => {
    console.error('❌ 请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 用于防止重复刷新token的标志
let isRefreshing = false
let failedQueue: Array<{ resolve: Function; reject: Function }> = []

// 处理队列中的请求
const processQueue = (error: any, token: string | null = null) => {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error)
    } else {
      resolve(token)
    }
  })
  
  failedQueue = []
}

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 处理成功响应
    const { data } = response
    
    if (import.meta.env.DEV) {
      console.log('✅ API响应:', response.config.url, data)
    }
    
    // 检查业务逻辑成功
    if (data && data.success) {
      return data
    } else {
      // 业务逻辑错误
      const errorMsg = data?.message || '请求失败'
      message.error(errorMsg)
      return Promise.reject(new Error(errorMsg))
    }
  },
  async (error) => {
    // 处理错误响应
    console.error('❌ API错误:', error)
    
    const originalRequest = error.config
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 如果是登录接口或者已经在刷新token，直接返回错误
          if (originalRequest.url?.includes('/login') || originalRequest._retry) {
            message.error('登录已过期，请重新登录')
            localStorage.removeItem('admin_token')
            window.location.href = '/login'
            return Promise.reject(error)
          }

          // 标记请求已重试
          originalRequest._retry = true

          if (isRefreshing) {
            // 如果正在刷新token，将请求加入队列
            return new Promise((resolve, reject) => {
              failedQueue.push({ resolve, reject })
            }).then(token => {
              originalRequest.headers.Authorization = `Bearer ${token}`
              return api(originalRequest)
            }).catch(err => {
              return Promise.reject(err)
            })
          }

          isRefreshing = true

          try {
            // 尝试刷新token
            const refreshToken = localStorage.getItem('admin_refresh_token')
            const response = await authAPI.refreshToken(refreshToken)
            const newToken = response.data.token
            
            // 更新localStorage中的token
            localStorage.setItem('admin_token', newToken)
            
            // 更新默认请求头
            api.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
            
            // 处理队列中的请求
            processQueue(null, newToken)
            
            // 重试原始请求
            originalRequest.headers['Authorization'] = `Bearer ${newToken}`
            return api(originalRequest)
          } catch (refreshError) {
            // 刷新失败，清除所有token并跳转登录页
            processQueue(refreshError, null)
            message.error('登录已过期，请重新登录')
            localStorage.removeItem('admin_token')
            localStorage.removeItem('admin_refresh_token')
            window.location.href = '/login'
            return Promise.reject(refreshError)
          } finally {
            isRefreshing = false
          }
          break
        case 403:
          message.error('权限不足，无法访问')
          break
        case 404:
          message.error('请求的资源不存在')
          break
        case 429:
          message.error('请求过于频繁，请稍后再试')
          break
        case 500:
          message.error('服务器内部错误')
          break
        default:
          message.error(data?.message || '请求失败')
      }
    } else if (error.request) {
      // 网络错误
      message.error('网络连接失败，请检查网络设置')
    } else {
      // 其他错误
      message.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 通用请求方法
export const request = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    api.get(url, config).then(res => res.data),
  
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    api.post(url, data, config).then(res => res.data),
  
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    api.put(url, data, config).then(res => res.data),
  
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    api.delete(url, config).then(res => res.data),
  
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> =>
    api.patch(url, data, config).then(res => res.data)
}

// 认证相关API（开发环境使用模拟数据）
export const authAPI = createMockWrapper({
  // 管理员登录
  login: (credentials: { username: string; password: string }) =>
    request.post<{
      success: boolean
      data: {
        token: string
        admin: any
      }
    }>('/admin/login', credentials),
  
  // 获取当前用户信息
  getCurrentUser: () =>
    request.get<{
      success: boolean
      data: {
        admin: any
      }
    }>('/admin/profile'),
  
  // 刷新token
  refreshToken: (refreshToken: string) =>
    request.post<{
      success: boolean
      data: {
        token: string
      }
    }>('/auth/refresh', { refreshToken }),
  
  // 退出登录
  logout: () =>
    request.post('/auth/logout')
}, mockAPI.auth)

// 为避免命名冲突，单独导出模块
export { default as userAPI } from './user'
export { default as merchantAPI } from './merchant'
export { default as travelAPI } from './travel'
export { default as animalAPI } from './animal'
export { default as orderAPI } from './order'
export { default as promotionAPI } from './promotion'
export { default as systemAPI } from './system'

// 重新导出特定类型以避免冲突
export type { ApiResponse } from './user'
export type { Merchant } from './merchant'
export type { Travel } from './travel'
export type { Animal } from './animal'
export type { Order } from './order'
export type { Promotion } from './promotion'
export type { SystemStats } from './system'

export default api