// 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 async function getFullAnswer(question, timeout = 300000) {
    const userStore = useUserStore();
    const token = getToken();
    const tenantId = userStore.currentTenant?.apiLoginTenantInfoResponse?.tenantBizId;

    const headers = {
        '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);

    try {
        const response = await fetch(url, {
            method: 'GET',
            headers,
            signal: controller.signal
        });
        clearTimeout(timeoutId);

        if (!response.ok) {
            let errorMessage = response.statusText;
            try {
                const errorBody = await response.json();
                errorMessage = errorBody.msg || errorBody.message || errorMessage;
            } catch (e) {}
            throw new Error(errorMessage);
        }

        // 直接返回纯文本
        return await response.text();
    } finally {
        clearTimeout(timeoutId);
    }
}

/**
 * 查询输出流信息（流式响应）
 * 增强错误处理：当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-sse?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) => {
        console.log(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
    }
}

/**
 * 启动流式生成，返回 sessionId
 */
export async function startStream(question) {
    const userStore = useUserStore();
    const token = getToken();
    const tenantId = userStore.currentTenant?.apiLoginTenantInfoResponse?.tenantBizId;

    const headers = {
        '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/start-stream`;

    const formData = new FormData();
    formData.append('question', question);

    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 30000); // 30秒超时

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers,
            body: formData,
            signal: controller.signal
        });
        clearTimeout(timeoutId);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        const data = await response.json();
        return data.sessionId;
    } catch (error) {
        clearTimeout(timeoutId);
        throw error;
    }
}

/**
 * 轮询获取流式内容
 */
export async function pollContent(sessionId) {
    const userStore = useUserStore();
    const token = getToken();
    const tenantId = userStore.currentTenant?.apiLoginTenantInfoResponse?.tenantBizId;

    const headers = {
        '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-content?sessionId=${encodeURIComponent(sessionId)}`;

    const response = await fetch(url, { headers });
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
    }
    return await response.json(); // { content: "...", finished: true/false }
}