"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AiFilterDateValueInput = void 0;
const i18n_1 = __importDefault(require("../../../locales/i18n.js"));
const react_1 = __importDefault(require("react"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const classnames_1 = __importDefault(require("classnames"));
const dayjs_1 = __importDefault(require("dayjs"));
const customParseFormat_1 = __importDefault(require("dayjs/plugin/customParseFormat"));
const date_shortcuts_1 = require("../../utils/constants/date-shortcuts");
const datetime_picker_display_utils_1 = require("../../utils/display/datetime-picker-display-utils");
require("./AiFilterDateValueInput.scss");
dayjs_1.default.extend(customParseFormat_1.default);
// 常量配置
const DEFAULT_DAYS_COUNT = 7;
/** 选项内可交互区域（点击/聚焦不触发选中并关弹窗） */
const INTERACTIVE_SELECTOR = '.ai-filter-date-number-picker-wrapper, .ai-filter-date-range-input-wrapper';
/** 获取默认的 start/end 与天数（用于 empty 或 fallback） */
function getDefaultState(showTime) {
    const now = (0, dayjs_1.default)();
    const format = showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD';
    return {
        nextDaysCount: DEFAULT_DAYS_COUNT,
        pastDaysCount: DEFAULT_DAYS_COUNT,
        startDate: now.subtract(1, 'month').format(format),
        endDate: now.format(format),
    };
}
/**
 * 解析外部传入的 value，返回组件内部状态（带 type，便于按类型处理）
 */
function parseValue(value, showTime) {
    const defaults = { ...getDefaultState(showTime), selectedOption: '' };
    const type = (0, date_shortcuts_1.getDateFilterValueType)(value);
    if (type === 'empty')
        return { type: 'empty', ...defaults };
    if (type === 'dateRange') {
        const [, rangeStr] = value.split(':');
        const [startDate, endDate] = (rangeStr || '').split(',');
        return {
            type: 'dateRange',
            selectedOption: date_shortcuts_1.DATE_RANGE_OPTION,
            nextDaysCount: DEFAULT_DAYS_COUNT,
            pastDaysCount: DEFAULT_DAYS_COUNT,
            startDate: startDate || '',
            endDate: endDate || '',
        };
    }
    if (type === 'dynamic') {
        const days = (0, datetime_picker_display_utils_1.parseDynamicDateDays)(value);
        const isFuture = value.startsWith('未来:');
        return {
            type: 'dynamic',
            selectedOption: isFuture
                ? i18n_1.default.get({ id: 'Future', dm: '未来' })
                : i18n_1.default.get({ id: 'Past', dm: '过去' }),
            ...getDefaultState(showTime),
            nextDaysCount: isFuture ? days : DEFAULT_DAYS_COUNT,
            pastDaysCount: isFuture ? DEFAULT_DAYS_COUNT : days,
        };
    }
    // type === 'shortcut'
    return { type: 'shortcut', selectedOption: value, ...getDefaultState(showTime) };
}
/**
 * 校验日期区间输入的合法性
 * @returns null 表示合法，否则返回错误提示文案
 */
function validateDateRange(startDate, endDate, showTime) {
    const format = showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD';
    if (!startDate && !endDate)
        return i18n_1.default.get({ id: 'PleaseEnterStartAndEndDates', dm: '请输入开始日期和结束日期' });
    // 两个有一个为空
    if (!startDate && endDate)
        return i18n_1.default.get({ id: 'PleaseEnterAStartDate', dm: '请输入开始日期' });
    if (startDate && !endDate)
        return i18n_1.default.get({ id: 'PleaseEnterAnEndDate', dm: '请输入结束日期' });
    const startDayjs = (0, dayjs_1.default)(startDate, format, true);
    const endDayjs = (0, dayjs_1.default)(endDate, format, true);
    const startInvalid = startDate && !startDayjs.isValid();
    const endInvalid = endDate && !endDayjs.isValid();
    if (startInvalid && endInvalid) {
        return i18n_1.default.get({
            id: 'TheStartDateAndEndDateAreNot',
            dm: '开始日期和结束日期格式均不正确，请输入 {format} 格式',
        }, { format });
    }
    if (startInvalid) {
        return i18n_1.default.get({
            id: 'StartDateFormatIsIncorrectPlease_371805958',
            dm: '开始日期格式不正确，请输入 {format} 格式',
        }, { format });
    }
    if (endInvalid) {
        return i18n_1.default.get({
            id: 'EndingDateFormatIsIncorrectPleas_1338140575',
            dm: '结束日期格式不正确，请输入 {format} 格式',
        }, { format });
    }
    if (startDate && endDate && startDayjs.isAfter(endDayjs)) {
        return i18n_1.default.get({ id: 'TheStartDateCannotBeLaterThanThe', dm: '开始日期不能晚于结束日期' });
    }
    return null;
}
/**
 * 将选项值转换为输出格式
 * 输出中文值或动态格式（如 "未来:7"、"过去:7"）或日期范围格式（如 "开始日期至结束日期:YYYY-MM-DD,YYYY-MM-DD"）
 */
function formatOutputValue(optionValue, nextDaysCount, pastDaysCount, startDate, endDate) {
    if (optionValue === '未来') {
        return i18n_1.default.get({
            id: 'FuturenextDaysCount',
            dm: '未来:{nextDaysCount}',
        }, { nextDaysCount });
    }
    if (optionValue === '过去') {
        return i18n_1.default.get({
            id: 'PastpastDaysCount',
            dm: '过去:{pastDaysCount}',
        }, { pastDaysCount });
    }
    if (optionValue === date_shortcuts_1.DATE_RANGE_OPTION && startDate && endDate) {
        return `${date_shortcuts_1.DATE_RANGE_OPTION}:${startDate},${endDate}`;
    }
    // 其他选项直接返回中文值（如 "今天"、"本周"）
    return optionValue;
}
/**
 * 日期筛选值输入组件（专用于 aifilter）
 * 使用中文值作为 value，与 date-shortcuts.ts 保持一致
 */
const AiFilterDateValueInput = ({ value, onChange, showTime = false, onConfirm, }) => {
    const [selectedOption, setSelectedOption] = react_1.default.useState('');
    const [nextDaysCount, setNextDaysCount] = react_1.default.useState(DEFAULT_DAYS_COUNT);
    const [pastDaysCount, setPastDaysCount] = react_1.default.useState(DEFAULT_DAYS_COUNT);
    const [popupVisible, setPopupVisible] = react_1.default.useState(false);
    const [startDate, setStartDate] = react_1.default.useState('');
    const [endDate, setEndDate] = react_1.default.useState('');
    const [dateRangeError, setDateRangeError] = react_1.default.useState(null);
    // 用于跟踪用户是否正在输入，防止 useEffect 覆盖用户输入的值
    const isUserInputtingRef = react_1.default.useRef(false);
    // 用户刚修改「未来/过去 N 天」时，短暂不根据外部 value 覆盖天数
    const isDaysInputtingRef = react_1.default.useRef(false);
    // 防抖定时器
    const debounceTimerRef = react_1.default.useRef(null);
    // 解析外部 value 并同步到内部状态
    react_1.default.useEffect(() => {
        if (isUserInputtingRef.current || isDaysInputtingRef.current)
            return;
        const parsed = parseValue(value, showTime);
        setSelectedOption(parsed.selectedOption);
        setNextDaysCount(parsed.nextDaysCount);
        setPastDaysCount(parsed.pastDaysCount);
        const defaults = getDefaultState(showTime);
        const hasDateRange = parsed.type === 'dateRange' && parsed.startDate && parsed.endDate;
        if (hasDateRange) {
            setStartDate(parsed.startDate);
            setEndDate(parsed.endDate);
        }
        else {
            setStartDate(defaults.startDate);
            setEndDate(defaults.endDate);
        }
    }, [value, showTime]);
    // 处理选项变化：选中项 → 按需初始化日期范围 → 通知父组件 → 可选关闭弹窗
    const handleOptionChange = react_1.default.useCallback((optionValue, closePopup = true) => {
        setSelectedOption(optionValue);
        let finalValue = null;
        if (optionValue === date_shortcuts_1.DATE_RANGE_OPTION) {
            const hasExistingRange = (0, date_shortcuts_1.getDateFilterValueType)(value) === 'dateRange';
            if (!hasExistingRange) {
                const defaults = getDefaultState(showTime);
                setStartDate(defaults.startDate);
                setEndDate(defaults.endDate);
                finalValue = formatOutputValue(optionValue, nextDaysCount, pastDaysCount, defaults.startDate, defaults.endDate);
            }
            // 已有日期范围时不再 onChange，由 useEffect 根据 value 同步内部状态
        }
        else {
            finalValue = formatOutputValue(optionValue, nextDaysCount, pastDaysCount);
        }
        if (finalValue !== null)
            onChange(finalValue);
        if (closePopup) {
            setPopupVisible(false);
            // 点击任意快捷选项时，都关闭外层弹窗
            if (onConfirm) {
                // 延迟调用，确保内部弹窗先关闭
                setTimeout(() => {
                    onConfirm();
                }, 100);
            }
        }
    }, [nextDaysCount, pastDaysCount, onChange, showTime, value, onConfirm]);
    // 处理天数变化
    const handleDaysChange = react_1.default.useCallback((optionValue, days) => {
        const daysValue = days || DEFAULT_DAYS_COUNT;
        isDaysInputtingRef.current = true;
        if (optionValue === '未来') {
            setNextDaysCount(daysValue);
        }
        else {
            setPastDaysCount(daysValue);
        }
        const finalValue = formatOutputValue(optionValue, daysValue, daysValue);
        onChange(finalValue);
        // 短暂不根据外部 value 覆盖天数，避免父组件未及时更新时被重置为旧值
        setTimeout(() => {
            isDaysInputtingRef.current = false;
        }, 150);
    }, [onChange]);
    // 处理日期范围变化（使用防抖，避免频繁更新外部 value）
    const handleDateRangeChange = react_1.default.useCallback((newStartDate, newEndDate) => {
        // 立即更新内部状态，让用户看到输入效果
        setStartDate(newStartDate);
        setEndDate(newEndDate);
        // 实时校验日期合法性
        const error = validateDateRange(newStartDate, newEndDate, showTime);
        setDateRangeError(error);
        // 标记用户正在输入
        isUserInputtingRef.current = true;
        // 清除之前的定时器
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }
        // 延迟更新外部 value，避免立即触发 useEffect
        const finalValue = formatOutputValue(date_shortcuts_1.DATE_RANGE_OPTION, nextDaysCount, pastDaysCount, newStartDate, newEndDate);
        debounceTimerRef.current = setTimeout(() => {
            // 仅在合法时才触发 onChange
            if (!validateDateRange(newStartDate, newEndDate, showTime)) {
                onChange(finalValue);
            }
            // 延迟重置标志，确保 onChange 触发的 value 更新不会覆盖用户输入
            setTimeout(() => {
                isUserInputtingRef.current = false;
            }, 100);
        }, 300);
    }, [nextDaysCount, pastDaysCount, onChange, showTime]);
    // 清理防抖定时器
    react_1.default.useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);
    // 获取输入框显示值
    const displayValue = react_1.default.useMemo(() => {
        if (!selectedOption)
            return '';
        if (selectedOption === '未来') {
            return i18n_1.default.get({
                id: 'InTheNextNextDaysCountDays',
                dm: '未来 {nextDaysCount} 天内',
            }, { nextDaysCount });
        }
        if (selectedOption === '过去') {
            return i18n_1.default.get({
                id: 'InTheLastPastDaysCountDays',
                dm: '过去 {pastDaysCount} 天内',
            }, { pastDaysCount });
        }
        if (selectedOption === date_shortcuts_1.DATE_RANGE_OPTION) {
            return i18n_1.default.get({
                id: 'StartDateToEndDate.6tqtG',
                dm: '{startDate} 至 {endDate}',
            }, { startDate, endDate });
        }
        // 使用 getDateShortcutLabel 获取中文标签
        return (0, date_shortcuts_1.getDateShortcutLabel)(selectedOption);
    }, [selectedOption, nextDaysCount, pastDaysCount, startDate, endDate]);
    // 统一的事件阻止冒泡处理
    const stopPropagation = react_1.default.useCallback((e) => {
        e.stopPropagation();
    }, []);
    /** 阻止冒泡 + 默认行为（用于弹窗内输入/选择器，避免触发选项选中或关弹窗） */
    const stopAll = react_1.default.useCallback((e) => {
        var _a, _b;
        e.stopPropagation();
        (_b = (_a = e).preventDefault) === null || _b === void 0 ? void 0 : _b.call(_a);
    }, []);
    /** 点击是否落在可交互区域（不触发选中/关弹窗） */
    const isTargetInInteractive = react_1.default.useCallback((e) => {
        const target = e.target;
        // 如果点击的是「至」字符，不算可交互区域，允许选中
        if (target.classList.contains('ai-filter-date-range-separator') ||
            target.closest('.ai-filter-date-range-separator')) {
            return false;
        }
        return target.closest(INTERACTIVE_SELECTOR) !== null;
    }, []);
    // 处理弹窗关闭前的检查
    const handlePopupClose = react_1.default.useCallback(() => {
        // 检查当前焦点是否在弹窗内的交互元素上
        const { activeElement } = document;
        if (activeElement &&
            (activeElement.closest('.ai-filter-date-number-picker-wrapper') !== null ||
                activeElement.closest('.ai-filter-date-popup') !== null ||
                activeElement.closest('.ai-filter-date-popup-wrapper') !== null ||
                activeElement.closest('[class*="number-picker"]') !== null ||
                activeElement.closest('[class*="NumberPicker"]') !== null ||
                activeElement.closest('[class*="next-input"]') !== null ||
                activeElement.closest('.ai-filter-date-range-input-wrapper') !== null)) {
            return false; // 不关闭
        }
        return true; // 允许关闭
    }, []);
    return (react_1.default.createElement("div", { className: "ai-filter-date-value-input" },
        react_1.default.createElement(cn_ui_1.CnPopup, { v2: true, triggerType: "click", visible: popupVisible, onVisibleChange: (visible) => {
                if (!visible) {
                    // 延迟检查，确保焦点已经移动
                    setTimeout(() => {
                        if (handlePopupClose()) {
                            setPopupVisible(false);
                        }
                    }, 0);
                }
                else {
                    setPopupVisible(visible);
                }
            }, trigger: react_1.default.createElement("div", { className: "ai-filter-date-input-wrapper" },
                react_1.default.createElement(cn_ui_1.CnInput, { value: displayValue, placeholder: i18n_1.default.get({ id: 'PleaseSelect', dm: '请选择' }), className: "ai-filter-date-trigger", onClick: (e) => {
                        stopPropagation(e);
                        setPopupVisible(true);
                    }, onFocus: (e) => {
                        stopPropagation(e);
                        setPopupVisible(true);
                    } })), placement: "bl", offset: [0, 4] },
            react_1.default.createElement("div", { className: "ai-filter-date-popup-wrapper", onClick: stopPropagation, onMouseDown: (e) => {
                    // 阻止 mousedown 事件冒泡，防止弹窗关闭
                    e.stopPropagation();
                } },
                react_1.default.createElement("div", { className: "ai-filter-date-popup", onClick: stopPropagation, onMouseDown: (e) => {
                        // 阻止 mousedown 事件冒泡，防止弹窗关闭
                        e.stopPropagation();
                    } }, date_shortcuts_1.ALL_DATE_OPTIONS.map((option) => {
                    const isSelected = selectedOption === option.value;
                    const isDaysOption = (0, date_shortcuts_1.isDynamicOption)(option.value);
                    const isDateRangeOption = option.value === date_shortcuts_1.DATE_RANGE_OPTION;
                    let optionContent;
                    if (isDaysOption) {
                        optionContent = (react_1.default.createElement("div", { className: "ai-filter-date-option-label" },
                            react_1.default.createElement("span", null, option.value),
                            react_1.default.createElement("div", { className: "ai-filter-date-number-picker-wrapper", onClick: stopAll, onMouseDown: stopAll, onMouseUp: stopPropagation },
                                react_1.default.createElement(cn_ui_1.CnNumberPicker, { className: "ai-filter-date-days-number-picker", value: option.value === '未来' ? nextDaysCount : pastDaysCount, onChange: (days) => handleDaysChange(option.value, days), min: 1, onClick: stopAll, onFocus: stopAll, onMouseDown: stopAll, onMouseUp: stopPropagation, onBlur: stopPropagation }),
                                react_1.default.createElement("span", null, i18n_1.default.get({ id: 'WithinDays', dm: '天内' })))));
                    }
                    else if (isDateRangeOption) {
                        optionContent = (react_1.default.createElement("div", { className: "ai-filter-date-option-label" },
                            react_1.default.createElement("div", { className: "ai-filter-date-range-input-wrapper", onClick: (e) => {
                                    // 如果点击的是「至」字符，不阻止冒泡，允许选中选项
                                    const target = e.target;
                                    if (!target.classList.contains('ai-filter-date-range-separator') &&
                                        !target.closest('.ai-filter-date-range-separator')) {
                                        stopPropagation(e);
                                    }
                                }, onMouseDown: (e) => {
                                    // 如果点击的是「至」字符，不阻止冒泡
                                    const target = e.target;
                                    if (!target.classList.contains('ai-filter-date-range-separator') &&
                                        !target.closest('.ai-filter-date-range-separator')) {
                                        stopAll(e);
                                    }
                                }, onMouseUp: stopPropagation },
                                react_1.default.createElement(cn_ui_1.CnInput, { className: `ai-filter-date-range-input${dateRangeError ? ' ai-filter-date-range-input-error' : ''}`, value: startDate, onChange: (val) => handleDateRangeChange(val || '', endDate), placeholder: showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD', onClick: stopPropagation, onFocus: stopPropagation, onMouseDown: stopPropagation, onBlur: stopPropagation, state: dateRangeError ? 'error' : undefined }),
                                react_1.default.createElement("span", { className: (0, classnames_1.default)('ai-filter-date-range-separator', {
                                        'ai-filter-date-range-separator-selected': isSelected,
                                    }) }, i18n_1.default.get({ id: 'To', dm: '至' })),
                                react_1.default.createElement(cn_ui_1.CnInput, { className: `ai-filter-date-range-input${dateRangeError ? ' ai-filter-date-range-input-error' : ''}`, value: endDate, onChange: (val) => handleDateRangeChange(startDate, val || ''), placeholder: showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD', onClick: stopPropagation, onFocus: stopPropagation, onMouseDown: stopPropagation, onBlur: stopPropagation, state: dateRangeError ? 'error' : undefined })),
                            dateRangeError && (react_1.default.createElement("div", { className: "ai-filter-date-range-error" }, dateRangeError))));
                    }
                    else {
                        optionContent = react_1.default.createElement("div", { className: "ai-filter-date-option-label" }, option.label);
                    }
                    return (react_1.default.createElement("div", { key: option.value, className: (0, classnames_1.default)('ai-filter-date-option', {
                            'ai-filter-date-option-selected': isSelected,
                            'ai-filter-date-option-days': isDaysOption,
                            'ai-filter-date-option-range': isDateRangeOption,
                        }), onClick: (e) => {
                            if (isTargetInInteractive(e)) {
                                e.stopPropagation();
                                e.preventDefault();
                                return;
                            }
                            stopPropagation(e);
                            handleOptionChange(option.value, true);
                        }, onMouseDown: (e) => {
                            if (isTargetInInteractive(e))
                                stopAll(e);
                        } }, optionContent));
                }))))));
};
exports.AiFilterDateValueInput = AiFilterDateValueInput;
