"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.CnAiFilter = void 0;
const i18n_1 = __importDefault(require("../../locales/i18n.js"));
const React = __importStar(require("react"));
const cn_sender_1 = require("../../cn-sender");
const use_insert_field_tag_1 = require("../../hooks/use-insert-field-tag.js");
const FieldTagPopupWrapper_1 = require("../../field-tag-popup-wrapper/FieldTagPopupWrapper");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const api_1 = require("./api");
const utils_1 = require("../../utils/index.js");
const copy_to_clipboard_1 = __importDefault(require("copy-to-clipboard"));
const transform_params_1 = require("./utils/transform-params");
const get_filter_meta_data_1 = require("./utils/get-filter-meta-data");
const use_common_query_1 = require("./hooks/use-common-query");
const convert_language_code_1 = require("../utils/convert-language-code");
const token_utils_1 = require("../utils/token-utils");
const common_query_list_1 = require("./components/common-query-list");
require("./cn-ai-filter.scss");
const stark_data_1 = require("@ice/stark-data");
const cn_ai_list_event_context_1 = require("../../cn-ai-agent/context/cn-ai-list-event-context");
const event_constants_1 = require("../../cn-ai-agent/constants/event-constants");
const convert_data_dict_1 = require("./utils/convert-data-dict");
const convert_internal_tokens_to_api_tokens_1 = require("./utils/convert-internal-tokens-to-api-tokens");
const normalize_token_value_1 = require("../utils/normalize/normalize-token-value");
const date_shortcuts_1 = require("../utils/constants/date-shortcuts");
const datetime_picker_display_utils_1 = require("../utils/display/datetime-picker-display-utils");
const arms_hot_tag_log_1 = require("../../utils/arms/arms-hot-tag-log.js");
const floating_layer_1 = require("../../utils/floating-layer.js");
const env_1 = require("../../utils/env/index.js");
const use_filter_agent_toggle_1 = require("./hooks/use-filter-agent-toggle");
const get_operator_1 = require("../utils/get-operator");
const context_1 = require("../../theme/context.js");
const field_icon_utils_1 = require("../../cn-ai-table/view/utils/field-icon-utils");
const lookup_field_config_utils_1 = require("../utils/lookup-field-config-utils");
const { createForm } = cn_ui_1.formilyCore;
/**
 * 按字段路径读取 formValue，兼容：
 * - 扁平字段：`formValue[path]`
 * - 嵌套字段：`formValue.a.b.c`
 *
 * @param formValue 当前表单值
 * @param path 字段路径（可能是点路径）
 * @returns 字段数据对象或原始值；未命中返回 undefined
 */
