"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AiFieldConfigPanel = AiFieldConfigPanel;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const mobx_react_simpler_1 = require("../../../../../../../utils/mobx-react-simpler/index.js");
const prompt_editor_1 = require("../prompt-editor");
const constants_1 = require("../constants");
const utils_1 = require("../utils");
const prompt_utils_1 = require("../utils/prompt-utils");
const ai_column_service_1 = require("../../../../../../../cn-ai-table/view/services/ai-column-service");
const constants_2 = require("../../../../../hooks/constants");
require("./ai-field-config-panel.scss");
const confirm_dialog_1 = require("./confirm-dialog");
const preview_content_1 = require("./preview-content");
/** 预览轮询间隔（毫秒） */
const PREVIEW_POLLING_INTERVAL = 1500;
/** 预览最大轮询次数 */
const PREVIEW_MAX_POLLING_COUNT = 40;
function AiFieldConfigPanel({ fieldType, fieldLabel, columnCode: existingColumnCode, saving = false, executing = false, initialPromptTemplate, isEditStatus, onSave, onCancel, }) {
    var _a;
    // 获取数据模型
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    // 状态管理
    const [fieldName, setFieldName] = (0, react_1.useState)(fieldLabel);
    const [promptValue, setPromptValue] = (0, react_1.useState)(initialPromptTemplate || (0, constants_1.getDefaultPromptByFieldType)(fieldType));
    const [model, setModel] = (0, react_1.useState)(constants_1.DEFAULT_MODEL);
    const [autoUpdate, setAutoUpdate] = (0, react_1.useState)(false);
    const [confirmDialogVisible, setConfirmDialogVisible] = (0, react_1.useState)(false);
    const [validationError, setValidationError] = (0, react_1.useState)('');
    // 预览状态
    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)(!!existingColumnCode);
    const previewPollingRef = (0, react_1.useRef)(null);
    // 记录上一次的变量数量，用于检测首次插入字段
    const prevVariableCountRef = (0, react_1.useRef)(0);
    // 记录是否已完成初始化（编辑模式下，初始化时已有字段，不触发预览）
    const isInitializedRef = (0, react_1.useRef)(false);
    // 防抖定时器，用于修改内容后自动触发预览
    const autoPreviewTimerRef = (0, react_1.useRef)(null);
    // Refs
    const promptEditorRef = (0, react_1.useRef)(null);
    const fieldNameInputRef = (0, react_1.useRef)(null);
    // 获取可插入的字段列表
    const getAvailableFields = (0, react_1.useCallback)(() => {
        const columnDefinitions = (dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) || [];
        const fieldMap = (dataModel === null || dataModel === void 0 ? void 0 : dataModel.fieldMap) || {};
        return columnDefinitions
            .filter((col) => !col.isAiColumn)
            .map((col) => {
            const fieldInfo = fieldMap[col.dataIndex];
            return {
                dataIndex: col.dataIndex,
                title: col.title || col.dataIndex,
                icon: (0, utils_1.getFieldIcon)(fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.component),
                group: (fieldInfo === null || fieldInfo === void 0 ? void 0 : fieldInfo.group) || i18n_1.default.get({ id: 'Field', dm: '字段' }),
            };
        });
    }, [dataModel]);
    // 获取补充后的 prompt（用于接口请求）
    const getEnrichedPrompt = (0, react_1.useCallback)((prompt) => {
        const fields = getAvailableFields();
        return (0, prompt_utils_1.enrichPromptWithFieldNames)(prompt, fields);
    }, [getAvailableFields]);
    // 验证表单
    const validateForm = () => {
        if (!(0, prompt_utils_1.hasPromptVariables)(promptValue)) {
            setValidationError(i18n_1.default.get({
                id: 'PleaseInsertAFieldInTheTaskDescr_1740586859',
                dm: '请在任务描述中插入字段',
            }));
            return false;
        }
        setValidationError('');
        return true;
    };
    // 当 fieldLabel 变化时，更新字段名称
    (0, react_1.useEffect)(() => {
        if (!fieldName || fieldName === fieldLabel) {
            setFieldName(fieldLabel);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fieldLabel]);
    // 当 initialPromptTemplate 变化时，更新 prompt 值（用于编辑场景）
    (0, react_1.useEffect)(() => {
        if (initialPromptTemplate) {
            setPromptValue(initialPromptTemplate);
            // 编辑模式下，初始化时已有字段，标记为已初始化，不触发预览
            if (existingColumnCode) {
                const variables = (0, prompt_utils_1.parsePromptVariables)(initialPromptTemplate);
                prevVariableCountRef.current = variables.length;
                isInitializedRef.current = true; // 编辑模式初始化完成，不触发预览
            }
        }
        else {
            // 添加模式下，初始化 prevVariableCountRef 为当前 promptValue 的变量数量
            const initialVariables = (0, prompt_utils_1.parsePromptVariables)(promptValue);
            prevVariableCountRef.current = initialVariables.length;
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [initialPromptTemplate, existingColumnCode]);
    // 打开弹窗时自动聚焦到字段名称输入框
    (0, react_1.useEffect)(() => {
        const timer = setTimeout(() => {
            var _a, _b;
            if (fieldNameInputRef.current) {
                const inputNode = ((_b = (_a = fieldNameInputRef.current).getInputNode) === null || _b === void 0 ? void 0 : _b.call(_a)) || fieldNameInputRef.current;
                if (inputNode && typeof inputNode.focus === 'function') {
                    inputNode.focus();
                    if (typeof inputNode.select === 'function') {
                        inputNode.select();
                    }
                }
            }
        }, 100);
        return () => clearTimeout(timer);
    }, []);
    // 获取当前用户工号
    const getUserId = (0, react_1.useCallback)(() => {
        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) || '';
    }, []);
    // 停止预览轮询
    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 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);
    }, []);
    // 执行预览
    const handlePreview = (0, react_1.useCallback)(async () => {
        var _a, _b;
        // 验证是否有变量
        if (!(0, prompt_utils_1.hasPromptVariables)(promptValue)) {
            setPreviewError(i18n_1.default.get({
                id: 'PleaseInsertFieldsInTheTaskDescr_441188635',
                dm: '请先在任务描述中插入字段',
            }));
            return;
        }
        // 获取第一行数据
        const firstRow = (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.rawData) === null || _a === void 0 ? void 0 : _a[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 allColumns = (dataModel === null || dataModel === void 0 ? void 0 : dataModel.columnDefinitions) || [];
        const processedColumnMap = (dataModel === null || dataModel === void 0 ? void 0 : dataModel.processedColumnMap) || new Map();
        const promptParams = (0, prompt_utils_1.buildPromptParamsWithExtractor)(firstRow, variables, allColumns, processedColumnMap, 0);
        setPreviewLoading(true);
        setPreviewResult('');
        setPreviewError('');
        setPreviewInterrupted(false);
        stopPreviewPolling();
        try {
            // 1. 提交预览任务（使用补充后的 prompt）
            const submitResult = await (0, ai_column_service_1.submitAiColumnPreview)({
                tableId: (dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId) || '',
                promptParams,
                scenarioId: constants_2.AGENT_ID,
                promptTemplate: enrichedPrompt,
                userId: getUserId(),
            }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.bizRequestConfig);
            if (!(submitResult === null || submitResult === void 0 ? void 0 : submitResult.success) || !((_b = submitResult.data) === null || _b === void 0 ? void 0 : _b.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: (dataModel === null || dataModel === void 0 ? void 0 : dataModel.tableId) || '',
                        taskId,
                    }, dataModel === null || dataModel === void 0 ? void 0 : dataModel.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);
        }
    }, [promptValue, dataModel, getUserId, stopPreviewPolling, getEnrichedPrompt]);
    // 处理 prompt 变化
    const handlePromptChange = (0, react_1.useCallback)((newValue) => {
        const prevHasVariables = (0, prompt_utils_1.hasPromptVariables)(promptValue);
        const newHasVariables = (0, prompt_utils_1.hasPromptVariables)(newValue);
        const meaningfulChange = isPromptMeaningfullyChanged(promptValue, newValue);
        // 标记初始化完成（用户开始修改内容）
        // 注意：首次插入字段（从0到1）的情况由 useEffect 处理，这里不设置 isInitializedRef
        // 只有当之前已经有变量时，才标记为已初始化
        if (!isInitializedRef.current && meaningfulChange && prevHasVariables) {
            isInitializedRef.current = true;
        }
        setPromptValue(newValue);
        if (validationError && (0, prompt_utils_1.parsePromptVariables)(newValue).length > 0) {
            setValidationError('');
        }
        // 如果新的 prompt 没有变量了，清空所有预览状态
        if (!newHasVariables) {
            stopPreviewPolling();
            // 清除自动预览定时器
            if (autoPreviewTimerRef.current) {
                clearTimeout(autoPreviewTimerRef.current);
                autoPreviewTimerRef.current = null;
            }
            setPreviewResult('');
            setPreviewError('');
            setPreviewInterrupted(false);
            return;
        }
        // 只有实质性变化才触发后续逻辑
        if (!meaningfulChange) {
            return;
        }
        // 如果正在轮询，停止并标记为中断（已自动设置 previewInterrupted = true）
        if (previewPollingRef.current) {
            stopPreviewPolling(true);
            return;
        }
        // 如果已完成初始化且有变量，标记为中断（需要重新生成）
        // 不再自动触发预览，用户需要点击"重新生成"按钮
        if (isInitializedRef.current && newHasVariables) {
            // 如果之前是"从未预览过"状态，改为"中断"状态（显示"重新生成"按钮）
            if (neverPreviewed) {
                setNeverPreviewed(false);
            }
            setPreviewResult('');
            setPreviewError('');
            setPreviewInterrupted(true);
        }
    }, [validationError, stopPreviewPolling, promptValue, isPromptMeaningfullyChanged, neverPreviewed]);
    // 组件卸载时清理轮询和自动预览定时器
    (0, react_1.useEffect)(() => {
        return () => {
            stopPreviewPolling();
            if (autoPreviewTimerRef.current) {
                clearTimeout(autoPreviewTimerRef.current);
                autoPreviewTimerRef.current = null;
            }
        };
    }, [stopPreviewPolling]);
    // 监听首次插入字段，自动触发预览（仅首次插入时触发，后续修改不再自动触发）
    (0, react_1.useEffect)(() => {
        var _a;
        const currentVariables = (0, prompt_utils_1.parsePromptVariables)(promptValue);
        const currentCount = currentVariables.length;
        const prevCount = prevVariableCountRef.current;
        // 当从 0 个变量变成 >= 1 个变量时，自动触发预览（仅首次插入字段时）
        // 编辑模式初始化时已有字段（isInitializedRef.current = true），不会触发（因为 prevCount 不为 0）
        // 添加模式初始化时没有字段（isInitializedRef.current = false），首次插入字段时会触发
        // 之后的所有修改（添加字段、删除字段、修改prompt等）都不会自动触发预览，需要点击"重新生成"按钮
        if (prevCount === 0 &&
            currentCount >= 1 &&
            !isInitializedRef.current &&
            ((_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.rawData) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            handlePreview();
            // 标记为已初始化，后续变化不再自动触发预览
            isInitializedRef.current = true;
        }
        // 更新上一次的变量数量（在检查之后更新）
        prevVariableCountRef.current = currentCount;
    }, [promptValue, (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.rawData) === null || _a === void 0 ? void 0 : _a.length, handlePreview]);
    // 获取配置
    // 在获取配置时统一补充字段名称，确保 onSave 拿到的是补充后的 prompt
    const getConfig = () => {
        const enrichedPrompt = getEnrichedPrompt(promptValue);
        return {
            fieldName,
            aiTaskType: (0, utils_1.getAiTaskType)(fieldType),
            targetInfo: enrichedPrompt, // 补充字段名后的 prompt（用于接口请求）
            content: promptValue, // 原始 prompt（用于编辑时回显）
            model,
            autoUpdate,
            allowEmptyField: false,
            columnCode: (0, utils_1.generateColumnCode)(existingColumnCode),
        };
    };
    // 处理保存按钮点击 - 显示确认对话框
    const handleSaveClick = () => {
        if (!validateForm())
            return;
        setConfirmDialogVisible(true);
    };
    // 仅保存配置
    const handleSaveConfigOnly = () => {
        if (isEditStatus) {
            onSave(getConfig(), 'config-only');
            setConfirmDialogVisible(false);
        }
    };
    // 生成前5行
    const handleGenerateFirst5Rows = () => {
        onSave(getConfig(), 'first-5-rows');
        setConfirmDialogVisible(false);
    };
    // 生成全列
    const handleGenerateAllRows = () => {
        onSave(getConfig(), 'all-rows');
        setConfirmDialogVisible(false);
    };
    // 处理保存前5行（底部按钮）
    const handleSaveFirst5Rows = () => {
        if (!validateForm())
            return;
        onSave(getConfig(), 'first-5-rows');
    };
    // 是否正在处理中
    const isProcessing = saving || executing;
    // 处理取消
    const handleCancel = () => {
        setFieldName(fieldLabel);
        setPromptValue((0, constants_1.getDefaultPromptByFieldType)(fieldType));
        setAutoUpdate(false);
        setConfirmDialogVisible(false);
        setValidationError('');
        onCancel();
    };
    // 处理确认对话框关闭
    const handleConfirmDialogClose = () => {
        setConfirmDialogVisible(false);
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "ai-field-config-panel" },
            react_1.default.createElement("div", { className: "ai-field-config-header" },
                react_1.default.createElement("div", { className: "ai-field-config-header-left" },
                    react_1.default.createElement(cn_ui_1.CnIcon, { type: "wand", style: { color: '#722ed1', fontSize: '16px' } }),
                    react_1.default.createElement("span", { className: "ai-field-config-title" }, i18n_1.default.get({ id: 'AIField', dm: 'AI字段' }))),
                react_1.default.createElement(cn_ui_1.CnIcon, { type: "close", size: "small", onClick: handleCancel })),
            react_1.default.createElement("div", { className: "ai-field-config-content" },
                react_1.default.createElement("div", { className: "ai-field-config-section" },
                    react_1.default.createElement("div", { className: "ai-field-config-label" }, i18n_1.default.get({ id: 'FieldName', dm: '字段名称' })),
                    react_1.default.createElement(cn_ui_1.CnInput, { ref: fieldNameInputRef, value: fieldName, onChange: setFieldName, placeholder: i18n_1.default.get({ id: 'PleaseEnterAFieldName', dm: '请输入字段名称' }), style: { width: '100%' } })),
                react_1.default.createElement("div", { className: "ai-field-config-section" },
                    react_1.default.createElement("div", { className: "ai-field-config-label" }, i18n_1.default.get({ id: 'AITaskDescription', dm: 'AI任务描述' })),
                    react_1.default.createElement(prompt_editor_1.PromptEditor, { ref: promptEditorRef, value: promptValue, onChange: handlePromptChange, fields: getAvailableFields(), placeholder: i18n_1.default.get({
                            id: 'PleaseEnterAITaskDescriptionAndC_840720935',
                            dm: '请输入AI任务描述，点击下方按钮插入字段变量...',
                        }), hasError: !!validationError, minHeight: 150, model: model, onModelChange: setModel }),
                    validationError && (react_1.default.createElement("div", { className: "ai-field-config-validation-error" }, validationError))),
                react_1.default.createElement("div", { className: "ai-field-config-section" },
                    react_1.default.createElement("div", { className: "ai-field-config-label", style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
                        react_1.default.createElement("span", null, i18n_1.default.get({ id: 'PreviewFirstLineOfData', dm: '预览（首行数据）' }))),
                    react_1.default.createElement("div", { className: "ai-field-config-preview" },
                        react_1.default.createElement(preview_content_1.PreviewContent, { loading: previewLoading, error: previewError, result: previewResult, interrupted: previewInterrupted, hasVariables: (0, prompt_utils_1.hasPromptVariables)(promptValue), neverPreviewed: neverPreviewed, onRegenerate: handlePreview })))),
            react_1.default.createElement("div", { className: "ai-field-config-footer" },
                react_1.default.createElement(cn_ui_1.CnButton, { text: true, onClick: () => { } }),
                react_1.default.createElement("div", { style: { display: 'flex', gap: '8px' } },
                    react_1.default.createElement(cn_ui_1.CnButton, { onClick: handleCancel, disabled: isProcessing }, i18n_1.default.get({ id: 'Cancel', dm: '取消' })),
                    react_1.default.createElement(cn_ui_1.CnButton, { onClick: handleSaveFirst5Rows, loading: executing, disabled: isProcessing }, i18n_1.default.get({ id: 'SaveTheFirst5Rows', dm: '保存前5行' })),
                    react_1.default.createElement(cn_ui_1.CnButton, { type: "primary", onClick: handleSaveClick, loading: saving, disabled: isProcessing }, i18n_1.default.get({ id: 'Save', dm: '保存' }))))),
        react_1.default.createElement(confirm_dialog_1.ConfirmDialog, { isEditStatus: isEditStatus, visible: confirmDialogVisible, onClose: handleConfirmDialogClose, onSaveConfigOnly: handleSaveConfigOnly, onGenerateFirst5Rows: handleGenerateFirst5Rows, onGenerateAllRows: handleGenerateAllRows, saving: saving, executing: executing, isProcessing: isProcessing })));
}
