<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?iconColor:''}"></text>
				<text v-if="iconDirection== 'right'" class="iconfont icon-youjiantou iconStyle"></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"></text>
			<text v-if="iconDirection== 'right'" class="iconfont icon-youjiantou iconStyle"></text>
          </view>
        </view>
        <uni-popup ref="timePopup" type="bottom" :maskClick="false">
            <view class="timeBox">
                <view class="titleBox">
                    <view @click="cancle" style="color:#333;">
                        取消
                    </view>
                    <view style="color:#20279b;" @click="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: function () {
            const date = new Date()
            const years = []
            const months = []
            const days = []
            const day = this.timeData.day || dataHandling.getDateParts().day
            const currentYear =this.yearEnd|| date.getFullYear()
            
            // 初始值优先使用传入的timeData，没有则使用当前日期
            const initialYear = this.timeData.year || dataHandling.getDateParts().year
            const initialMonth = this.timeData.month || dataHandling.getDateParts().month
           
            const startYear = this.yearStart
            for (let i = startYear; i <= currentYear; i++) {
                years.push(i)
            }
            
            for (let i = 1; i <= 12; i++) {
                months.push(i)
            }
            for (let i = 1; i <= 31; i++) {
                days.push(i)
            }
            
            return {
                title: 'picker-view',
                years,
                months,
                year: initialYear,
                month: initialMonth,
                day: this.timeData.day|| day ,
                value: [
                    Math.max(0, years.indexOf(initialYear)),
                    Math.max(0, initialMonth - 1),
                    Math.max(0, (this.timeData.day || day) - 1)
                ],
                days,
                indicatorStyle: `height: 50px;`,
                initDate: this.generateDateString({
                    year: this.timeData.year ,
                    month: this.timeData.month ,
                    day: this.timeData.day 
                }),
                currentValue: [
                    Math.max(0, years.indexOf(initialYear)),
                    Math.max(0,initialMonth - 1),
                    Math.max(0, (this.timeData.day || day) - 1)
                ]
            }
        },
        watch: {
            visible: {
                deep: true,
                handler(newVal) {
                    if(newVal) this.$refs.timePopup.open()
                }
            },
            birthDay: {
                immediate: true,
                handler(newVal) {
                    this.updateYears(newVal)
                }
            },
            timeData: {
                deep: true,
                immediate: true,
                handler(newVal) {
                    if (newVal && (newVal.year || newVal.month || newVal.day)) {
                        this.updateSelectedDate(newVal)
                    }
                }
            }
        },
        methods: {
            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('-');
            },
            updateYears(isBirthDay) {
                // 更新年份范围
                const date = new Date()
                const currentYear = this.yearEnd|| date.getFullYear()
                const startYear = this.yearStart
                this.years = []
                for (let i = startYear; i <= currentYear; i++) {
                    this.years.push(i)
                }
                
                // 确保当前选中的年份在新范围内
                const yearIndex = this.years.indexOf(this.year)
                if (yearIndex >= 0) {
                    this.currentValue[0] = yearIndex
                    this.value[0] = yearIndex
                } else {
                    // 如果当前年份不在新范围内，选择最近的年份
                    const newYearIndex = Math.max(0, this.years.length - 1)
                    this.year = this.years[newYearIndex]
                    this.currentValue[0] = newYearIndex
                    this.value[0] = newYearIndex
                }
            },
            updateSelectedDate(dateObj) {
                // 更新选中的日期
                if (dateObj.year) {
                    this.year = dateObj.year
                    const yearIndex = this.years.indexOf(dateObj.year)
                    if (yearIndex >= 0) {
                        this.currentValue[0] = yearIndex
                        this.value[0] = yearIndex
                    }
                }
                
                if (dateObj.month) {
                    this.month = dateObj.month
                    const monthIndex = Math.max(0, dateObj.month - 1)
                    this.currentValue[1] = monthIndex
                    this.value[1] = monthIndex
                }
                
                if (dateObj.day) {
                    this.day = dateObj.day
                    const dayIndex = Math.max(0, dateObj.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;
                this.currentValue = val;
                this.year = this.years[val[0]];
                this.month = this.months[val[1]];
                this.day = this.days[val[2]];
            }, 50),
            cancle(){
                this.$emit('closeTime', false)
                this.$refs.timePopup.close()
            },
            confirm(){
				console.log('currentValue',this.currentValue);
                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;
		.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>

