<template>
    <view v-if="visible" class="popup-overlay">
        <view class="popup-content" @click.stop>
            <!-- 标题栏 -->
            <view class="header">
                <text class="title">本次测评日期</text>
                <view class="close-btn" @click="closePopup">
                    <image class="close-icon" :src="`${$baseUrl}shengzhangTool/1001/changeBaby/closeBtn.png`" mode="aspectFit"></image>
                </view>
            </view>

            <view class="date-picker-container">
                <view class="date-picker-bg">
                    <view class="date-con0">
                        <image class="time-bg" :src="`${$baseUrl}shengzhangTool/1001/timeBg.png`" mode="aspectFit"></image>
                        <text class="time-text">年</text>
                    </view>
                    <view class="date-con1">
                        <image class="time-bg" :src="`${$baseUrl}shengzhangTool/1001/timeBg.png`" mode="aspectFit"></image>
                        <text class="time-text">月</text>
                    </view>
                    <view class="date-con2">
                        <image class="time-bg" :src="`${$baseUrl}shengzhangTool/1001/timeBg.png`" mode="aspectFit"></image>
                        <text class="time-text">日</text>
                    </view>
                    
                </view>
                    <!-- 日期选择器 -->
                    <picker-view
                        class="date-picker"
                        :value="datePickerValue"
                        @change="onDateChange"
                        :indicator-style="indicatorStyle"
                        indicator-class="date-picker"
                        mask-style="opacity: 0.5; border: none;"
                    >
                        <!-- 年份选择 -->
                        <picker-view-column>
                            <view v-for="(year, index) in yearRange" :key="index" class="picker-item">
                                <text class="picker-text">{{ year }}</text>
                                <!-- <text v-if="index === datePickerValue[0]" class="picker-label">年</text> -->
                            </view>
                        </picker-view-column>
                        
                        <!-- 月份选择 -->
                        <picker-view-column>
                            <view v-for="(month, index) in monthRange" :key="index" class="picker-item">
                                <text class="picker-text">{{ month }}</text>
                                <!-- <text v-if="index === datePickerValue[1]" class="picker-label">月</text> -->
                            </view>
                        </picker-view-column>
                        
                        <!-- 日期选择 -->
                        <picker-view-column>
                            <view v-for="(day, index) in dayRange" :key="index" class="picker-item">
                                <text class="picker-text">{{ day }}</text>
                                <!-- <text v-if="index === datePickerValue[2]" class="picker-label">日</text> -->
                            </view>
                        </picker-view-column>
                    </picker-view>
                </view>

        </view>
    </view>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch, computed,onMounted } from 'vue'
import md from '../md.js'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    selectedDate: {
        type: String,
        default: ''
    },
    babyBirthday: {
        type: Number,
        default: 0
    }
})

const emit = defineEmits(['update:visible', 'update:selectedDate', 'change'])

// 按钮状态
const isCancelPressed = ref(false)
const isOkPressed = ref(false)

// 日期选择器样式
const indicatorStyle = `height: 40px; border: none;`
// const maskStyle = `background: rgba(246, 248, 250, 0.8); `

// 当前选择的日期
const currentDate = ref(new Date(props.selectedDate))

const babyBirthday = ref(new Date(props.babyBirthday))

// 生成年份范围 (2024-2030)
const yearRange = computed(() => {
    console.log('babyBirthday.value=',babyBirthday.value.getFullYear());
    const yearRange = []
    for (let i = babyBirthday.value.getFullYear(); i <= 2030; i++) {
        yearRange.push(i)
    }
    return yearRange
})

onMounted(() => {
   
})

// 生成月份范围 (1-12)
const monthRange = computed(() => {
    const monthRange = []
    let startMonth = 1

    // 如果选择的年份等于宝宝生日年份，则从宝宝生日月份开始
    if (currentDate.value.getFullYear() === babyBirthday.value.getFullYear()) {
        startMonth = babyBirthday.value.getMonth() + 1
    } else {
        startMonth = 1
    }
    
    for (let i = startMonth; i <= 12; i++) {
        monthRange.push(i)
    }
    return monthRange
})

