"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAiColumns = useAiColumns;
const i18n_1 = __importDefault(require("../../../locales/i18n.js"));
const react_1 = require("react");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const services_1 = require("../services");
const constants_1 = require("./constants");
const hooks_1 = require("../../../hooks/index.js");
/**
 * 获取当前用户工号
 * 需要在调用时获取，而不是模块加载时，因为 window.__PAGE_INFO__ 可能还未初始化
 */
const getAliWorkNo = () => { 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 getTaskKey = (task) => `${task.columnCode}-${task.rowId}`;
/**
 * 从 TableTaskItem 解析 promptParams
 */
const parsePromptParams = (task) => {
    if (task.promptParams)
        return task.promptParams;
    if (task.jobContext) {
        try {
            const context = JSON.parse(task.jobContext);
            return context.promptParams || {};
        }
        catch {
            return {};
        }
    }
    return {};
};
/**
 * 将 TableTaskItem 转换为 SingleGridTaskSubmitRequest
 */
const convertTaskToRequest = (task) => ({
    columnCode: task.columnCode,
    rowId: task.rowId,
    promptParams: parsePromptParams(task),
});
// ==================== Hook 实现 ====================
/**
 * AI列管理 Hook
 *
 * 功能：
 * 1. 页面加载时自动查询 AI 列和全表任务
 * 2. 回显已完成任务的结果到表格
 * 3. 使用统一轮询池管理所有运行中的任务
 * 4. 提供保存 AI 列的方法
 */
function useAiColumns(options) {
    const { tableId, enabled = true, onAiColumnsLoaded, onFinishedTasksUpdate, bizRequestConfig, cubePlatformUserConfigRowIdHint, onCubePlatformUserConfigRowId, } = options;
    const cubePlatformCtxRef = (0, react_1.useRef)({});
    cubePlatformCtxRef.current = {
        userCubeConfigRowIdHint: cubePlatformUserConfigRowIdHint,
        onUserCubeConfigRowId: onCubePlatformUserConfigRowId,
    };
    // ==================== 状态 ====================
    const [aiColumns, setAiColumns] = (0, react_1.useState)([]);
    const [loadingAiColumns, setLoadingAiColumns] = (0, react_1.useState)(false);
    const [savingAiColumn, setSavingAiColumn] = (0, react_1.useState)(false);
    const [finishedTasks, setFinishedTasks] = (0, react_1.useState)([]);
    const [runningTasks, setRunningTasks] = (0, react_1.useState)([]);
    const [pollingTasks, setPollingTasks] = (0, react_1.useState)(false);
    const [executingColumnTask, setExecutingColumnTask] = (0, react_1.useState)(false);
    // 统一轮询池：使用 Map 管理所有待轮询的任务
    const taskPoolRef = (0, react_1.useRef)(new Map());
    // 正在执行的列集合（用于追踪 executingColumnTask 状态）
    const executingColumnsRef = (0, react_1.useRef)(new Set());
    // 轮询定时器
    const pollingTimerRef = (0, react_1.useRef)(null);
    // 轮询计数（用于超时控制）
    const pollingCountRef = (0, react_1.useRef)(0);
    // 是否正在轮询中
    const isPollingRef = (0, react_1.useRef)(false);
    // 是否发生API失败（用于停止轮询）
    const hasApiFailureRef = (0, react_1.useRef)(false);
    // ==================== 轮询控制 ====================
    /** 停止轮询 */
    const stopPolling = (0, react_1.useCallback)(() => {
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        pollingCountRef.current = 0;
        isPollingRef.current = false;
        hasApiFailureRef.current = false;
        taskPoolRef.current.clear();
        executingColumnsRef.current.clear();
        setRunningTasks([]);
        setPollingTasks(false);
        setExecutingColumnTask(false);
    }, []);
    /** 处理已完成的任务 */
    const handleFinishedTasks = (0, react_1.useCallback)((newTasks) => {
        if (!(newTasks === null || newTasks === void 0 ? void 0 : newTasks.length))
            return;
        // 合并到状态中（去重）
        setFinishedTasks((prev) => {
            const existingKeys = new Set(prev.map(getTaskKey));
            const uniqueTasks = newTasks.filter((t) => !existingKeys.has(getTaskKey(t)));
            return uniqueTasks.length ? [...prev, ...uniqueTasks] : prev;
        });
        // 触发回调
        onFinishedTasksUpdate === null || onFinishedTasksUpdate === void 0 ? void 0 : onFinishedTasksUpdate(newTasks);
    }, [onFinishedTasksUpdate]);
    /** 将任务添加到轮询池 */
    const addTasksToPool = (0, react_1.useCallback)((tasks) => {
        tasks.forEach((task) => {
            const key = getTaskKey(task);
            taskPoolRef.current.set(key, task);
        });
    }, []);
    /** 从轮询池移除任务 */
    const removeTasksFromPool = (0, react_1.useCallback)((tasks) => {
        tasks.forEach((task) => {
            const key = getTaskKey(task);
            taskPoolRef.current.delete(key);
        });
    }, []);
    /** 执行一次轮询 */
    const pollOnce = (0, react_1.useCallback)(async () => {
        const tasks = Array.from(taskPoolRef.current.values());
        if (!tasks.length)
            return false;
        try {
            const result = await (0, services_1.pollTasks)({
                tableId,
                forcePrompt: false,
                singleGridTaskSubmitRequests: tasks,
                userId: getAliWorkNo(),
            }, bizRequestConfig);
            // API调用失败，标记失败状态并停止轮询
            if (!(result === null || result === void 0 ? void 0 : result.success) || !result.data) {
                hasApiFailureRef.current = true;
                cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'TaskQueryFailedPollingStopped', dm: '任务查询失败，已停止轮询' }));
                return false;
            }
            const { runningTasks: running, finishedTasks: finished, failedTasks } = result.data;
            // 处理已完成的任务
            if (finished === null || finished === void 0 ? void 0 : finished.length) {
                handleFinishedTasks(finished);
                removeTasksFromPool(finished);
            }
            // 处理失败的任务（从池中移除）
            if (failedTasks === null || failedTasks === void 0 ? void 0 : failedTasks.length) {
                removeTasksFromPool(failedTasks);
            }
            // 更新任务池：只保留仍在运行的任务
            if (running === null || running === void 0 ? void 0 : running.length) {
                // 更新运行中任务状态
                setRunningTasks(running);
                // 更新池中的任务为最新状态
                const runningKeys = new Set(running.map(getTaskKey));
                // 移除不在运行列表中的任务
                Array.from(taskPoolRef.current.keys()).forEach((key) => {
                    if (!runningKeys.has(key)) {
                        taskPoolRef.current.delete(key);
                    }
                });
                // 更新运行中任务的信息
                running.forEach((task) => {
                    const key = getTaskKey(task);
                    taskPoolRef.current.set(key, convertTaskToRequest(task));
                });
            }
            else {
                // 没有运行中的任务，清空池和状态
                setRunningTasks([]);
                taskPoolRef.current.clear();
            }
            return taskPoolRef.current.size > 0;
        }
        catch (error) {
            // 接口异常，标记失败状态并停止轮询
            hasApiFailureRef.current = true;
            cn_ui_1.CnMessage.error((error === null || error === void 0 ? void 0 : error.message) ||
                i18n_1.default.get({ id: 'TaskQueryExceptionPollingStopped', dm: '任务查询异常，已停止轮询' }));
            return false;
        }
    }, [tableId, handleFinishedTasks, removeTasksFromPool, bizRequestConfig]);
    /** 检查并更新执行状态 */
    const updateExecutingState = (0, react_1.useCallback)(() => {
        // 检查执行中的列是否还有任务在池中
        const poolKeys = Array.from(taskPoolRef.current.keys());
        const stillExecuting = new Set();
        executingColumnsRef.current.forEach((columnCode) => {
            const hasRunningTask = poolKeys.some((key) => key.startsWith(`${columnCode}-`));
            if (hasRunningTask) {
                stillExecuting.add(columnCode);
            }
        });
        executingColumnsRef.current = stillExecuting;
        setExecutingColumnTask(stillExecuting.size > 0);
    }, []);
    /** 启动统一轮询 */
    const startPolling = (0, react_1.useCallback)(() => {
        // 如果已经在轮询中，直接返回（新任务已加入池中会被下次轮询处理）
        if (isPollingRef.current) {
            return;
        }
        if (taskPoolRef.current.size === 0) {
            return;
        }
        // 重置失败标记
        hasApiFailureRef.current = false;
        isPollingRef.current = true;
        pollingCountRef.current = 0;
        setPollingTasks(true);
        const poll = async () => {
            pollingCountRef.current += 1;
            // 检查是否发生API失败
            if (hasApiFailureRef.current) {
                stopPolling();
                return;
            }
            // 超时检查
            if (pollingCountRef.current > constants_1.MAX_POLLING_COUNT) {
                cn_ui_1.CnMessage.warning(i18n_1.default.get({
                    id: 'TaskExecutionTimedOutPleaseRefre_1388561657',
                    dm: '任务执行超时，请稍后刷新查看结果',
                }));
                stopPolling();
                return;
            }
            // 执行一次轮询
            const hasMoreTasks = await pollOnce();
            // 再次检查是否发生API失败（pollOnce中可能设置了失败标记）
            if (hasApiFailureRef.current) {
                stopPolling();
                return;
            }
            // 更新执行状态
            updateExecutingState();
            if (hasMoreTasks) {
                // 继续轮询
                pollingTimerRef.current = setTimeout(poll, constants_1.POLLING_INTERVAL);
            }
            else {
                // 所有任务完成
                isPollingRef.current = false;
                setPollingTasks(false);
                pollingTimerRef.current = null;
                // 如果有正在执行的列任务刚完成，显示成功消息
                if (executingColumnsRef.current.size > 0) {
                    cn_ui_1.CnMessage.success(i18n_1.default.get({ id: 'AITaskExecutionCompleted', dm: 'AI任务执行完成' }));
                    executingColumnsRef.current.clear();
                    setExecutingColumnTask(false);
                }
            }
        };
        // 立即开始第一次轮询
        pollingTimerRef.current = setTimeout(poll, constants_1.POLLING_INTERVAL);
    }, [pollOnce, stopPolling, updateExecutingState]);
    // ==================== API 方法 ====================
    /** 查询全表任务并开始轮询 */
    const queryAndPollTableTasks = (0, react_1.useCallback)(async () => {
        if (!enabled)
            return;
        try {
            const result = await (0, services_1.queryTableTasks)({ tableId }, bizRequestConfig, cubePlatformCtxRef.current);
            if (!(result === null || result === void 0 ? void 0 : result.success) || !result.data)
                return;
            const { runningTasks: running, finishedTasks: finished } = result.data;
            // 回显已完成任务
            handleFinishedTasks(finished || []);
            // 如果有运行中的任务，加入轮询池
            if (running === null || running === void 0 ? void 0 : running.length) {
                // 更新运行中任务状态
                setRunningTasks(running);
                const requests = running.map(convertTaskToRequest);
                addTasksToPool(requests);
                startPolling();
            }
        }
        catch {
            // 查询失败时静默处理
        }
    }, [enabled, tableId, handleFinishedTasks, addTasksToPool, startPolling, bizRequestConfig]);
    /** 加载所有 AI 列 */
    const loadAiColumns = (0, react_1.useCallback)(async () => {
        if (!enabled || !tableId)
            return [];
        setLoadingAiColumns(true);
        try {
            const result = await (0, services_1.queryAiTableColumns)({ tableId }, bizRequestConfig, cubePlatformCtxRef.current);
            const columns = (result === null || result === void 0 ? void 0 : result.data) || [];
            setAiColumns(columns);
            onAiColumnsLoaded === null || onAiColumnsLoaded === void 0 ? void 0 : onAiColumnsLoaded(columns);
            return columns;
        }
        catch {
            return [];
        }
        finally {
            setLoadingAiColumns(false);
        }
    }, [enabled, tableId, onAiColumnsLoaded, bizRequestConfig]);
    /** 创建或修改 AI 列（不自动执行任务查询） */
    const saveAiColumn = (0, react_1.useCallback)(async (params) => {
        var _a, _b;
        if (!enabled)
            return false;
        // 数据校验：列名不能为空
        if (!((_a = params.columnName) === null || _a === void 0 ? void 0 : _a.trim())) {
            cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'AIColumnNameCannotBeEmpty', dm: 'AI列名称不能为空' }));
            return false;
        }
        // 数据校验：columnCode 不能为空
        if (!((_b = params.columnCode) === null || _b === void 0 ? void 0 : _b.trim())) {
            cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'AIColumnCodeCannotBeEmpty', dm: 'AI列编码不能为空' }));
            return false;
        }
        setSavingAiColumn(true);
        try {
            const { _nodeId } = (0, hooks_1.getLowcodeConfig)();
            if (_nodeId) {
                params.nodeId = _nodeId;
            }
            const result = await (0, services_1.createOrModifyAiColumn)(params, bizRequestConfig, cubePlatformCtxRef.current);
            if (result.success) {
                cn_ui_1.CnMessage.success(i18n_1.default.get({ id: 'AIColumnSavedSuccessfully', dm: 'AI列保存成功' }));
                // 刷新 AI 列列表
                await loadAiColumns();
                return true;
            }
            cn_ui_1.CnMessage.error(result.errorMsg || i18n_1.default.get({ id: 'AIColumnSaveFailed', dm: 'AI列保存失败' }));
            return false;
        }
        catch (error) {
            cn_ui_1.CnMessage.error((error === null || error === void 0 ? void 0 : error.message) || i18n_1.default.get({ id: 'AIColumnSaveFailed', dm: 'AI列保存失败' }));
            return false;
        }
        finally {
            setSavingAiColumn(false);
        }
    }, [enabled, loadAiColumns, bizRequestConfig]);
    /**
     * 提交单列任务并轮询
     * 用于新建 AI 列时执行任务
     * 任务会加入统一轮询池，与其他任务一起轮询
     */
    const submitColumnTasks = (0, react_1.useCallback)(async (columnCode, taskRequests) => {
        if (!enabled || !taskRequests.length)
            return;
        // 标记该列正在执行
        executingColumnsRef.current.add(columnCode);
        setExecutingColumnTask(true);
        try {
            // 第一步：提交任务（forcePrompt = true）
            const submitResult = await (0, services_1.submitTasks)({
                tableId,
                forcePrompt: true,
                singleGridTaskSubmitRequests: taskRequests,
                userId: getAliWorkNo(),
            }, bizRequestConfig);
            if (!(submitResult === null || submitResult === void 0 ? void 0 : submitResult.success)) {
                cn_ui_1.CnMessage.error((submitResult === null || submitResult === void 0 ? void 0 : submitResult.errorMsg) || i18n_1.default.get({ id: 'TaskSubmissionFailed', dm: '任务提交失败' }));
                executingColumnsRef.current.delete(columnCode);
                setExecutingColumnTask(executingColumnsRef.current.size > 0);
                return;
            }
            // 第二步：调用查询接口获取任务状态
            const queryResult = await (0, services_1.pollTasks)({
                tableId,
                forcePrompt: false,
                singleGridTaskSubmitRequests: taskRequests,
                userId: getAliWorkNo(),
            }, bizRequestConfig);
            if (!(queryResult === null || queryResult === void 0 ? void 0 : queryResult.success) || !queryResult.data) {
                cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'FailedToQueryTaskStatus', dm: '查询任务状态失败' }));
                executingColumnsRef.current.delete(columnCode);
                setExecutingColumnTask(executingColumnsRef.current.size > 0);
                return;
            }
            const { finishedTasks: finished, runningTasks: running, failedTasks } = queryResult.data;
            // 回显已完成的任务
            const columnFinished = (finished || []).filter((t) => t.columnCode === columnCode);
            if (columnFinished.length) {
                handleFinishedTasks(columnFinished);
            }
            // 处理失败的任务
            if (failedTasks === null || failedTasks === void 0 ? void 0 : failedTasks.length) {
                const columnFailed = failedTasks.filter((t) => t.columnCode === columnCode);
                if (columnFailed.length) {
                    cn_ui_1.CnMessage.warning(i18n_1.default.get({
                        id: 'ColumnFailedLengthFailedToExecut_499001366',
                        dm: '{columnFailedLength} 个任务执行失败',
                    }, { columnFailedLength: columnFailed.length }));
                }
            }
            // 过滤出当前列的运行中任务
            const columnRunning = (running || []).filter((t) => t.columnCode === columnCode);
            if (!columnRunning.length) {
                // 该列任务已全部完成
                executingColumnsRef.current.delete(columnCode);
                setExecutingColumnTask(executingColumnsRef.current.size > 0);
                cn_ui_1.CnMessage.success(i18n_1.default.get({ id: 'AITaskExecutionCompleted', dm: 'AI任务执行完成' }));
                return;
            }
            // 第三步：将运行中的任务加入轮询池并开始轮询
            const requests = columnRunning.map(convertTaskToRequest);
            addTasksToPool(requests);
            // 启动轮询（如果已在轮询中，会自动合并处理）
            startPolling();
        }
        catch (error) {
            cn_ui_1.CnMessage.error((error === null || error === void 0 ? void 0 : error.message) || i18n_1.default.get({ id: 'TaskSubmissionFailed', dm: '任务提交失败' }));
            executingColumnsRef.current.delete(columnCode);
            setExecutingColumnTask(executingColumnsRef.current.size > 0);
        }
    }, [enabled, tableId, handleFinishedTasks, addTasksToPool, startPolling, bizRequestConfig]);
    // ==================== 生命周期 ====================
    // 注意：不在 Hook 内部自动初始化，由外部（cn-ai-table.tsx）控制初始化时机
    // 这样可以避免重复调用，并确保在 viewsConfigs 加载完成后再初始化
    (0, react_1.useEffect)(() => {
        if (!enabled) {
            stopPolling();
        }
    }, [enabled, stopPolling]);
    // 组件卸载时清理
    (0, react_1.useEffect)(() => {
        return () => {
            if (pollingTimerRef.current) {
                clearTimeout(pollingTimerRef.current);
            }
        };
    }, []);
    // ==================== 返回值 ====================
    return {
        aiColumns,
        loadingAiColumns,
        savingAiColumn,
        finishedTasks,
        runningTasks,
        pollingTasks,
        executingColumnTask,
        loadAiColumns,
        saveAiColumn,
        queryAndPollTableTasks,
        submitColumnTasks,
        stopPolling,
    };
}
