// request.ts
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'

const baseURL = "https://uc.ljsea.top/"

// 统一错误处理
const errorHandler = (msg: string = '请求失败，请稍后重试！') => {
  ElMessage.error(msg)
  return Promise.reject(new Error(msg))
}

// 核心请求方法
const fetchRequest = async (url: string, config?: RequestInit) => {
  try {
    const fullUrl = new URL(url, baseURL).toString()
    const response = await fetch(fullUrl, {
      ...config,
      //credentials: 'include', // 携带 Cookie
      headers: {
        'Content-Type': 'application/json',
        ...config?.headers,
      },
    })

    // HTTP 状态码处理
    if (!response.ok) {
      router.push("/login")
      return errorHandler(`HTTP 错误 ${response.status}`)
    }

    // 业务数据处理
    const result = await response.json()
    
    if (result.message === "NOT_LOGIN" || [2, 3, 4].includes(result.code)) {
      ElMessage.error('登录失效，请重新登录！')
      localStorage.removeItem("token")
      router.push("/login")
      return Promise.reject(result)
    }

    if (result.code === 1) {
      return errorHandler(result.message || '请求失败，请稍后重试！')
    }

    return result.data || result

  } catch (error) {
    return errorHandler(error instanceof Error ? error.message : '网络连接异常')
  }
}

// 封装不同请求方法
export default {
  get: (url: string, config?: RequestInit) => 
    fetchRequest(url, { ...config, method: 'GET' }),

  post: (url: string, data?: any, config?: RequestInit) =>
    fetchRequest(url, { 
      ...config, 
      method: 'POST',
      body: JSON.stringify(data),
    }),

  put: (url: string, data?: any, config?: RequestInit) =>
    fetchRequest(url, { 
      ...config, 
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  delete: (url: string, config?: RequestInit) =>
    fetchRequest(url, { ...config, method: 'DELETE' }),
}