// src/api/ai/ai.js
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

// 加载随机词条列表
export function randList(data) {
    return request({
        url: '/ai/api/entry/rand/list',
        method: 'post',
        data: data
    })
}

/**
 * 查询输出流信息（流式响应）
 * 增强错误处理：当HTTP状态非2xx时，解析错误响应体并抛出包含code属性的错误
 */
export function getStream(question, timeout = 300000) {
    const userStore = useUserStore()
    const token = getToken()
    const tenantId = userStore.currentTenant?.apiLoginTenantInfoResponse?.tenantBizId

    const headers = {
        'Accept': 'text/event-stream',
        'Authorization': `Bearer ${token}`
    }
    if (tenantId) {
        headers['X-Tenant-ID'] = tenantId
    }

    const baseUrl = import.meta.env.VITE_APP_BASE_API
    const url = `${baseUrl}/ai/api/api/ai/stream?question=${encodeURIComponent(question)}`

    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), timeout)

    return fetch(url, {
        method: 'GET',
        headers,
        signal: controller.signal
    }).then(async (response) => {
        clearTimeout(timeoutId)
        if (!response.ok) {
            // 尝试解析错误响应体
            let errorCode = null
            let errorMessage = response.statusText
            try {
                const errorBody = await response.json()
                if (errorBody && errorBody.code !== undefined) {
                    errorCode = errorBody.code
                    errorMessage = errorBody.msg || errorBody.message || errorMessage
                }
            } catch (e) {
                // 无法解析JSON，使用默认错误信息
            }
            const error = new Error(errorMessage)
            error.code = errorCode
            error.status = response.status
            throw error
        }
        return response
    }).finally(() => {
        clearTimeout(timeoutId)
    })
}

/**
 * 获取服务卡片列表（产品列表）
 */
export async function getServiceCardList() {
    const userStore = useUserStore()
    const token = getToken()
    const userId = userStore.userInfo?.userId || userStore.userId || '30'

    let cleanToken = token
    if (token && token.startsWith('Bearer ')) {
        cleanToken = token.slice(7)
    }

    const headers = {
        'Content-Type': 'application/json',
        'x-authorization': `sfpfamilyfinancialplanning ${cleanToken}`
    }

    const url = 'https://hoservice.ydhomeoffice.cn/hoserviceApi/ydServiceCard/serviceCardList'
    const body = {
        userId: String(userId),
        cardType: '11'
    }

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(body)
        })

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }

        const data = await response.json()
        return data
    } catch (error) {
        console.error('获取服务卡片列表失败:', error)
        throw error
    }
}