// 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
    })
}

/**
 * 查询输出流信息（流式响应）
 */
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
    }).finally(() => {
        clearTimeout(timeoutId)
    })
}

/**
 * 获取服务卡片列表（产品列表）
 */
export async function getServiceCardList() {
    const userStore = useUserStore()
    const token = getToken()
    // 根据实际 store 获取 userId，如果不存在则使用默认值（示例中为 '30'）
    const userId = userStore.userInfo?.userId || userStore.userId || '30'

    // 处理 token 格式（去掉 "Bearer " 前缀）
    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
    }
}