function getFieldDataByPath(formValue, path) {
    if (!formValue || !path)
        return undefined;
    if (formValue[path] !== undefined)
        return formValue[path];
    return path.split('.').reduce((acc, key) => {
        if (!acc || typeof acc !== 'object')
            return undefined;
        return acc[key];
    }, formValue);
}
const CnAiFilterView = (props) => {
    var _a, _b;
    const eventNames = (0, cn_ai_list_event_context_1.useCnAiListEventNames)();
    const listInstanceKey = (0, cn_ai_list_event_context_1.useCnAiListInstanceKey)();
    const { onSearch, popupTriggerKey = '/', // 可以自定义触发键，默认为 "/"
    customPopupProps, // 自定义弹窗配置
    schema, customFieldTransformApi, operator: operatorProp, id, showAgentIcon = true, onLastSearchParamsChange, bizRequestConfig, lookupFieldConfigs, ...restProps } = props;
    const operator = operatorProp !== null && operatorProp !== void 0 ? operatorProp : (0, get_operator_1.getOperator)();
    const pageId = id !== null && id !== void 0 ? id : '';
    const brandAssets = (0, context_1.useBrandAssets)();
    const getFieldIcon = (0, field_icon_utils_1.useFieldIcon)();
    // 从 restProps 中提取 form 和 formProps（这些是 SenderProps 的一部分）
    const { form: formFromProps, formProps } = restProps;
    /** 筛选内字段弹层共用一个 Formily 实例（x-reactions）；tag 删除时 Sender 会同步清对应 form 字段，避免再插入同字段遗留值 */
    const filterFormRef = React.useRef(null);
    if (!filterFormRef.current) {
        filterFormRef.current = createForm({ ...(formProps || {}) });
    }
    const form = formFromProps !== null && formFromProps !== void 0 ? formFromProps : filterFormRef.current;
    // 创建 ref 来访问 CnSender 的 insert 方法
    const senderRef = React.useRef(null);
    // 数据字典 ref，用于承载转换后的字段数据
    const dataDictRef = React.useRef([]);
    // 加载状态：是否正在调用翻译 API
    const [isLoading, setIsLoading] = React.useState(false);
    // 上一次的搜索参数
    const [lastSearchParams, setLastSearchParams] = React.useState('');
    const [lookupConfigMap, setLookupConfigMap] = React.useState(() => (0, lookup_field_config_utils_1.normalizeLookupSearchConfigs)(lookupFieldConfigs));
    /** 始终指向最新 map，避免 translate 回调链里闭包仍用「增列前」的 lookupConfigMap，导致 joinTableColumns 少列 */
    const lookupConfigMapRef = React.useRef(lookupConfigMap);
    lookupConfigMapRef.current = lookupConfigMap;
    const { enableAIAgent, agentVisible, handleToggleAgent } = (0, use_filter_agent_toggle_1.useFilterAgentToggle)(showAgentIcon);
    const agentToggleTitle = React.useMemo(() => agentVisible
        ? i18n_1.default.get({ id: 'HiddenAIAssistant', dm: '隐藏AI助理' })
        : i18n_1.default.get({ id: 'ShowAIAssistant', dm: '显示AI助理' }), [agentVisible]);
    React.useEffect(() => {
        onLastSearchParamsChange === null || onLastSearchParamsChange === void 0 ? void 0 : onLastSearchParamsChange(lastSearchParams);
    }, [lastSearchParams, onLastSearchParamsChange]);
    /** 仅同步宿主显式传入的 lookup 列表；undefined 表示未受控，不要用 {} 覆盖总线事件已下发的全量配置 */
    React.useEffect(() => {
        if (lookupFieldConfigs == null)
            return;
        setLookupConfigMap((0, lookup_field_config_utils_1.normalizeLookupSearchConfigs)(lookupFieldConfigs));
    }, [lookupFieldConfigs]);
    React.useEffect(() => {
        const handleLookupConfigUpdate = (payload) => {
            const nextLookupConfigMap = (0, lookup_field_config_utils_1.normalizeLookupSearchConfigs)(payload === null || payload === void 0 ? void 0 : payload.lookupSearchConfigs);
            setLookupConfigMap(nextLookupConfigMap);
        };
        stark_data_1.event.on(eventNames.LOOKUP_FIELD_SEARCH_CONFIG_UPDATE, handleLookupConfigUpdate);
        return () => {
            stark_data_1.event.off(eventNames.LOOKUP_FIELD_SEARCH_CONFIG_UPDATE, handleLookupConfigUpdate);
        };
    }, [eventNames.LOOKUP_FIELD_SEARCH_CONFIG_UPDATE]);
    // AbortController 引用，用于取消正在进行的请求
    const abortControllerRef = React.useRef(null);
    const mergedSchema = React.useMemo(() => (0, lookup_field_config_utils_1.mergeLookupSchemaPropertiesToJoinTableParams)(schema, lookupConfigMap), [schema, lookupConfigMap]);
    React.useEffect(() => {
        // eslint-disable-next-line no-console -- 调试 mergeLookupSchema（mergeLookupSchemaPropertiesToJoinTableParams）结果
        console.log('[CnAiFilter] mergedSchema', mergedSchema);
    }, [mergedSchema]);
    // 清洗 schema 数据，提取字段元数据并转换为数据字典格式
    React.useEffect(() => {
        if (mergedSchema) {
            const cleanedData = (0, get_filter_meta_data_1.cleanSchemaData)(mergedSchema);
            const dataDict = (0, convert_data_dict_1.convertDataDict)(cleanedData);
            dataDictRef.current = dataDict;
        }
    }, [mergedSchema]);
    // formMap 现在在 SlotTextArea 中管理，不再需要在这里定义
    // 获取语言代码
    const language = (0, transform_params_1.getLanguage)();
    const dispatchSearch = React.useCallback((searchParams, formValue) => {
        if (!onSearch)
            return;
        const finalSearchParams = (0, lookup_field_config_utils_1.buildLookupJoinSearchPayload)({
            lookupConfigMap: lookupConfigMapRef.current,
            searchParams,
            formValue,
        });
        onSearch(finalSearchParams);
        stark_data_1.event.emit(eventNames.PAGINATION_CHANGE);
    }, [onSearch, eventNames.PAGINATION_CHANGE]);
    // 常用查询条件相关逻辑（包含钉住功能）
    const { commonQueryVisible, setCommonQueryVisible, commonQueriesLoading, handleCommonQueryClick, pinnedQueries, unpinnedQueries, handlePinCommonQuery, handleUnpinCommonQuery, } = (0, use_common_query_1.useCommonQuery)({
        senderRef,
        schema: mergedSchema === null || mergedSchema === void 0 ? void 0 : mergedSchema.properties,
        onSearch: (params) => dispatchSearch(params),
        setLastSearchParams,
        operator,
        code: pageId,
        language,
        customFieldTransformApi: ((_a = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.filter) === null || _a === void 0 ? void 0 : _a.fieldTransformUrl) || customFieldTransformApi,
        customSuggestApi: (_b = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.filter) === null || _b === void 0 ? void 0 : _b.suggestionUrl,
        dataDict: dataDictRef.current,
    });
    // 组件卸载时清理 AbortController
    React.useEffect(() => {
        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
                abortControllerRef.current = null;
            }
        };
    }, []);
    // 使用公共 API 插入字段 tag
    const insertFieldTag = (0, use_insert_field_tag_1.useInsertFieldTag)(senderRef, popupTriggerKey, (value, onValueChange, renderProps, item, formMapRef, onFormMapUpdate) => {
        return (React.createElement(FieldTagPopupWrapper_1.FieldTagPopupWrapper, { value: value, onValueChange: onValueChange, renderProps: renderProps, item: item, formMapRef: formMapRef, onFormMapUpdate: onFormMapUpdate }));
    });
    // 创建增强的 customPopupProps，将 onFieldSelect 集成到 asyncSelectProps.onChange 中
    const enhancedCustomPopupProps = React.useMemo(() => {
        const { onFieldSelect, asyncSelectProps, ...rest } = customPopupProps || {};
        // 如果提供了 onFieldSelect，使用它；否则使用内部的 insertFieldTag
        const fieldSelectHandler = onFieldSelect || insertFieldTag;
        return {
            ...rest,
            onFieldSelect: fieldSelectHandler,
            asyncSelectProps: {
                ...asyncSelectProps,
                placeholder: i18n_1.default.get({
                    id: 'SelectTheFieldsThatNeedToBeIntro_2004559010',
                    dm: '选择需要引入的字段',
                }),
                itemRender: (item) => {
                    var _a;
                    return (React.createElement(React.Fragment, null,
                        React.createElement("div", { className: `cn-sender-schema-menu-option-content` },
                            React.createElement("img", { src: getFieldIcon((_a = item.fieldConfig) === null || _a === void 0 ? void 0 : _a['x-component']), alt: item.label, className: `cn-sender-schema-menu-option-icon`, style: { width: '16px', height: '16px' } }),
                            React.createElement("span", { className: `cn-sender-schema-menu-option-label` }, item.label))));
                },
                onChange: (value, actionType, item) => {
                    // 先调用自定义的 onChange（如果存在）
                    if (asyncSelectProps === null || asyncSelectProps === void 0 ? void 0 : asyncSelectProps.onChange) {
                        asyncSelectProps.onChange(value, actionType, item);
                    }
                    // 然后调用 onFieldSelect 回调
                    const fieldConfig = item === null || item === void 0 ? void 0 : item.fieldConfig;
                    if (value && fieldConfig) {
                        (0, arms_hot_tag_log_1.armsHottagLog)({
                            hottag: 'cn-ai-filter.selectField',
                            name: i18n_1.default.get({ id: 'SelectField', dm: '选择字段' }),
                            c6: value,
                        });
                        if (onFieldSelect) {
                            // 如果提供了自定义的 onFieldSelect，调用它
                            onFieldSelect({
                                fieldKey: value,
                                fieldConfig,
                            });
                        }
                        else {
                            // 否则使用内部的 insertFieldTag
                            insertFieldTag(value, fieldConfig);
                        }
                    }
                },
            },
        };
    }, [customPopupProps, insertFieldTag, getFieldIcon]);
    // 停止加载：取消正在进行的请求
    const handleStopLoading = React.useCallback(() => {
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-filter.stopLoading',
            name: i18n_1.default.get({ id: 'StopLoading', dm: '停止加载' }),
        });
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
            abortControllerRef.current = null;
        }
        setIsLoading(false);
    }, []);
    // 包装 onSearch，点击发送按钮时首先会向翻译 API 发起请求
    const handleSubmit = React.useCallback(async (value, slotConfig, skill, formValue) => {
        var _a, _b, _c, _d, _e, _f;
        // 如果查询的 value 为空，表示查询全部数据，直接调用 onSearch
        if (!value || !value.trim()) {
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-filter.search',
                name: i18n_1.default.get({ id: 'Search', dm: '搜索' }),
                c6: i18n_1.default.get({ id: 'AllData', dm: '全部数据' }),
            });
            // 用户未输入任何内容，不展示「已为您查询」提示
            setLastSearchParams('');
            dispatchSearch({});
            return;
        }
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-filter.search',
            name: i18n_1.default.get({ id: 'Search', dm: '搜索' }),
            c6: value,
            c7: JSON.stringify(slotConfig),
            c8: JSON.stringify(formValue),
        });
        // 点击发送按钮时，首先会向翻译 API 发起请求
        try {
            // 创建新的 AbortController
            const abortController = new AbortController();
            abortControllerRef.current = abortController;
            setIsLoading(true);
            const finalSlotConfig = slotConfig || [];
            const finalFormValue = formValue || {};
            const internalTokens = finalSlotConfig.length > 0
                ? (0, utils_1.convertSlotConfigToInternalTokens)(finalSlotConfig, finalFormValue)
                : [];
            // 检查必要参数
            if (!operator) {
                // eslint-disable-next-line no-console
                console.error('Operator is required for field transform API');
                setIsLoading(false);
                return;
            }
            // 转换语言代码（zh-CN -> zh_CN）
            const languageCode = (0, convert_language_code_1.convertLanguageCode)(language);
            // 将内部 tokens 转换为 API tokens 格式
            const apiTokens = (0, convert_internal_tokens_to_api_tokens_1.convertInternalTokensToApiTokens)(internalTokens, value, mergedSchema === null || mergedSchema === void 0 ? void 0 : mergedSchema.properties);
            // 获取 columns（从 dataDictRef）
            const columns = dataDictRef.current.map((item) => ({
                displayName: item.displayName,
                columnName: item.columnName,
                columnType: item.columnType,
                ...(item.options && { options: item.options }),
            }));
            // 1. 调用翻译接口
            const transformResult = await (0, api_1.fetchFieldTransform)({
                customFieldTransformApi: ((_a = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.filter) === null || _a === void 0 ? void 0 : _a.fieldTransformUrl) || customFieldTransformApi,
                operator,
                code: pageId,
                languageCode,
                tokens: apiTokens,
                columns,
                signal: abortController.signal, // 传递 signal 用于取消请求
            });
            // 2. 处理接口响应数据
            // 新接口响应结构: { success: true, data: { tokens: [...] } }
            const responseData = transformResult === null || transformResult === void 0 ? void 0 : transformResult.data;
            // 检查响应是否成功
            const isSuccess = (transformResult === null || transformResult === void 0 ? void 0 : transformResult.success) && (responseData === null || responseData === void 0 ? void 0 : responseData.tokens);
            // 检查请求是否被取消
            if ((_b = abortControllerRef.current) === null || _b === void 0 ? void 0 : _b.signal.aborted) {
                return;
            }
            if (isSuccess && (responseData === null || responseData === void 0 ? void 0 : responseData.tokens)) {
                // 标准化 tokens 的 value，确保符合组件预期格式
                const normalizedTokens = responseData.tokens.map((token) => (0, normalize_token_value_1.normalizeTokenValue)(token, (mergedSchema === null || mergedSchema === void 0 ? void 0 : mergedSchema.properties) || {}));
                // 检查是否有结构化数据
                const hasStructuredTokensInResponse = normalizedTokens.some((token) => token.queryType === 'STRUCTURED');
                // 如果有结构化数据，将输入框中的自然语言转换为 tags
                if (hasStructuredTokensInResponse && senderRef.current) {
                    // 清空输入框
                    (_d = (_c = senderRef.current).clear) === null || _d === void 0 ? void 0 : _d.call(_c);
                    // 转换 tokens 为 slotConfigs
                    const customRenderForTag = (tagValue, onValueChange, renderProps, item, formMapRef, onFormMapUpdate) => {
                        return (React.createElement(FieldTagPopupWrapper_1.FieldTagPopupWrapper, { value: tagValue, onValueChange: onValueChange, renderProps: renderProps, item: item, formMapRef: formMapRef, onFormMapUpdate: onFormMapUpdate }));
                    };
                    // 将后端返回的 tokens 与原始 formValue 合并，以便恢复日期快捷选项值
                    const tokensWithOriginalValues = normalizedTokens.map((token) => {
                        if (token.queryType !== 'STRUCTURED' || !token.columnName)
                            return token;
                        const originalFieldData = getFieldDataByPath(finalFormValue, token.columnName);
                        let originalValue;
                        if (originalFieldData === null || originalFieldData === void 0 ? void 0 : originalFieldData.values) {
                            originalValue = Array.isArray(originalFieldData.values)
                                ? originalFieldData.values[0]
                                : originalFieldData.values;
                        }
                        if (typeof originalValue !== 'string')
                            return token;
                        const valueType = (0, date_shortcuts_1.getDateFilterValueType)(originalValue);
                        if (valueType === 'dateRange') {
                            const labels = (0, datetime_picker_display_utils_1.formatTimestampToDateStringArray)(originalValue);
                            return {
                                ...token,
                                _originalDateShortcutValue: originalValue,
                                naturalLanguage: labels[0],
                            };
                        }
                        if (valueType === 'dynamic') {
                            const chineseLabel = (0, datetime_picker_display_utils_1.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: (0, date_shortcuts_1.getDateShortcutLabel)(originalValue),
                                _originalDateShortcutValue: originalValue,
                            };
                        }
                        return token;
                    });
                    const { slotConfigs, displayTexts } = (0, token_utils_1.convertTokensToSlotConfigs)(tokensWithOriginalValues, (mergedSchema === null || mergedSchema === void 0 ? void 0 : mergedSchema.properties) || {}, customRenderForTag);
                    if (slotConfigs.length > 0) {
                        (_f = (_e = senderRef.current).insert) === null || _f === void 0 ? void 0 : _f.call(_e, slotConfigs);
                    }
                    const displayText = displayTexts.join(' ') || value || i18n_1.default.get({ id: 'AllData', dm: '全部数据' });
                    setLastSearchParams(displayText);
                }
                else {
                    // 如果没有结构化数据，使用原始输入值
                    setLastSearchParams(value || i18n_1.default.get({ id: 'AllData', dm: '全部数据' }));
                }
                // 3. 处理响应数据：将 tokens 转换为查询参数格式
                const searchParams = (0, token_utils_1.tokensToSearchParams)(normalizedTokens);
                // 4. 统一在 CnAiFilter 内清洗 lookup join 协议并触发查询
                dispatchSearch(searchParams, finalFormValue);
            }
            else {
                // 转换失败，显示错误信息（如果需要）
                const errorMsg = (responseData === null || responseData === void 0 ? void 0 : responseData.errorMsg) || (transformResult === null || transformResult === void 0 ? void 0 : transformResult.errorMsg);
                if (errorMsg) {
                    // eslint-disable-next-line no-console
                    console.error('Field transform failed:', errorMsg);
                }
            }
        }
        catch (error) {
            // 如果请求被取消，不显示错误
            if ((error === null || error === void 0 ? void 0 : error.name) === 'AbortError') {
                // eslint-disable-next-line no-console
                console.log('Request aborted by user');
                return;
            }
            // eslint-disable-next-line no-console
            console.error('Field transform API failed:', error);
        }
        finally {
            // 清理状态
            abortControllerRef.current = null;
            setIsLoading(false);
        }
    }, [
        dispatchSearch,
        customFieldTransformApi,
        language,
        operator,
        pageId,
        dataDictRef,
        mergedSchema,
        bizRequestConfig,
    ]);
    const filterSender = (React.createElement(cn_sender_1.CnSender, { ref: senderRef, placeholder: i18n_1.default.get({
            id: 'AIQuerySupportsNaturalLanguageQu_233901144',
            dm: "AI查询支持自然语言查询,支持键入'/'引入字段精确查询,基于用户维度的查询习惯总结,让查询越用越智能~",
        }), className: "cn-ai-filter__sender", ...restProps, onSubmit: handleSubmit, popupTriggerKey: popupTriggerKey, customPopupProps: enhancedCustomPopupProps, schema: mergedSchema, form: form, formProps: formProps, prefix: (() => {
            const prefixDiv = (React.createElement("div", { className: "cn-ai-filter__prefix", onClick: (e) => {
                    e.stopPropagation();
                    const willOpen = !commonQueryVisible;
                    if (willOpen) {
                        (0, arms_hot_tag_log_1.armsHottagLog)({
                            hottag: 'cn-ai-filter.openCommonQuery',
                            name: i18n_1.default.get({ id: 'OpenCommonQuery', dm: '打开常用查询' }),
                        });
                    }
                    setCommonQueryVisible(willOpen);
                }, style: { cursor: 'pointer' } },
                React.createElement(cn_ui_1.CnIcon, { type: "time", className: "cn-ai-filter__prefix-icon-clock" }),
                React.createElement(cn_ui_1.CnIcon, { type: "triangle-down-fill", className: "cn-ai-filter__prefix-icon-arrow" })));
            const tooltipTrigger = (React.createElement(cn_ui_1.CnTooltip, { triggerType: "hover", align: "b", trigger: prefixDiv, popupProps: {
                    ...(commonQueryVisible ? { visible: false } : {}),
                    style: { zIndex: floating_layer_1.FLOATING_LAYER_Z_INDEX },
                } }, i18n_1.default.get({ id: 'CommonQueryCondition', dm: '常用查询条件' })));
            return (React.createElement(cn_ui_1.CnPopup, { v2: true, visible: commonQueryVisible, onVisibleChange: setCommonQueryVisible, trigger: tooltipTrigger, placement: "bl", offset: [0, 8], container: floating_layer_1.getPopupContainer, ...floating_layer_1.cnPopupFloatingLayerOverlayProps },
                React.createElement("div", { className: "cn-ai-filter__common-query-popup" },
                    React.createElement("div", { className: "cn-ai-filter__common-query-list" },
                        React.createElement(common_query_list_1.CommonQueryList, { loading: commonQueriesLoading, pinnedQueries: pinnedQueries, unpinnedQueries: unpinnedQueries, onQueryClick: handleCommonQueryClick, onPinQuery: handlePinCommonQuery, onUnpinQuery: handleUnpinCommonQuery, onClose: () => setCommonQueryVisible(false), schema: mergedSchema })))));
        })(), sendButtonProps: {
            icon: React.createElement("img", { src: brandAssets.filter.sendButtonIconUrl, alt: "search" }),
            className: 'cn-ai-filter__send-button',
            ...(env_1.isEditor ? { disabled: true } : {}),
        }, allowRecord: true, suffix: (actionNode) => {
            return React.createElement("div", { className: "cn-ai-filter__footer" }, actionNode);
        }, loading: isLoading, onCancel: handleStopLoading, autoSize: { minRows: 1, maxRows: 2 }, canEmptySubmit: true }));
    return (React.createElement("div", { className: "cn-ai-filter", id: id, [event_constants_1.CN_AI_LIST_INSTANCE_KEY_DATA_ATTR]: listInstanceKey },
        showAgentIcon ? (React.createElement("div", { className: "cn-ai-filter__agent-row" },
            enableAIAgent && (React.createElement(cn_ui_1.CnTooltip, { triggerType: "hover", align: "b", trigger: React.createElement("div", { className: "cn-ai-filter__agent-toggle", onClick: (e) => {
                        e.stopPropagation();
                        handleToggleAgent();
                    } },
                    React.createElement("img", { src: "https://img.alicdn.com/imgextra/i1/O1CN01b1jDbz1WdwqxSTQbR_!!6000000002812-55-tps-22-22.svg", alt: "AI Assistant" })) }, agentToggleTitle)),
            React.createElement("div", { className: "cn-ai-filter__agent-row-body" }, filterSender))) : (filterSender),
        lastSearchParams && (React.createElement("div", { className: "translate-tags-container" },
            React.createElement("div", { className: "translate-tags-title" },
                React.createElement("div", { className: "success-icon" },
                    React.createElement(cn_ui_1.CnIcon, { type: "complete", size: "small" })),
                React.createElement("div", { className: "success-label" }, i18n_1.default.get({ id: 'HasBeenQueriedForYou', dm: '已为您查询：' }))),
            React.createElement("div", { className: "translate-tags-content" },
                React.createElement("span", { className: "translate-tag-word", title: lastSearchParams }, `"${lastSearchParams}"`),
                React.createElement(cn_ui_1.CnIcon, { className: "translate-tag-copy", type: "copy-fill", size: "medium", onClick: () => {
                        (0, arms_hot_tag_log_1.armsHottagLog)({
                            hottag: 'cn-ai-filter.copySearchParams',
                            name: i18n_1.default.get({ id: 'CopyQueryCriteria', dm: '复制查询条件' }),
                            c6: lastSearchParams,
                        });
                        (0, copy_to_clipboard_1.default)(lastSearchParams);
                        cn_ui_1.CnMessage.notice(i18n_1.default.get({ id: 'CopiedToClipboard', dm: '已复制到剪切板' }));
                    } }))))));
};
CnAiFilterView.displayName = 'CnAiFilter';
const CnAiFilter = (props) => (React.createElement(cn_ai_list_event_context_1.CnAiListEventProvider, { instanceId: props.id },
    React.createElement(CnAiFilterView, { ...props })));
exports.CnAiFilter = CnAiFilter;
