import $i18n from '../../../locales/i18n.js';
import React from 'react';
import { CnIcon, CnPopup } from '@cainiaofe/cn-ui';
import { FieldInputForm } from './FieldInputForm';
import { getDisplayValueFromFormMap } from '../../utils/display/form-map-display-utils';
import { armsHottagLog } from '../../../utils/arms/arms-hot-tag-log.js';
export const FieldTagPopup = ({ prefixCls, tagKey, config, value, onValueChange, renderProps, formMapRef, form, formProps, schema, fieldKey, onFormMapUpdate, title, }) => {
    var _a, _b, _c, _d;
    const [popupVisible, setPopupVisible] = React.useState(false);
    // 用于强制重新计算 displayValue（当 formMap 更新时）
    const [formMapTick, setFormMapTick] = React.useState(0);
    // 监听 formMapRef 的变化，当 formMap 更新时触发重新计算
    React.useEffect(() => {
        var _a;
        if ((_a = formMapRef === null || formMapRef === void 0 ? void 0 : formMapRef.current) === null || _a === void 0 ? void 0 : _a[fieldKey]) {
            setFormMapTick((prev) => prev + 1);
        }
    }, [(_b = (_a = formMapRef === null || formMapRef === void 0 ? void 0 : formMapRef.current) === null || _a === void 0 ? void 0 : _a[fieldKey]) === null || _b === void 0 ? void 0 : _b.labels, (_d = (_c = formMapRef === null || formMapRef === void 0 ? void 0 : formMapRef.current) === null || _c === void 0 ? void 0 : _c[fieldKey]) === null || _d === void 0 ? void 0 : _d.values]);
    // 获取字段名称（从 config 中提取，如果没有 title 则使用 key）
    const fieldName = React.useMemo(() => {
        return title || (config === null || config === void 0 ? void 0 : config.title) || tagKey.split('.').pop() || tagKey;
    }, [tagKey, config, title]);
    // 从 formMap 中获取显示值（优先使用 labels，其次使用 options）
    const displayValue = React.useMemo(() => {
        var _a;
        const formMapData = (_a = formMapRef === null || formMapRef === void 0 ? void 0 : formMapRef.current) === null || _a === void 0 ? void 0 : _a[fieldKey];
        if ((formMapData === null || formMapData === void 0 ? void 0 : formMapData.labels) && formMapData.labels.length > 0) {
            // 使用 formMap 中的 labels，多个值用逗号分隔
            return formMapData.labels.join(', ');
        }
        // 回退到使用 formMap.options 查找（传入 config 以便识别时区日期等类型并正确格式化）
        return getDisplayValueFromFormMap(value, fieldKey, formMapRef, config);
    }, [formMapRef, fieldKey, value, config, formMapTick]);
    // 检查焦点是否在交互元素上（如日期选择器、下拉框等）
    const isActiveInInteractiveElement = React.useCallback(() => {
        const { activeElement } = document;
        if (!activeElement)
            return false;
        const interactiveSelectors = [
            `.${prefixCls}-slot-custom-field-popup`,
            '[class*="picker"]',
            '[class*="Picker"]',
            '[class*="next-input"]',
            '[class*="select"]',
            '[class*="Select"]',
        ];
        return interactiveSelectors.some((selector) => activeElement.closest(selector));
    }, [prefixCls]);
    // 处理弹出层显隐变化
    const handlePopupVisibleChange = React.useCallback((visible) => {
        if (visible) {
            setPopupVisible(true);
            armsHottagLog({
                hottag: 'cn-ai-filter.fieldTag.open',
                name: $i18n.get({ id: 'OpenFieldLabel', dm: '打开字段标签' }),
                c6: fieldName,
            });
        }
        else {
            // 延迟检查，确保焦点已转移到新元素
            setTimeout(() => {
                if (!isActiveInInteractiveElement()) {
                    setPopupVisible(false);
                }
            }, 0);
        }
    }, [fieldName, isActiveInInteractiveElement]);
    return (React.createElement(CnPopup, { disabled: renderProps.disabled || renderProps.readOnly, triggerType: "click", v2: true, visible: popupVisible, onVisibleChange: handlePopupVisibleChange, container: () => document.body, trigger: React.createElement("span", { className: `${prefixCls}-slot-tag ${prefixCls}-slot-tag--editable`, "data-slot-component": config === null || config === void 0 ? void 0 : config['x-component'], style: {
                cursor: renderProps.disabled || renderProps.readOnly ? 'default' : 'pointer',
                userSelect: 'none',
                display: 'inline-flex',
                alignItems: 'center',
                gap: '4px',
            } },
            React.createElement("span", { className: `${prefixCls}-slot-tag-name` },
                fieldName,
                ":"),
            React.createElement("span", { className: `${prefixCls}-slot-tag-value` }, displayValue),
            React.createElement(CnIcon, { type: "triangle-down-fill", size: "small", className: `${prefixCls}-slot-tag-icon` })), offset: [0, 4] },
        React.createElement("div", { className: `${prefixCls}-slot-custom-field-popup`, style: {
                padding: '12px',
                minWidth: '200px',
                maxWidth: '400px',
            }, onClick: (e) => e.stopPropagation() },
            React.createElement(FieldInputForm, { form: form, formProps: formProps, schema: schema, fieldConfig: config, currentValue: value, onValueChange: onValueChange, disabled: renderProps.disabled, readOnly: renderProps.readOnly, inline: true, prefixCls: prefixCls, fieldKey: fieldKey, onFormMapUpdate: onFormMapUpdate, formMapRef: formMapRef, onConfirm: () => {
                    // 时间选择器确定按钮点击后，关闭弹层
                    setPopupVisible(false);
                } }))));
};
