<template>
    <view>
        <view class="timeTitle">
            <view class="" v-if="initDate">
                <text style="font-size: 30rpx;">{{initDate}}</text>
                <text v-if="iconDirection == 'down'" class="iconfont icon-xiajiantou iconStyle" :style="{color: iconColor || ''}"></text>
                <text v-if="iconDirection == 'right'" class="iconfont icon-youjiantou iconStyle" :style="{color: iconColor || ''}"></text>
            </view>
            <view class="emptyTxt" v-else>
                <text v-if="startTxt" :style="{fontSize: placeholderSize}">{{startTxt}}</text>
                <text v-if="endTxt" :style="{fontSize: placeholderSize}">{{endTxt}}</text>
                <text v-if="iconDirection == 'down'" class="iconfont icon-xiajiantou iconStyle" :style="{color: iconColor || ''}"></text>
                <text v-if="iconDirection == 'right'" class="iconfont icon-youjiantou iconStyle" :style="{color: iconColor || ''}"></text>
            </view>
        </view>
        <uni-popup ref="timePopup" type="bottom" :maskClick="false">
            <view class="timeBox">
                <view class="titleBox">
                    <view @click.stop="cancel" style="color:#333;">取消</view>
                    <view style="color:#20279b;" @click.stop="confirm">确定</view>
                </view>
                <picker-view :indicator-style="indicatorStyle" :value="value" @change="bindChange" class="picker-view">
                    <picker-view-column v-if="showYear">
                        <view class="item" v-for="(item, index) in years" :key="index">
                            <view class="myItem" :class="{ 'selected': currentValue[0] === index }">
                                {{item}}年
                            </view>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="showMonth">
                        <view class="item" v-for="(item, index) in months" :key="index">
                            <view class="myItem" :class="{ 'selected': currentValue[1] === index }">
                                {{item}}月
                            </view>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="showDay">
                        <view class="item" v-for="(item, index) in days" :key="index">
                            <view class="myItem" :class="{ 'selected': currentValue[2] === index }">
                                {{item}}日
                            </view>
                        </view>
                    </picker-view-column>
                </picker-view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import dataHandling from "@/util/dataHandling";
import dayjs from 'dayjs';

