import $i18n from '../../../locales/i18n.js';
/**
 * 常用查询条件 Hook
 */
import * as React from 'react';
import { fetchSuggestions, fetchFieldTransform } from '../api';
import { normalizeTokenValue } from '../../../cn-ai-filter/utils/normalize/normalize-token-value';
import { tokensToSearchParams, convertTokensToSlotConfigs, processTokenOptions, } from '../../utils/token-utils';
import { extractDisplayTextFromTokens } from '../../utils/display/slot-config-display-utils';
import { getPinnedCommonQueries, addPinnedCommonQuery, removePinnedCommonQuery, } from '../../utils/pinned-common-queries-storage';
import { convertLanguageCode } from '../../utils/convert-language-code';
import { parseDynamicDateOption, parseDynamicDateNaturalLanguageToValue, } from '../../utils/display/datetime-picker-display-utils';
import { getDateShortcutLabel, getDateShortcutValue, getDateFilterValueType, } from '../../utils/constants/date-shortcuts';
import { armsHottagLog } from '../../../utils/arms/arms-hot-tag-log.js';
export function useCommonQuery(params) {
    const { senderRef, schema, customRenderForTag, onSearch, setLastSearchParams, operator, code, language, customFieldTransformApi, customSuggestApi, dataDict, } = params;
    // 常用查询条件弹层显示状态
    const [commonQueryVisible, setCommonQueryVisible] = React.useState(false);
    // 常用查询条件数据
    const [commonQueries, setCommonQueries] = React.useState([]);
    const [commonQueriesLoading, setCommonQueriesLoading] = React.useState(false);
    // 钉住的常用查询条件状态
    const [pinnedQueries, setPinnedQueries] = React.useState([]);
    // 转换语言代码（zh-CN -> zh_CN）
    const languageCode = React.useMemo(() => (language ? convertLanguageCode(language) : 'zh_CN'), [language]);
    // 从本地存储加载钉住的常用查询条件
    React.useEffect(() => {
        if (operator && code) {
            const pinned = getPinnedCommonQueries(operator, code);
            setPinnedQueries(pinned);
        }
    }, [operator, code]);
    // 处理 tokens：标准化、转换为 slotConfigs、插入 tags、设置显示文本
    const processTokensAndInsertTags = React.useCallback((tokensToProcess, originalTokens) => {
        var _a, _b;
        // 标准化 tokens 的 value，确保符合组件预期格式
        const normalizedTokens = tokensToProcess.map((token) => normalizeTokenValue(token, schema));
        // 将后端返回的 tokens 与原始 tokens 合并，以便恢复日期快捷选项值
        const tokensWithOriginalValues = normalizedTokens.map((token) => {
            if (token.queryType === 'STRUCTURED' && token.columnName && originalTokens) {
                // 查找原始 tokens 中对应的 token
                const originalToken = originalTokens.find((t) => t.columnName === token.columnName && t.queryType === 'STRUCTURED');
                if (originalToken) {
                    // 优先从 naturalLanguage 中提取日期快捷选项值
                    if (originalToken.naturalLanguage) {
                        const shortcutValue = getDateShortcutValue(originalToken.naturalLanguage);
                        if (shortcutValue) {
                            return {
                                ...token,
                                naturalLanguage: originalToken.naturalLanguage,
                                _originalDateShortcutValue: shortcutValue,
                            };
                        }
                        const dynamicValue = parseDynamicDateNaturalLanguageToValue(originalToken.naturalLanguage);
                        if (dynamicValue) {
                            return {
                                ...token,
                                naturalLanguage: originalToken.naturalLanguage,
                                _originalDateShortcutValue: dynamicValue,
                            };
                        }
                    }
                    // 原始 token 无 naturalLanguage 时，用 value 判断日期快捷/动态/范围（兼容旧逻辑）
                    const originalValue = Array.isArray(originalToken.value)
                        ? originalToken.value[0]
                        : originalToken.value;
                    if (typeof originalValue !== 'string')
                        return token;
                    const valueType = getDateFilterValueType(originalValue);
                    if (valueType === 'dynamic') {
                        const chineseLabel = parseDynamicDateOption(originalValue) || '';
                        return {
                            ...token,
                            value: Array.isArray(token.value) && token.value.length > 0 ? token.value : [],
                            naturalLanguage: chineseLabel,
                            _originalDateShortcutValue: originalValue,
                        };
                    }
                    if (valueType === 'shortcut' && Array.isArray(token.value) && token.value.length > 0) {
                        return {
                            ...token,
                            naturalLanguage: getDateShortcutLabel(originalValue),
                            _originalDateShortcutValue: originalValue,
                        };
                    }
                    if (valueType === 'dateRange') {
                        const [, rangeStr] = originalValue.split(':');
                        const [startDateStr, endDateStr] = (rangeStr || '').split(',');
                        return {
                            ...token,
                            _originalDateShortcutValue: originalValue,
                            naturalLanguage: startDateStr && endDateStr
                                ? $i18n.get({
                                    id: 'StartDateStrToEndDateStr',
                                    dm: '{startDateStr} 至 {endDateStr}',
                                }, { startDateStr, endDateStr })
                                : undefined,
                        };
                    }
                }
            }
            return token;
        });
        // 转换 tokens 为 slotConfigs 和 displayTexts
        const { slotConfigs, displayTexts } = convertTokensToSlotConfigs(tokensWithOriginalValues, schema, customRenderForTag);
        // 插入所有配置到输入框
        if (slotConfigs.length > 0 && senderRef.current) {
            (_b = (_a = senderRef.current).insert) === null || _b === void 0 ? void 0 : _b.call(_a, slotConfigs);
        }
        // 设置显示文本：按照原始 tokens 的顺序组合自然语言和结构化数据
        const displayText = extractDisplayTextFromTokens(originalTokens || [], tokensWithOriginalValues, displayTexts);
        setLastSearchParams(displayText);
        return tokensWithOriginalValues;
    }, [schema, customRenderForTag, setLastSearchParams, senderRef]);
    // 获取常用查询条件
    React.useEffect(() => {
        if (!commonQueryVisible || !operator || !code) {
            return;
        }
        const fetchCommonQueries = async () => {
            var _a;
            try {
                setCommonQueriesLoading(true);
                const columns = dataDict || [];
                const result = await fetchSuggestions({
                    customSuggestApi,
                    operator,
                    code,
                    languageCode,
                    columns,
                });
                if ((result === null || result === void 0 ? void 0 : result.success) && ((_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.translators)) {
                    const translators = Array.isArray(result.data.translators) ? result.data.translators : [];
                    // 去重处理：根据 id 去重，避免重复数据
                    const seenIds = new Set();
                    const uniqueTranslators = translators.filter((translator) => {
                        var _a;
                        const translatorId = (_a = translator === null || translator === void 0 ? void 0 : translator.id) !== null && _a !== void 0 ? _a : '';
                        if (seenIds.has(translatorId)) {
                            return false;
                        }
                        seenIds.add(translatorId);
                        return true;
                    });
                    setCommonQueries(uniqueTranslators);
                }
                else {
                    setCommonQueries([]);
                }
            }
            catch (error) {
                // eslint-disable-next-line no-console
                console.error('Failed to fetch common queries:', error);
                setCommonQueries([]);
            }
            finally {
                setCommonQueriesLoading(false);
            }
        };
        fetchCommonQueries();
    }, [commonQueryVisible, customSuggestApi, operator, code, languageCode, dataDict]);
    // 处理常用查询条件点击：将 tokens 转换为 tag 插入到输入框，并自动触发查询
    const handleCommonQueryClick = React.useCallback(async (tokens) => {
        var _a, _b, _c, _d;
        if (!senderRef.current || !schema)
            return;
        // 提取查询条件的显示文本用于埋点
        const hasNaturalLanguage = tokens.some((t) => t.queryType === 'NATURAL_LANGUAGE');
        const naturalLanguageText = hasNaturalLanguage
            ? tokens
                .filter((t) => t.queryType === 'NATURAL_LANGUAGE')
                .map((t) => t.naturalLanguage)
                .join(' ')
            : '';
        const structuredCount = tokens.filter((t) => t.queryType === 'STRUCTURED').length;
        armsHottagLog({
            hottag: 'cn-ai-filter.commonQuery.click',
            name: $i18n.get({ id: 'ClickCommonQuery', dm: '点击常用查询' }),
            c6: naturalLanguageText ||
                $i18n.get({
                    id: 'StructuredQueryStructuredCountCo_935376310',
                    dm: '结构化查询({structuredCount}个条件)',
                }, { structuredCount }),
        });
        const hasStructured = tokens.some((t) => t.queryType === 'STRUCTURED');
        // 清空输入框
        (_b = (_a = senderRef.current).clear) === null || _b === void 0 ? void 0 : _b.call(_a);
        // 处理结构化 tokens：过滤 options 只保留选中项
        const processedTokens = tokens.map((token) => processTokenOptions(token));
        // 统一处理：调用 API 进行转换/标准化
        try {
            const columns = dataDict || [];
            const transformResult = await fetchFieldTransform({
                customFieldTransformApi,
                operator,
                code,
                languageCode,
                tokens: processedTokens,
                columns,
            });
            const responseData = transformResult === null || transformResult === void 0 ? void 0 : transformResult.data;
            const isSuccess = (transformResult === null || transformResult === void 0 ? void 0 : transformResult.success) && responseData;
            if (!isSuccess || !(responseData === null || responseData === void 0 ? void 0 : responseData.tokens) || responseData.tokens.length === 0) {
                // 如果 tokens 为空数组，说明无法转换为结构化查询
                // 纯自然语言且转换失败：显示自然语言文本，查询全部数据
                if (hasNaturalLanguage && !hasStructured) {
                    const naturalLanguageDisplayText = processedTokens
                        .filter((t) => t.queryType === 'NATURAL_LANGUAGE')
                        .map((t) => t.naturalLanguage)
                        .join(' ');
                    if (naturalLanguageDisplayText && senderRef.current) {
                        (_d = (_c = senderRef.current).insert) === null || _d === void 0 ? void 0 : _d.call(_c, [
                            {
                                type: 'text',
                                value: naturalLanguageDisplayText,
                            },
                        ]);
                    }
                    setLastSearchParams(naturalLanguageDisplayText || $i18n.get({ id: 'AllData', dm: '全部数据' }));
                    if (onSearch) {
                        onSearch({});
                    }
                }
                return;
            }
            // 处理 tokens：标准化、转换为 slotConfigs、插入 tags、设置显示文本
            // 传入原始 tokens 作为第二个参数，用于提取自然语言文本显示在「已为您查询」
            const normalizedTokens = processTokensAndInsertTags(responseData.tokens, tokens);
            // 构建查询参数并触发搜索
            const finalSearchParams = tokensToSearchParams(normalizedTokens);
            if (onSearch && Object.keys(finalSearchParams).length > 0) {
                onSearch(finalSearchParams);
            }
        }
        catch (error) {
            console.error('[常用查询条件] 调用 ai_translate 失败:', error);
        }
    }, [
        senderRef,
        schema,
        setLastSearchParams,
        operator,
        code,
        languageCode,
        customFieldTransformApi,
        dataDict,
        onSearch,
        processTokensAndInsertTags,
    ]);
    // 使用 useMemo 计算未钉住的查询条件
    const unpinnedQueries = React.useMemo(() => {
        // 获取所有已钉住的 translatorId 集合
        const pinnedTranslatorIds = new Set(pinnedQueries.map((q) => q.translatorId));
        // 过滤掉已钉住的查询条件，得到未钉住的推荐查询条件
        return commonQueries.filter((translator) => {
            var _a;
            const translatorId = (_a = translator === null || translator === void 0 ? void 0 : translator.id) !== null && _a !== void 0 ? _a : '';
            return !pinnedTranslatorIds.has(translatorId);
        });
    }, [commonQueries, pinnedQueries]);
    // 钉住常用查询条件
    const handlePinCommonQuery = React.useCallback((translator) => {
        if (!operator || !code)
            return;
        armsHottagLog({
            hottag: 'cn-ai-filter.commonQuery.pin',
            name: $i18n.get({ id: 'PinningQueryCriteria', dm: '钉住查询条件' }),
            c6: translator.id || '',
        });
        addPinnedCommonQuery(operator, code, translator);
        const pinned = getPinnedCommonQueries(operator, code);
        setPinnedQueries(pinned);
    }, [operator, code]);
    // 取消钉住常用查询条件
    const handleUnpinCommonQuery = React.useCallback((queryId) => {
        if (!operator || !code)
            return;
        armsHottagLog({
            hottag: 'cn-ai-filter.commonQuery.unpin',
            name: $i18n.get({ id: 'UnpinQueryCriteria', dm: '取消钉住查询条件' }),
            c6: queryId,
        });
        removePinnedCommonQuery(operator, code, queryId);
        const pinned = getPinnedCommonQueries(operator, code);
        setPinnedQueries(pinned);
    }, [operator, code]);
    return {
        commonQueryVisible,
        setCommonQueryVisible,
        commonQueries,
        commonQueriesLoading,
        handleCommonQueryClick,
        pinnedQueries,
        unpinnedQueries,
        handlePinCommonQuery,
        handleUnpinCommonQuery,
    };
}
