"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateFilterValueInput = 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"));
require("./date-filter-value-input.scss");
/**
 * 日期筛选的相对日期选项
 * 点选项：单个日期
 * 范围选项：日期范围
 * 动态选项：用户设置天数
 */
const DATE_FILTER_OPTIONS = [
    { label: i18n_1.default.get({ id: 'Today', dm: '今天' }), value: 'today' },
    { label: i18n_1.default.get({ id: 'Tomorrow', dm: '明天' }), value: 'tomorrow' },
    { label: i18n_1.default.get({ id: 'Yesterday', dm: '昨天' }), value: 'yesterday' },
    { label: i18n_1.default.get({ id: 'ThisWeek', dm: '本周' }), value: 'thisWeek' },
    { label: i18n_1.default.get({ id: 'LastWeek', dm: '上周' }), value: 'lastWeek' },
    { label: i18n_1.default.get({ id: 'NextWeek', dm: '下周' }), value: 'nextWeek' },
    { label: i18n_1.default.get({ id: 'ThisMonth', dm: '本月' }), value: 'thisMonth' },
    { label: i18n_1.default.get({ id: 'LastMonth', dm: '上个月' }), value: 'lastMonth' },
    { label: i18n_1.default.get({ id: 'NextMonth', dm: '下个月' }), value: 'nextMonth' },
    { label: i18n_1.default.get({ id: 'ThisYear', dm: '今年' }), value: 'thisYear' },
    { label: i18n_1.default.get({ id: 'LastYear', dm: '去年' }), value: 'lastYear' },
    { label: i18n_1.default.get({ id: 'NextYear', dm: '明年' }), value: 'nextYear' },
    { label: i18n_1.default.get({ id: 'Future', dm: '未来' }), value: 'nextDays' },
    { label: i18n_1.default.get({ id: 'Past', dm: '过去' }), value: 'pastDays' },
];
// 常量配置
const DYNAMIC_OPTIONS = ['nextDays', 'pastDays'];
const DEFAULT_DAYS_COUNT = 7;
// 正则表达式（用于兼容旧格式）
const RANGE_FORMAT_REGEX = /^(thisWeek|lastWeek|nextWeek|thisMonth|lastMonth|nextMonth|thisYear|lastYear|nextYear):(\d+)$/;
/**
 * 解析外部传入的 value，返回组件内部状态
 * value 格式：选项名（如 "today"、"thisWeek"）或动态格式（如 "nextDays:7"）
 */
function parseValue(value) {
    // 空值处理
    if (!value) {
        return {
            selectedOption: '',
            nextDaysCount: DEFAULT_DAYS_COUNT,
            pastDaysCount: DEFAULT_DAYS_COUNT,
        };
    }
    // 动态选项格式：nextDays:7 或 pastDays:7
    if (value.startsWith('nextDays:')) {
        const days = parseInt(value.replace('nextDays:', ''), 10);
        return {
            selectedOption: 'nextDays',
            nextDaysCount: isNaN(days) ? DEFAULT_DAYS_COUNT : days,
            pastDaysCount: DEFAULT_DAYS_COUNT,
        };
    }
    if (value.startsWith('pastDays:')) {
        const days = parseInt(value.replace('pastDays:', ''), 10);
        return {
            selectedOption: 'pastDays',
            nextDaysCount: DEFAULT_DAYS_COUNT,
            pastDaysCount: isNaN(days) ? DEFAULT_DAYS_COUNT : days,
        };
    }
    // 范围格式：thisWeek:timestamp（兼容旧格式）
    const rangeMatch = value.match(RANGE_FORMAT_REGEX);
    if (rangeMatch) {
        return {
            selectedOption: rangeMatch[1],
            nextDaysCount: DEFAULT_DAYS_COUNT,
            pastDaysCount: DEFAULT_DAYS_COUNT,
        };
    }
    // 相对日期选项字符串（today, tomorrow, thisWeek 等）
    // 检查是否是有效的选项值
    const isValidOption = DATE_FILTER_OPTIONS.some((opt) => opt.value === value);
    if (isValidOption) {
        return {
            selectedOption: value,
            nextDaysCount: DEFAULT_DAYS_COUNT,
            pastDaysCount: DEFAULT_DAYS_COUNT,
        };
    }
    // 默认清空选择
    return {
        selectedOption: '',
        nextDaysCount: DEFAULT_DAYS_COUNT,
        pastDaysCount: DEFAULT_DAYS_COUNT,
    };
}
/**
 * 将选项值转换为输出格式
 * 直接保存选项名，筛选时动态计算时间戳
 */
function formatOutputValue(optionValue, nextDaysCount, pastDaysCount) {
    if (optionValue === 'nextDays') {
        return `nextDays:${nextDaysCount}`;
    }
    if (optionValue === 'pastDays') {
        return `pastDays:${pastDaysCount}`;
    }
    // 其他选项直接返回选项名（如 "today"、"thisWeek"）
    // 筛选逻辑会根据选项名动态计算时间戳
    return optionValue;
}
/**
 * 日期筛选值输入组件
 */
