// 引入 axios 请求
import axios from 'axios'
// 引入 element-plus 里面的消息提示
import { ElMessage } from 'element-plus'

// Token 管理
const TOKEN_KEY = 'auth_token'

// 获取token
const getToken = () => {
  return 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkYXRhLWNlbnRlciIsImF1ZCI6IndlYiIsImlzcyI6ImRhdGEtY2VudGVyIiwiZXhwIjozODI1ODM1NTkxLCJpYXQiOjE2NzgzNTE5NTMsImp0aSI6IjI4YmY1NTZjMTc0MDQ3YjJiNTExNWM3NzVhYjhlNWRmIiwidXNlcm5hbWUiOiJzdXBlcl91c2VyIn0.zHyVzsleX2lEqjDBYRpwluu_wy2nZKGl0dw3IUGnKNw'
    // return localStorage.getItem(TOKEN_KEY)
}

// 设置 token
const setToken = (token) => {
    localStorage.setItem(TOKEN_KEY, token)
}

// 移除 token
const removeToken = () => {
    localStorage.removeItem(TOKEN_KEY)
}

// 导出 token 管理方法
export { getToken, setToken, removeToken }

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

// request 拦截器
service.interceptors.request.use(config => {
    // 获取 token 并添加到请求头
    const token = getToken()
    if (token) {
        config.headers['token'] = token
    }
    // 图表解读等 AI 分析服务（Vite 代理 /aiAnalysis）需要 X-API-Key
    const reqUrl = String(config.url || '')
    if (reqUrl.includes('aiAnalysis')) {
        const aiApiKey = import.meta.env.VITE_AI_ANALYSIS_API_KEY
        if (aiApiKey) {
            config.headers['X-API-Key'] = aiApiKey
        }
    }
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})

// response 拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        // 根据需求：接口返回 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
            })
            removeToken()
        } else {
            ElMessage({
                message: 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