export default {
    name: 'CommonTimePicker',
    props: {
        timeData: {
            type: Object,
            default: () => ({})
        },
        iconDirection: {
            type: String,
            default: 'down'
        },
        iconColor: {
            type: String,
            default: '#000'
        },
        visible: {
            type: Boolean,
            default: false
        },
        showYear: {
            type: Boolean,
            default: true
        },
        showMonth: {
            type: Boolean,
            default: true
        },
        showDay: {
            type: Boolean,
            default: false
        },
        birthDay: {
            type: Boolean,
            default: false
        },
        startTxt: {
            type: String,
            default: ''
        },
        endTxt: {
            type: String,
            default: ''
        },
        placeholderSize: {
            type: String,
            default: '30rpx'
        },
        yearStart: {
            type: Number,
            default: 2025
        },
        yearEnd: {
            type: Number,
        },
		
    },
    data() {
        const date = new Date();
        const currentYear = this.yearEnd || date.getFullYear();
        const startYear = this.yearStart;
        
        // 年份数组
        const years = [];
        for (let i = startYear; i <= currentYear; i++) {
            years.push(i);
        }
        
        // 月份数组
        const months = [];
        for (let i = 1; i <= 12; i++) {
            months.push(i);
        }
        
        // 内部默认值：使用当前日期（仅用于弹窗初始显示，不影响外部展示）
        let defaultYear = date.getFullYear();
        let defaultMonth = date.getMonth() + 1;
        let defaultDay = date.getDate();
        
        // 如果传入了 timeData 且有效，则使用传入值作为内部默认值
        if (this.timeData && (this.timeData.year || this.timeData.month || this.timeData.day)) {
            if (this.timeData.year) defaultYear = this.timeData.year;
            if (this.timeData.month) defaultMonth = this.timeData.month;
            if (this.timeData.day) defaultDay = this.timeData.day;
        }
        
        // 保证年份在范围内
        if (defaultYear < startYear) defaultYear = startYear;
        if (defaultYear > currentYear) defaultYear = currentYear;
        if (defaultMonth < 1) defaultMonth = 1;
        if (defaultMonth > 12) defaultMonth = 12;
        
        // 根据年月计算正确天数
        const maxDay = this.getDaysInMonth(defaultYear, defaultMonth);
        if (defaultDay > maxDay) defaultDay = maxDay;
        
        const days = [];
        for (let i = 1; i <= maxDay; i++) {
            days.push(i);
        }
        
        const yearIndex = Math.max(0, years.indexOf(defaultYear));
        const monthIndex = Math.max(0, defaultMonth - 1);
        const dayIndex = Math.max(0, defaultDay - 1);
        
        return {
            years,
            months,
            days,
            year: defaultYear,
            month: defaultMonth,
            day: defaultDay,
            value: [yearIndex, monthIndex, dayIndex],
            currentValue: [yearIndex, monthIndex, dayIndex],
            indicatorStyle: `height: 50px;`,
            initDate: '', // 初始不显示任何日期，占位符优先
        };
    },
    watch: {
        visible: {
            handler(newVal) {
                if (newVal) this.$refs.timePopup.open();
            }
        },
        timeData: {
            deep: true,
            immediate: true,
            handler(newVal) {
                if (newVal && (newVal.year || newVal.month || newVal.day)) {
					
                    this.updateSelectedDate(newVal);
                } else {
                    // 没有传入有效日期时，清空显示
                    this.initDate = '';
                }
            }
        },
        year() {
            if (this.showDay) this.updateDaysAndAdjust();
        },
        month() {
            if (this.showDay) this.updateDaysAndAdjust();
        }
    },
    methods: {
        getDaysInMonth(year, month) {
            return new Date(year, month, 0).getDate();
        },
        updateDaysAndAdjust() {
            const maxDay = this.getDaysInMonth(this.year, this.month);
            const newDays = [];
            for (let i = 1; i <= maxDay; i++) {
                newDays.push(i);
            }
            this.days = newDays;
            
            if (this.day > maxDay) {
                this.day = maxDay;
            }
            const dayIndex = Math.max(0, this.day - 1);
            if (this.currentValue.length >= 3) this.currentValue[2] = dayIndex;
            if (this.value.length >= 3) this.value[2] = dayIndex;
        },
        generateDateString(dateObj) {
            const parts = [];
            if (this.showYear && dateObj.year) parts.push(dateObj.year);
            if (this.showMonth && dateObj.month) {
                const month = dateObj.month < 10 ? '0' + dateObj.month : dateObj.month;
                parts.push(month);
            }
            if (this.showDay && dateObj.day) {
                const day = dateObj.day < 10 ? '0' + dateObj.day : dateObj.day;
                parts.push(day);
            }
            return parts.join('-');
        },
        updateSelectedDate(dateObj) {
            if (!dateObj) return;
            let needUpdateDays = false;
            if (dateObj.year && this.years.includes(dateObj.year)) {
                this.year = dateObj.year;
                const yearIndex = this.years.indexOf(dateObj.year);
                if (yearIndex >= 0) {
                    this.currentValue[0] = yearIndex;
                    this.value[0] = yearIndex;
                }
                needUpdateDays = true;
            }
            if (dateObj.month && dateObj.month >= 1 && dateObj.month <= 12) {
                this.month = dateObj.month;
                const monthIndex = dateObj.month - 1;
                this.currentValue[1] = monthIndex;
                this.value[1] = monthIndex;
                needUpdateDays = true;
            }
            if (dateObj.day && this.showDay) {
                this.day = dateObj.day;
            }
            if (needUpdateDays && this.showDay) {
                this.updateDaysAndAdjust();
            } else if (dateObj.day && this.showDay) {
                const maxDay = this.getDaysInMonth(this.year, this.month);
                if (this.day > maxDay) this.day = maxDay;
                const dayIndex = this.day - 1;
                this.currentValue[2] = dayIndex;
                this.value[2] = dayIndex;
            }
            // 更新显示文本
            this.initDate = this.generateDateString({
                year: this.year,
                month: this.month,
                day: this.day
            });
        },
        bindChange: dataHandling.debounce(function(e) {
            const val = e.detail.value;
            if (this.showYear && val[0] !== undefined) this.year = this.years[val[0]];
            if (this.showMonth && val[1] !== undefined) this.month = this.months[val[1]];
            
            if (this.showDay) {
                const maxDay = this.getDaysInMonth(this.year, this.month);
                const newDays = [];
                for (let i = 1; i <= maxDay; i++) newDays.push(i);
                this.days = newDays;
                let dayIndex = val[2] || 0;
                if (dayIndex >= this.days.length) dayIndex = this.days.length - 1;
                this.day = this.days[dayIndex];
                this.currentValue = [val[0], val[1], dayIndex];
                this.value = [val[0], val[1], dayIndex];
            } else {
                this.currentValue = val;
                this.value = val;
            }
        }, 50),
        cancel() {
            this.$emit('closeTime', false);
            this.$refs.timePopup.close();
        },
        confirm() {
            if (this.showDay) {
                const maxDay = this.getDaysInMonth(this.year, this.month);
                if (this.day > maxDay) {
                    this.day = maxDay;
                    this.currentValue[2] = maxDay - 1;
                    this.value[2] = maxDay - 1;
                }
            }
            this.initDate = this.generateDateString({
                year: this.year,
                month: this.month,
                day: this.day
            });
            this.$refs.timePopup.close();
            this.$emit('confirmDate', {
                year: this.year,
                month: this.month,
                day: this.day
            });
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep .uni-popup .uni-popup__wrapper {
    margin: 0 !important;
}
.timeTitle {
    font-size: 35rpx;
	.iconStyle{
		margin-left: 5rpx;
	}
    .emptyTxt {
        color: gray;
        font-size: 31rpx;
        display: flex;
        align-items: center;
    }
}
.timeBox {
    width: 100%;
    background-color: #fff;
    border-radius: 10rpx 10rpx 0 0;
    .titleBox {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 35rpx;
        padding: 20rpx 30rpx;
    }
    .picker-view {
        width: 100%;
        height: 600rpx;
        margin-top: 20rpx;
    }
    .item {
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        .myItem {
            padding: 10rpx;
            border-radius: 10rpx;
            color: #000;
            transition: transform 0.2s ease;
            &.selected {
                transform: scale(1.05);
                color: #20279b;
                font-weight: bold;
            }
        }
    }
}
</style>