// 引入 axios 请求
import axios from 'axios'
// 引入 element-plus 里面的消息提示
import { ElMessage } from 'element-plus'
import { getToken, setToken, removeToken, formatBearerAuthorization } from '@/api/request.js'

export { getToken, setToken, removeToken }

// 创建 axios 实例
const service = axios.create({
    timeout: 300 * 1000 // 请求超时时间
})

// request 拦截器：与主 request 一致，就地改 config，避免 mergeConfig 破坏 url
service.interceptors.request.use(config => {
    const raw = getToken()
    const token = raw ? String(raw).trim() : ""
    if (!config.headers) {
        config.headers = new axios.AxiosHeaders()
    } else if (!(config.headers instanceof axios.AxiosHeaders)) {
        config.headers = axios.AxiosHeaders.from(config.headers)
    }
    if (token) {
        config.headers.set('token', token, true)
    } else {
        config.headers.delete('token')
        config.headers.delete('Token')

        // ===== 旧逻辑保留（勿删）：Authorization: Bearer <token> =====
        // config.headers.delete('Authorization')
        // config.headers.delete('authorization')
    }
    const reqUrl = String(config.url ?? '')
    if (reqUrl.includes('aiAnalysis')) {
        const aiApiKey = import.meta.env.VITE_AI_ANALYSIS_API_KEY
        if (aiApiKey) {
            if (!config.headers) {
                config.headers = new axios.AxiosHeaders()
            } else if (!(config.headers instanceof axios.AxiosHeaders)) {
                config.headers = axios.AxiosHeaders.from(config.headers)
            }
            config.headers.set('X-API-Key', aiApiKey)
        }
    }
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})

// response 拦截器
service.interceptors.response.use(
    response => {
        const res = response?.data
        if (!res) {
            return Promise.reject(new Error('响应数据为空'))
        }
        // 根据需求：接口返回 code 不等于 200 的时候报错
        if (res.code !== 200) {
            ElMessage({
                message: res.message || '请求失败',
                type: 'error',
                duration: 3 * 1000
            })
            return Promise.reject(res)
        }
        return res.data
    },
    error => {
        console.log('err' + error)

        const isCanceledError =
            error?.code === 'ERR_CANCELED' ||
            error?.name === 'CanceledError' ||
            error?.name === 'AbortError' ||
            (typeof error?.message === 'string' && /canceled/i.test(error.message))

        if (isCanceledError) return Promise.reject(error)
        
        // 处理 token 过期或无效的情况
        const errUrl = String(error.config?.url || '')
        const isAiAnalysisRequest = errUrl.includes('aiAnalysis')
        if (
            error.response &&
            (error.response.status === 401 || error.response.status === 403) &&
            !isAiAnalysisRequest
        ) {
            ElMessage({
                message: 'Token 已过期，请重新登录',
                type: 'error',
                duration: 3 * 1000
            })
            const h = error.config?.headers
            const hadToken =
                h &&
                (typeof h.get === 'function'
                    ? Boolean(
                          h.get('token') || h.get('Token')
                      )
                    : Boolean(
                          h.token || h.Token
                      ))
            if (hadToken) removeToken()
        } else {
            ElMessage({
                message: typeof error?.message === 'string' ? error.message : '请求失败',
                type: 'error',
                duration: 3 * 1000
            })
        }
        return Promise.reject(error)
    }
)

// 封装通用请求函数（支持 http(config) 和 http.get/post 等调用方式）
function http(config) {
    return service(config)
}

// 为 http 函数添加快捷方法
http.get = function(url, params) {
    return service({ url, method: 'get', params })
}

http.post = function(url, data) {
    return service({ url, method: 'post', data })
}

http.put = function(url, data) {
    return service({ url, method: 'put', data })
}

http.delete = function(url, params) {
    return service({ url, method: 'delete', params })
}

export { http }
export default service