"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePreview = usePreview;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
/**
 * 预览相关逻辑 Hook
 * 管理预览状态、轮询和触发逻辑
 */
const react_1 = require("react");
const ai_column_service_1 = require("../../../../../../../cn-ai-table/view/services/ai-column-service");
const constants_1 = require("../../../../../../../cn-ai-table/view/hooks/constants");
const prompt_utils_1 = require("../utils/prompt-utils");
/** 预览轮询间隔（毫秒） */
const PREVIEW_POLLING_INTERVAL = 1500;
/** 预览最大轮询次数 */
const PREVIEW_MAX_POLLING_COUNT = 40;
/**
 * 获取当前用户工号
 */
const getUserId = () => {
    var _a, _b;
    return ((_b = (_a = window.__PAGE_INFO__) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.aliWorkNo) || '';
};
/**
 * 预览相关逻辑 Hook
 */
function usePreview({ tableId, rawData, fields, isEditMode, allColumns = [], processedColumnMap = new Map(), bizRequestConfig, }) {
    // 预览状态
    const [previewLoading, setPreviewLoading] = (0, react_1.useState)(false);
    const [previewResult, setPreviewResult] = (0, react_1.useState)('');
    const [previewError, setPreviewError] = (0, react_1.useState)('');
    const [previewInterrupted, setPreviewInterrupted] = (0, react_1.useState)(false);
    // 是否从未预览过（编辑模式初始为 true）
    const [neverPreviewed, setNeverPreviewed] = (0, react_1.useState)(isEditMode);
    // 轮询定时器
    const previewPollingRef = (0, react_1.useRef)(null);
    // 停止预览轮询
    const stopPreviewPolling = (0, react_1.useCallback)((interrupted = false) => {
        if (previewPollingRef.current) {
            clearTimeout(previewPollingRef.current);
            previewPollingRef.current = null;
            if (interrupted) {
                setPreviewLoading(false);
                setPreviewInterrupted(true);
            }
        }
    }, []);
    // 获取补充后的 prompt
    const getEnrichedPrompt = (0, react_1.useCallback)((prompt) => {
        return (0, prompt_utils_1.enrichPromptWithFieldNames)(prompt, fields);
    }, [fields]);
    // 执行预览
    const handlePreview = (0, react_1.useCallback)(async (promptValue) => {
        var _a;
        // 验证是否有变量
        if (!(0, prompt_utils_1.hasPromptVariables)(promptValue)) {
            setPreviewError(i18n_1.default.get({
                id: 'PleaseInsertFieldsInTheTaskDescr_441188635',
                dm: '请先在任务描述中插入字段',
            }));
            return;
        }
        // 获取第一行数据
        const firstRow = rawData === null || rawData === void 0 ? void 0 : rawData[0];
        if (!firstRow) {
            setPreviewError(i18n_1.default.get({ id: 'NoDataAvailableForPreview', dm: '暂无数据可预览' }));
            return;
        }
        // 标记为已预览过
        setNeverPreviewed(false);
        // 在接口请求时补充字段名称
        const enrichedPrompt = getEnrichedPrompt(promptValue);
        // 解析变量并构建 promptParams（格式化显示值优先）
        const variables = (0, prompt_utils_1.parsePromptVariables)(enrichedPrompt);
        const promptParams = (0, prompt_utils_1.buildPromptParamsWithExtractor)(firstRow, variables, allColumns, processedColumnMap, 0);
        setPreviewLoading(true);
        setPreviewResult('');
        setPreviewError('');
        setPreviewInterrupted(false);
        stopPreviewPolling();
        try {
            // 1. 提交预览任务
            const submitResult = await (0, ai_column_service_1.submitAiColumnPreview)({
                tableId: tableId || '',
                promptParams,
                scenarioId: constants_1.AGENT_ID,
                promptTemplate: enrichedPrompt,
                userId: getUserId(),
            }, bizRequestConfig);
            if (!(submitResult === null || submitResult === void 0 ? void 0 : submitResult.success) || !((_a = submitResult.data) === null || _a === void 0 ? void 0 : _a.taskId)) {
                setPreviewError((submitResult === null || submitResult === void 0 ? void 0 : submitResult.errorMsg) || i18n_1.default.get({ id: 'PreviewRequestFailed', dm: '预览请求失败' }));
                setPreviewLoading(false);
                return;
            }
            const { taskId } = submitResult.data;
            // 2. 轮询查询预览结果
            let pollingCount = 0;
            const pollResult = async () => {
                pollingCount += 1;
                if (pollingCount > PREVIEW_MAX_POLLING_COUNT) {
                    setPreviewError(i18n_1.default.get({ id: 'PreviewTimedOutPleaseTryAgain', dm: '预览超时，请重试' }));
                    setPreviewLoading(false);
                    return;
                }
                try {
                    const queryResult = await (0, ai_column_service_1.queryAiColumnPreview)({
                        tableId: tableId || '',
                        taskId,
                    }, bizRequestConfig);
                    if (!(queryResult === null || queryResult === void 0 ? void 0 : queryResult.success)) {
                        setPreviewError((queryResult === null || queryResult === void 0 ? void 0 : queryResult.errorMsg) ||
                            i18n_1.default.get({ id: 'QueryPreviewResultFailed', dm: '查询预览结果失败' }));
                        setPreviewLoading(false);
                        return;
                    }
                    const { status, jobOutput } = queryResult.data || {};
                    if (status === 'finish') {
                        setPreviewResult(jobOutput || '');
                        setPreviewLoading(false);
                    }
                    else if (status === 'failed') {
                        setPreviewError(i18n_1.default.get({ id: 'PreviewGenerationFailed', dm: '预览生成失败' }));
                        setPreviewLoading(false);
                    }
                    else {
                        // 继续轮询
                        previewPollingRef.current = setTimeout(pollResult, PREVIEW_POLLING_INTERVAL);
                    }
                }
                catch {
                    setPreviewError(i18n_1.default.get({ id: 'QueryPreviewResultFailed', dm: '查询预览结果失败' }));
                    setPreviewLoading(false);
                }
            };
            // 开始轮询
            previewPollingRef.current = setTimeout(pollResult, PREVIEW_POLLING_INTERVAL);
        }
        catch {
            setPreviewError(i18n_1.default.get({ id: 'PreviewRequestFailed', dm: '预览请求失败' }));
            setPreviewLoading(false);
        }
    }, [
        tableId,
        rawData,
        allColumns,
        processedColumnMap,
        getEnrichedPrompt,
        stopPreviewPolling,
        bizRequestConfig,
    ]);
    // 判断 prompt 是否有实质性变化
    const isPromptMeaningfullyChanged = (0, react_1.useCallback)((oldValue, newValue) => {
        // 比较变量列表
        const oldVars = (0, prompt_utils_1.parsePromptVariables)(oldValue).sort().join(',');
        const newVars = (0, prompt_utils_1.parsePromptVariables)(newValue).sort().join(',');
        if (oldVars !== newVars) {
            return true;
        }
        // 规范化空白字符后比较
        const normalize = (s) => s.replace(/\s+/g, ' ').trim();
        return normalize(oldValue) !== normalize(newValue);
    }, []);
    // 处理 prompt 变化
    const handlePromptChange = (0, react_1.useCallback)((oldValue, newValue) => {
        const newHasVariables = (0, prompt_utils_1.hasPromptVariables)(newValue);
        const meaningfulChange = isPromptMeaningfullyChanged(oldValue, newValue);
        // 如果新的 prompt 没有变量了，清空所有预览状态
        if (!newHasVariables) {
            stopPreviewPolling();
            setPreviewResult('');
            setPreviewError('');
            setPreviewInterrupted(false);
            return;
        }
        // 只有实质性变化才触发后续逻辑
        if (!meaningfulChange) {
            return;
        }
        // 如果正在轮询，停止并标记为中断
        if (previewPollingRef.current) {
            stopPreviewPolling(true);
            return;
        }
        // 如果已预览过且有变量，标记为中断（需要重新生成）
        if (!neverPreviewed && newHasVariables) {
            setPreviewResult('');
            setPreviewError('');
            setPreviewInterrupted(true);
        }
    }, [stopPreviewPolling, isPromptMeaningfullyChanged, neverPreviewed]);
    // 重置预览状态
    const resetPreviewState = (0, react_1.useCallback)(() => {
        stopPreviewPolling();
        setPreviewLoading(false);
        setPreviewResult('');
        setPreviewError('');
        setPreviewInterrupted(false);
        setNeverPreviewed(isEditMode);
    }, [stopPreviewPolling, isEditMode]);
    // 组件卸载时清理
    (0, react_1.useEffect)(() => {
        return () => {
            stopPreviewPolling();
        };
    }, [stopPreviewPolling]);
    return {
        previewLoading,
        previewResult,
        previewError,
        previewInterrupted,
        neverPreviewed,
        handlePreview,
        handlePromptChange,
        stopPreviewPolling,
        resetPreviewState,
    };
}