// 计算当前月份的天数
const dayRange = computed(() => {
    const selectedYear = currentDate.value.getFullYear()
    const selectedMonth = currentDate.value.getMonth() + 1
    const daysInMonth = new Date(selectedYear, selectedMonth, 0).getDate()
    const days = []

    let startDay = 1

    // 如果选择的年份和月份都等于宝宝生日，则从宝宝生日日期开始
    if (selectedYear === babyBirthday.value.getFullYear() && 
        selectedMonth === babyBirthday.value.getMonth() + 1) {
        startDay = babyBirthday.value.getDate()
    } else {
        startDay = 1
    }

    for (let i = startDay; i <= daysInMonth; i++) {
        days.push(i)
    }
    return days
})

// 日期选择器的值
const datePickerValue = computed(() => {
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth() + 1
    const day = currentDate.value.getDate()
    
    const yearIndex = yearRange.value.indexOf(year)
    const monthIndex = monthRange.value.indexOf(month)
    const dayIndex = dayRange.value.indexOf(day)
    
    return [yearIndex, monthIndex, dayIndex]
})

// 监听 props.selectedDate 的变化
watch(() => props.selectedDate, (newVal) => {
    const newDate = new Date(newVal)
    const minDate = new Date(babyBirthday.value)
    
    // 如果选择的日期早于宝宝生日，使用宝宝生日作为默认值
    if (newDate < minDate) {
        currentDate.value = new Date(babyBirthday.value)
    } else {
        currentDate.value = newDate
    }
}, { immediate: true })

// 监听 props.babyBirthday 的变化
watch(() => props.babyBirthday, (newVal) => {
    babyBirthday.value = new Date(newVal)
    
    // 重新检查当前日期是否有效
    const minDate = new Date(babyBirthday.value)
    if (currentDate.value < minDate) {
        currentDate.value = new Date(babyBirthday.value)
    }
}, { immediate: true })

// 日期选择变化处理
const onDateChange = (e) => {
    console.log('e11111=', e.detail.value);
    const [yearIndex, monthIndex, dayIndex] = e.detail.value
    
    const year = yearRange.value[yearIndex]
    const month = monthRange.value[monthIndex]
    const day = dayRange.value[dayIndex]
    
    // 创建新日期
    const newDate = new Date(year, month - 1, day)
    
    // 检查是否早于宝宝生日
    const minDate = new Date(babyBirthday.value)
    console.log('babyBirthday=', babyBirthday.value);
    if (newDate < minDate) {
        // 如果选择的日期早于宝宝生日，重置为宝宝生日
        currentDate.value = new Date(babyBirthday.value)
        return
    }
    
    currentDate.value = newDate
}

// 取消按钮事件
const handleCancelTouchStart = () => {
    isCancelPressed.value = true
}

const handleCancelTouchEnd = () => {
    isCancelPressed.value = false
    
    // 格式化日期为 YYYY-MM-DD
    const year = currentDate.value.getFullYear()
    const month = String(currentDate.value.getMonth() + 1).padStart(2, '0')
    const day = String(currentDate.value.getDate()).padStart(2, '0')
    const formattedDate = `${year}-${month}-${day}`
    
    // 发送事件通知主页面
    emit('change', formattedDate)
    emit('update:selectedDate', formattedDate)

    closePopup()
}

// 确认按钮事件
const handleOkTouchStart = () => {
    isOkPressed.value = true
}

const handleOkTouchEnd = () => {
    isOkPressed.value = false
    
    // 格式化日期为 YYYY-MM-DD
    const year = currentDate.value.getFullYear()
    const month = String(currentDate.value.getMonth() + 1).padStart(2, '0')
    const day = String(currentDate.value.getDate()).padStart(2, '0')
    const formattedDate = `${year}-${month}-${day}`
    
    // 发送事件通知主页面
    emit('change', formattedDate)
    emit('update:selectedDate', formattedDate)
    closePopup()
}