const DateFilterValueInput = ({ value, onChange }) => {
    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);
    // 解析外部 value 并同步到内部状态
    react_1.default.useEffect(() => {
        const parsed = parseValue(value);
        setSelectedOption(parsed.selectedOption);
        setNextDaysCount(parsed.nextDaysCount);
        setPastDaysCount(parsed.pastDaysCount);
    }, [value]);
    // 处理选项变化
    const handleOptionChange = react_1.default.useCallback((optionValue, closePopup = true) => {
        setSelectedOption(optionValue);
        // 动态选项保持弹窗打开
        if (DYNAMIC_OPTIONS.includes(optionValue)) {
            setPopupVisible(true);
        }
        else if (closePopup) {
            setPopupVisible(false);
        }
        const finalValue = formatOutputValue(optionValue, nextDaysCount, pastDaysCount);
        onChange(finalValue);
    }, [nextDaysCount, pastDaysCount, onChange]);
    // 处理天数变化
    const handleDaysChange = react_1.default.useCallback((optionValue, days) => {
        const daysValue = days || DEFAULT_DAYS_COUNT;
        if (optionValue === 'nextDays') {
            setNextDaysCount(daysValue);
        }
        else {
            setPastDaysCount(daysValue);
        }
        const finalValue = formatOutputValue(optionValue, daysValue, daysValue);
        onChange(finalValue);
    }, [onChange]);
    // 获取输入框显示值
    const displayValue = react_1.default.useMemo(() => {
        if (!selectedOption)
            return '';
        const option = DATE_FILTER_OPTIONS.find((opt) => opt.value === selectedOption);
        if (selectedOption === 'nextDays') {
            return i18n_1.default.get({
                id: 'InTheNextNextDaysCountDays',
                dm: '未来 {nextDaysCount} 天内',
            }, { nextDaysCount });
        }
        if (selectedOption === 'pastDays') {
            return i18n_1.default.get({
                id: 'InTheLastPastDaysCountDays',
                dm: '过去 {pastDaysCount} 天内',
            }, { pastDaysCount });
        }
        return (option === null || option === void 0 ? void 0 : option.label) || '';
    }, [selectedOption, nextDaysCount, pastDaysCount]);
    // 统一的事件阻止冒泡处理
    const stopPropagation = react_1.default.useCallback((e) => {
        e.stopPropagation();
    }, []);
    // 检查是否是 NumberPicker 点击
    const isNumberPickerClick = react_1.default.useCallback((target) => {
        return (target.closest('.date-filter-number-picker-wrapper') !== null ||
            target.closest('[class*="number-picker"]') !== null ||
            target.closest('[class*="NumberPicker"]') !== null);
    }, []);
    return (react_1.default.createElement("div", { className: "date-filter-value-input" },
        react_1.default.createElement(cn_ui_1.CnPopup, { triggerType: "click", visible: popupVisible, onVisibleChange: setPopupVisible, trigger: react_1.default.createElement("div", { className: "date-filter-input-wrapper" },
                react_1.default.createElement(cn_ui_1.CnInput, { value: displayValue, placeholder: i18n_1.default.get({ id: 'PleaseSelect', dm: '请选择' }), className: "date-filter-trigger", onClick: (e) => {
                        stopPropagation(e);
                        setPopupVisible(true);
                    }, onFocus: (e) => {
                        stopPropagation(e);
                        setPopupVisible(true);
                    } })), placement: "bl", offset: [0, 4] },
            react_1.default.createElement("div", { className: "date-filter-popup-wrapper", onClick: stopPropagation },
                react_1.default.createElement("div", { className: "date-filter-popup", onClick: stopPropagation }, DATE_FILTER_OPTIONS.map((option) => {
                    const isSelected = selectedOption === option.value;
                    const isDaysOption = DYNAMIC_OPTIONS.includes(option.value);
                    return (react_1.default.createElement("div", { key: option.value, className: (0, classnames_1.default)('date-filter-option', {
                            'date-filter-option-selected': isSelected,
                            'date-filter-option-days': isDaysOption,
                        }), onClick: (e) => {
                            stopPropagation(e);
                            if (isDaysOption) {
                                const target = e.target;
                                if (!isNumberPickerClick(target)) {
                                    handleOptionChange(option.value, false);
                                }
                            }
                            else {
                                handleOptionChange(option.value, true);
                            }
                        } }, isDaysOption ? (react_1.default.createElement("div", { className: "date-filter-option-label", onClick: stopPropagation },
                        react_1.default.createElement("span", null, option.value === 'nextDays'
                            ? i18n_1.default.get({ id: 'Future', dm: '未来' })
                            : i18n_1.default.get({ id: 'Past', dm: '过去' })),
                        react_1.default.createElement("div", { className: "date-filter-number-picker-wrapper", onClick: stopPropagation },
                            react_1.default.createElement(cn_ui_1.CnNumberPicker, { value: option.value === 'nextDays' ? nextDaysCount : pastDaysCount, onChange: (days) => {
                                    handleDaysChange(option.value, days);
                                }, min: 1, style: { width: '80px', marginRight: '4px', height: '28px' }, onClick: stopPropagation, onFocus: stopPropagation, onMouseDown: stopPropagation }),
                            react_1.default.createElement("span", null, i18n_1.default.get({ id: 'WithinDays', dm: '天内' }))))) : (react_1.default.createElement("div", { className: "date-filter-option-label" }, option.label))));
                }))))));
};
exports.DateFilterValueInput = DateFilterValueInput;
