<template>
    <div class="flex gap-2 date-search" :class="{'justify-end': position === 'right', 'justify-start': position === 'left', 'justify-center': position === 'center'}">
        <div class="quick-select">
            <el-button
                :type="activeQuickSelect === 7 ? 'primary' : ''"
                @click="handleQuickSelect(7)"
                >7日</el-button
            >
            <el-button
                :type="activeQuickSelect === 14 ? 'primary' : ''"
                @click="handleQuickSelect(14)"
                >15日</el-button
            >
            <el-button
                :type="activeQuickSelect === 30 ? 'primary' : ''"
                @click="handleQuickSelect(30)"
                >30日</el-button
            >
        </div>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            style="max-width: 320px"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
    </div>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import dayjs from "dayjs";

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => [],
    },
    position: {
        type: String,
        default: "right",
    },
});

const emit = defineEmits(["update:modelValue", "search"]);

const dateRange = ref(props.modelValue);
const activeQuickSelect = ref(7); // 默认选中7日

// 监听外部值变化
watch(
    () => props.modelValue,
    (newVal) => {
        dateRange.value = newVal;
    },
    { deep: true }
);

// 监听内部值变化
watch(
    dateRange,
    (newVal) => {
        emit("update:modelValue", newVal);
    },
    { deep: true }
);

// 快捷选项点击
const handleQuickSelect = (days) => {
    activeQuickSelect.value = days;
    const end = dayjs();
    const start = dayjs().subtract(days, "day");
    const newDateRange = [start.format("YYYY-MM-DD"), end.format("YYYY-MM-DD")];
    
    // 先更新日期范围
    dateRange.value = newDateRange;
    
    // 使用 nextTick 确保数据更新后再触发搜索
    nextTick(() => {
        emit("search", newDateRange);
    });
};

// 日期选择变化
const handleDateChange = (val) => {
    // 清除快捷选项的选中状态
    activeQuickSelect.value = null;
    
    // 使用 nextTick 确保数据更新后再触发搜索
    nextTick(() => {
        emit("search", val);
    });
};

// 搜索按钮点击
const handleSearch = () => {
    emit("search", dateRange.value);
};

// 重置按钮点击
const handleReset = () => {
    // 重置为默认7天
    handleQuickSelect(7);
};

// 禁用未来日期
const disabledDate = (time) => {
    return dayjs(time).isAfter(dayjs(), "day");
};
</script>