const closePopup = () => {
    md.sensorPopLogTake({
        xcxPopClick: "true",
        toolName: "生长曲线",
        popName: "选择本次测评日期弹窗",
        buttonName: "关闭"
    });
    // 格式化日期为 YYYY-MM-DD
    const year = currentDate.value.getFullYear()
    const month = String(currentDate.value.getMonth() + 1).padStart(2, '0')
    const day = String(currentDate.value.getDate()).padStart(2, '0')
    const formattedDate = `${year}-${month}-${day}`

    console.log('formattedDate=', formattedDate);
    
    // 发送事件通知主页面
    emit('change', formattedDate)
    emit('update:selectedDate', formattedDate);
    emit('update:visible', false)
}
</script>

<style lang="less" scoped>
.popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;

    .popup-content {
        position: absolute;
        width: 750rpx;
        height: 564rpx;
        background-color: #f6f8fa;
        overflow: hidden;
        border-top-left-radius: 32rpx;
        border-top-right-radius: 32rpx;
        bottom: 0rpx;
        padding-top: 40rpx;
        display: flex;
        flex-direction: column;

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-right: 30rpx;
            margin-left: 30rpx;

            .title {
                font-size: 36rpx;
                font-weight: 400;
                color: #1d1e26;
            }

            .close-btn {
                width: 60rpx;
                height: 60rpx;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .close-icon {
                width: 40rpx;
                height: 40rpx;
            }
        }

        .date-picker-container {
                position: relative;
                width: 100%;
                margin-top: 100rpx;
                
                .date-picker-bg{
                    position: absolute;
                    top: 96rpx;
                    left: 0;
                    width: 100%;
                    height: 60rpx;
                    .date-con0{
                        position: absolute;
                        // width: 122rpx;
                        height: 100%;
                        left: 64rpx;
                        .time-bg{
                            position: absolute;
                            width: 122rpx;
                            height: 51rpx;
                            top:50%;
                            transform: translateY(-50%);
                        }
                        .time-text{
                            position: absolute;
                            font-size: 28rpx;
                            color: #1d1e26;
                            font-weight: bold;
                            left: 135rpx;
                            top:50%;
                            transform: translateY(-50%);
                        }
                    }
                    .date-con1{
                        position: absolute;
                        // width: 122rpx;
                        height: 100%;
                        left: 313rpx;   
                        .time-bg{
                            position: absolute;
                            width: 122rpx;
                            height: 51rpx;
                            top:50%;
                            transform: translateY(-50%);
                        }
                        .time-text{ 
                            position: absolute;
                            font-size: 28rpx;
                            color: #1d1e26;
                            font-weight: bold;
                            left: 135rpx;
                            top:50%;
                            transform: translateY(-50%);
                        }
                    } 
                    .date-con2{
                        position: absolute;
                        // width: 122rpx;
                        height: 100%;
                        left: 562rpx;
                        .time-bg{
                            position: absolute;
                            top:50%;
                            transform: translateY(-50%);
                            width: 122rpx;
                            height: 51rpx;
                        }
                        .time-text{ 
                            position: absolute;
                            font-size: 28rpx;
                            color: #1d1e26;
                            font-weight: bold;
                            left: 135rpx;
                            top:50%;
                            transform: translateY(-50%);
                        }
                    }
                }
                .date-picker {
                    position: relative;
                    z-index: 2;
                    width: 100%;
                    height: 250rpx;
                    background: transparent;
                    :deep(.date-picker::before) {
                        content: none;
                    }

                    :deep(.date-picker::after) {
                        content: none;
                    }
                    
                    .picker-item {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        height: 40rpx;
                        line-height: 40rpx;
                        
                        .picker-text {
                            font-size: 32rpx;
                            color: #1d1e26;
                            font-weight: bold;
                        }
                        
                        .picker-label {
                            font-size: 28rpx;
                            color: #1d1e26;
                            font-weight: bold;
                            margin-left: 8rpx;
                        }
                    }
                }
            }
    }
}
</style> 