"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSmartFollowDetail = useSmartFollowDetail;
/**
 * 智能跟单详情摘要钩子。
 * 提交单行跟单详情任务，然后轮询直到完成。
 *
 * 安全保证:
 * - MAX_POLLING_COUNT 超时
 * - isMountedRef 卸载保护
 * - 请求所有权验证 (rowId token)
 * - 共享 summaryCache 集成
 */
const i18n_1 = __importDefault(require("../../../../../locales/i18n.js"));
const react_1 = require("react");
const services_1 = require("../../../services");
const format_column_definitions_1 = require("../../../../../cn-ai-agent/utils/format-column-definitions");
const constants_1 = require("../../../hooks/constants");
const env_1 = require("../../../../../utils/env/index.js");
const summary_cache_1 = require("./summary-cache");
const row_data_cache_1 = require("./row-data-cache");
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 SUMMARY_MODE = 'smartFollowDetail';
function useSmartFollowDetail({ tableId, recordId, recordData, columnDefinitions, conversationId, viewData, enabled = true, bizRequestConfig, }) {
    const [status, setStatus] = (0, react_1.useState)('idle');
    const [summary, setSummary] = (0, react_1.useState)('');
    const [gmtModified, setGmtModified] = (0, react_1.useState)(undefined);
    const pollingTimerRef = (0, react_1.useRef)(null);
    const pollingCountRef = (0, react_1.useRef)(0);
    const currentRowIdRef = (0, react_1.useRef)(null);
    const isMountedRef = (0, react_1.useRef)(true);
    // 用数据指纹（行数 + 首行/末行 id）判断 viewData 是否真正变化，
    // 避免仅引用变化就全量清空摘要缓存。
    const viewDataFingerprintRef = (0, react_1.useRef)('');
    const stopPolling = (0, react_1.useCallback)(() => {
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        pollingCountRef.current = 0;
    }, []);
    const clearCache = (0, react_1.useCallback)(() => {
        summary_cache_1.summaryCache.clear();
    }, []);
    const safeSetResult = (0, react_1.useCallback)((rowId, newStatus, newSummary, newGmtModified) => {
        if (!isMountedRef.current || currentRowIdRef.current !== rowId)
            return;
        setStatus(newStatus);
        setSummary(newSummary);
        setGmtModified(newGmtModified);
        const key = (0, summary_cache_1.buildCacheKey)(tableId, rowId, SUMMARY_MODE);
        summary_cache_1.summaryCache.set(key, {
            status: newStatus,
            summary: newSummary,
            gmtModified: newGmtModified,
        });
    }, [tableId]);
    const pollDetailTask = (0, react_1.useCallback)(async (rowId) => {
        if (!isMountedRef.current || currentRowIdRef.current !== rowId)
            return;
        pollingCountRef.current += 1;
        if (pollingCountRef.current > constants_1.MAX_POLLING_COUNT) {
            safeSetResult(rowId, 'error', i18n_1.default.get({
                id: 'GenerateSummaryTimeoutPleaseTryA_308174635',
                dm: '生成总结超时，请重试',
            }));
            stopPolling();
            return;
        }
        try {
            const result = await (0, services_1.queryFollowOrderTask)({ tableId, rowIds: rowId }, bizRequestConfig);
            if (!isMountedRef.current || currentRowIdRef.current !== rowId)
                return;
            if (!result) {
                pollingTimerRef.current = setTimeout(() => pollDetailTask(rowId), constants_1.POLLING_INTERVAL);
                return;
            }
            const { finishedTasks: finished = [], runningTasks: running = [] } = result;
            const task = finished.find((t) => String(t.rowId) === rowId);
            if (task === null || task === void 0 ? void 0 : task.jobOutput) {
                safeSetResult(rowId, 'done', task.jobOutput, task.gmtModified);
                stopPolling();
            }
            else if (running.length > 0 || finished.length === 0) {
                pollingTimerRef.current = setTimeout(() => pollDetailTask(rowId), constants_1.POLLING_INTERVAL);
            }
            else {
                safeSetResult(rowId, 'done', '', task === null || task === void 0 ? void 0 : task.gmtModified);
                stopPolling();
            }
        }
        catch {
            if (!isMountedRef.current || currentRowIdRef.current !== rowId)
                return;
            pollingTimerRef.current = setTimeout(() => pollDetailTask(rowId), constants_1.POLLING_INTERVAL);
        }
    }, [tableId, stopPolling, safeSetResult, bizRequestConfig]);
    const fetchDetail = (0, react_1.useCallback)(async (rowId, record, forceRefresh = false) => {
        if (!forceRefresh) {
            const key = (0, summary_cache_1.buildCacheKey)(tableId, rowId, SUMMARY_MODE);
            const cached = summary_cache_1.summaryCache.get(key);
            if (cached && (cached.status === 'done' || cached.status === 'error')) {
                setStatus(cached.status);
                setSummary(cached.summary);
                setGmtModified(cached.gmtModified);
                return;
            }
        }
        stopPolling();
        if (!record || !(columnDefinitions === null || columnDefinitions === void 0 ? void 0 : columnDefinitions.length) || !tableId)
            return;
        const nonAiColumnDefinitions = columnDefinitions.filter((col) => !col.isAiColumn && col.format !== 'ai-generate');
        const formattedColumnDefs = (0, format_column_definitions_1.formatColumnDefinitions)(nonAiColumnDefinitions);
        // 优先从 rowDataCache 获取，使用同一数据源
        let rowDataDTO = row_data_cache_1.rowDataCache.get(tableId, rowId);
        if (!rowDataDTO) {
            const aiColumnDataIndexes = new Set(columnDefinitions
                .filter((col) => col.isAiColumn || col.format === 'ai-generate')
                .map((col) => col.dataIndex));
            const filteredRowData = {};
            Object.keys(record).forEach((key) => {
                if (!aiColumnDataIndexes.has(key)) {
                    const value = record[key];
                    filteredRowData[key] = value != null ? String(value) : '';
                }
            });
            rowDataDTO = { rowId, rowData: filteredRowData };
        }
        currentRowIdRef.current = rowId;
        if (forceRefresh) {
            const key = (0, summary_cache_1.buildCacheKey)(tableId, rowId, SUMMARY_MODE);
            summary_cache_1.summaryCache.delete(key);
        }
        setStatus('loading');
        setSummary('');
        try {
            await (0, services_1.submitOrderFollowDetailTask)({
                tableId,
                columnDefinitions: formattedColumnDefs,
                rowDataDTOS: [rowDataDTO],
                userId: getAliWorkNo(),
                conversationId,
                forcePrompt: true,
            }, bizRequestConfig);
            if (isMountedRef.current && currentRowIdRef.current === rowId) {
                pollDetailTask(rowId);
            }
        }
        catch {
            safeSetResult(rowId, 'error', i18n_1.default.get({
                id: 'FailedToGenerateSummaryPleaseTry_1755030794',
                dm: '生成总结失败，请重试',
            }));
            stopPolling();
        }
    }, [
        tableId,
        columnDefinitions,
        conversationId,
        stopPolling,
        pollDetailTask,
        safeSetResult,
        bizRequestConfig,
    ]);
    // viewData 内容真正变化时才清空缓存（按行数 + 首行/末行 id 判断）
    (0, react_1.useEffect)(() => {
        var _a, _b, _c, _d, _e;
        const len = (_a = viewData === null || viewData === void 0 ? void 0 : viewData.length) !== null && _a !== void 0 ? _a : 0;
        const firstId = len > 0 ? ((_c = (_b = viewData[0]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : '') : '';
        const lastId = len > 1 ? ((_e = (_d = viewData[len - 1]) === null || _d === void 0 ? void 0 : _d.id) !== null && _e !== void 0 ? _e : '') : '';
        const fp = `${len}:${firstId}:${lastId}`;
        if (viewDataFingerprintRef.current && viewDataFingerprintRef.current !== fp) {
            clearCache();
        }
        viewDataFingerprintRef.current = fp;
    }, [viewData, clearCache]);
    // recordId / enabled change -> fetch detail
    (0, react_1.useEffect)(() => {
        if (enabled && recordId && recordData && !env_1.isEditor) {
            const rowId = String(recordId);
            currentRowIdRef.current = rowId;
            fetchDetail(rowId, recordData);
        }
        else if (!recordId || !enabled) {
            stopPolling();
            if (!recordId) {
                currentRowIdRef.current = null;
            }
            setStatus('idle');
            setSummary('');
            setGmtModified(undefined);
        }
        return () => stopPolling();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [recordId, enabled]);
    // Lifecycle
    (0, react_1.useEffect)(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false;
            stopPolling();
        };
    }, [stopPolling]);
    const refresh = (0, react_1.useCallback)(() => {
        if (!enabled || status === 'loading' || !recordId || !recordData)
            return;
        fetchDetail(String(recordId), recordData, true);
    }, [enabled, status, recordId, recordData, fetchDetail]);
    return { status, summary, gmtModified, refresh, clearCache };
}
