<template>
	<view class="popupCon" v-if="current">
		<view class="header">
			<view class="headerTab">
				<view 
					class="headerTxt" 
					v-for="item in lableList" 
					:key="item.value"
					:class="{active:item.value == current }"
					@click="current = item.value"
				>
					{{item.name}}
				</view>
			</view>
			<view class="closeIcon" @click="$emit('closePop')">
				<text class="iconfont icon-guanbi iconStyle" ></text>
			</view>
		</view>
		<view class="popupContent">
			
			<picker-view v-if="current=='1'" :indicator-style="indicatorStyle" :value="value" @change="bindChange" class="picker-view">
					<picker-view-column>
						<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>
						<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>
			 <view class="zidingyiBox" v-if="current=='2'">
			 	<view class="one">
			 		<view class="commonTitle">
			 			订单时间
			 		</view>
					<view class="oneCon">
						
						<button 
							type="default" 
							plain="true"
							v-for="item in monthList"
							:key="item.value"
							size="mini"
							class="oneItem"
							:class="{active:item.value == currentMonth }"
							 @click="changMonth(item)"
						>
							{{item.name}}
						</button>
					</view>
			 	</view>
				<view class="two">
					<view class="commonTitle" style="margin-top: 40rpx;">
						自定义
					</view>
					<view style="width: 100%;" class="timePickerBox">
						<view class="timeHeader">
							<view
								class="header-time" 
								@click="openTime('start')"
							>
								<CommonTimePicker 
									:timeData="startDate"
									:visible="showTime1" 
									:birthDay="true"
									:showDay="true"
									:yearStart="2024"
									startTxt="开始日期"
									placeholderSize="26rpx"
									@confirmDate="changeStartTime" 
									@closeTime="showTime1=false"
									
								/>
							</view>
							<view style="margin: 10rpx 20rpx;font-size: 28rpx;">
								<text>-</text>
							</view>
							
							<view
								class="header-time" 
								@click="openTime('end')"
							>
								<CommonTimePicker 
									:timeData="endDate"
									:visible="showTime2" 
									:birthDay="true"
									:showDay="true"
									:yearStart="2024"
									endTxt="结束日期"
									placeholderSize="26rpx"
									@confirmDate="changeEndTime" 
									@closeTime="showTime2=false"
								>
								</CommonTimePicker>
							</view>
						</view>
					</view>
				</view>
			 </view>
			 <view class="bottomBtn" @click="comfirm">
			 	<view class="bottonTxt">
			 		确定
			 	</view>
			 </view>
		</view>
	</view>
</template>

<script>
	import dataHandling from "@/util/dataHandling";
	import CommonTimePicker from '@/components/commonTimePicker/commonTimePicker.vue';
	import dayjs from 'dayjs';
	
	export default {
		components: {
			CommonTimePicker
		},
		props: {
			dateParts: {
				type: Object
			},
			currentItem: {
				type: String
			},
			timeType: {
				type: String
			},
			childData: { //父组件中选好的日期，方便子组件回显值
				type: Object,
				default: () => ({})
			},
		},
		 data: function () {
		            const date = new Date()
		            const years = []
		            const months = []
		            const days = []
		            const day = date.getDate()
					const initialYear = this.childData?.year || this.dateParts.year
					const initialMonth = this.childData?.month || this.dateParts.month
					// 初始化startDate和endDate
					  let initialStartDate = {year: null, month: null, day: null};
					  let initialEndDate = {year: null, month: null, day: null};
		            for (let i =2025; i <= date.getFullYear(); i++) {
		                years.push(i)
		            }
		            for (let i = 1; i <= 12; i++) {
		                months.push(i)
		            }
		            for (let i = 1; i <= 31; i++) {
		                days.push(i)
		            }
					
					if (this.childData?.currentDate && this.childData.currentDate.length === 2) {
					    const [startStr, endStr] = this.childData.currentDate;
					    const startParts = startStr.split('-');
					    const endParts = endStr.split('-');
					    
					    initialStartDate = {
					      year: parseInt(startParts[0]),
					      month: parseInt(startParts[1]),
					      day: parseInt(startParts[2])
					    };
					    
					    initialEndDate = {
					      year: parseInt(endParts[0]),
					      month: parseInt(endParts[1]),
					      day: parseInt(endParts[2])
					    };
					  }
					
					
		            return {
		                title: 'picker-view',
		                years,
		                months,
						year: initialYear,
						month: initialMonth,
						value: [
						        Math.max(0, years.indexOf(initialYear)), // 防止-1
						        Math.max(0, initialMonth - 1),
						        0
						],
		                days,
		                day,
		                indicatorStyle: `height: 50px;`,
						lableList:[
							{name:'月份选择',value:'1'},
							{name:'自定义',value:'2'},
						],
						 current: this.childData?.current || '1',//当前选择的那个tab
						monthList:[
							{name:'本月',value:'1'},
							{name:'近90天',value:'2'},
							{name:'近180天',value:'3'},
						],
						currentMonth:this.childData?.value || '',//选择的monthList中的哪一种方式
						currentDate:this.childData?.currentDate || [],//选择的日期,
						currentValue: [ //月份这种方式的时候对应的当前时间
						    Math.max(0, years.indexOf(initialYear)),
						    Math.max(0, initialMonth - 1),
						    // Math.max(0, (this.timeData.day || day) - 1)
						],
						startDate: initialStartDate,
						endDate: initialEndDate,
						showTime1:false,
						showTime2:false,
		            }
		        },
				watch: {
				   childData: {
				      deep: true,
				      immediate: true, // 添加immediate确保初始化时也执行
				      handler(newVal) {
				        this.current = newVal.current || '1';
				        
				        // 处理月份选择模式
				        if (newVal.timeType === '8') {
				          this.year = newVal.year;
				          this.month = newVal.month;
				          this.value = [
				            Math.max(0, this.years.indexOf(newVal.year)),
				            Math.max(0, newVal.month - 1),
				            0
				          ];
				        }
				        
				        // 处理自定义日期模式
				        if (newVal.timeType === '9' || newVal.timeType === '10') {
				          this.currentMonth = newVal.value || '';
				          
				          // 只有当currentDate存在且格式正确时才更新
				          if (newVal.currentDate && Array.isArray(newVal.currentDate) && newVal.currentDate.length === 2) {
				            const [startStr, endStr] = newVal.currentDate;
				            
				            // 解析开始日期
				            if (startStr) {
				              const startParts = startStr.split('-');
				              this.startDate = {
				                year: parseInt(startParts[0]) || null,
				                month: parseInt(startParts[1]) || null,
				                day: parseInt(startParts[2]) || null
				              };
				            }
				            
				            // 解析结束日期
				            if (endStr) {
				              const endParts = endStr.split('-');
				              this.endDate = {
				                year: parseInt(endParts[0]) || null,
				                month: parseInt(endParts[1]) || null,
				                day: parseInt(endParts[2]) || null
				              };
				            }
				            
				            // 更新currentDate确保格式一致
				            this.currentDate = newVal.currentDate;
				          }
				        }
				      }
				    },
					// 监听日期选择器变化
					    currentDate(newVal) {
					      if (newVal && newVal.length === 2) {
							  
					        this.checkDateRange(newVal);
					      }
					    }
				  }, 
		        methods: {
					changeStartTime(obj){
						this.startDate = obj
						this.currentDate[0] = `${obj.year}-${obj.month<10?`0${obj.month}`:obj.month}-${obj.day<10?`0${obj.day}`:obj.day}`
						
						this.showTime1 = false
						this.checkDateRange(this.currentDate)
					},
					changeEndTime(obj){
						this.endDate = obj
						this.currentDate[1] = `${obj.year}-${obj.month<10?`0${obj.month}`:obj.month}-${obj.day<10?`0${obj.day}`:obj.day}`
						this.showTime2 = false
						this.checkDateRange(this.currentDate)
					},
					openTime(key){
						if(key=='start'){
							this.showTime1 = true
							return
						}
						if(key=='end'){
							if(!this.startDate.year){
								uni.showToast({
									title: '请先选择开始日期',
									duration: 2000,
									icon: 'none'
								})
								 this.currentMonth = ''
								return
							}
							this.showTime2 = true
							
						}
					},
					 // 检查日期范围是否匹配预设范围
					    checkDateRange(dateRange) {
							console.log('dateRange',dateRange);
					      if (!dateRange || dateRange.length !== 2) return;
					      
					      const [start, end] = dateRange;
					      const today = dayjs();
					      const startDate = dayjs(start);
					      const endDate = dayjs(end);
					      
					      // 1. 检查是否本月
					      const currentMonthRange = dataHandling.getCurrentMonthRange();
					      if (this.isSameRange(dateRange, currentMonthRange)) {
					        this.$nextTick(()=>{
					        	this.currentMonth = '1';
					        })
					        return;
					      }
					      
					      // 2. 检查是否近三月
					      const recent3MonthsRange = dataHandling.getRecentDaysRange(90);
					      if (this.isSameRange(dateRange, recent3MonthsRange)) {
					       this.$nextTick(()=>{
					       	this.currentMonth = '2';
					       })
					        return;
					      }
					      
					      // 3. 检查是否近半年
					      const recent6MonthsRange = dataHandling.getRecentDaysRange(180);
					      if (this.isSameRange(dateRange, recent6MonthsRange)) {
					        this.$nextTick(()=>{
					        	this.currentMonth = '3';
					        })
					        return;
					      }
					      // 都不匹配则清空
					      this.$nextTick(()=>{
							  this.currentMonth = '';
						  })
						 
					    },
					    
					    // 比较两个日期范围是否相同
					    isSameRange(range1, range2) {
					      if (!range1 || !range2 || range1.length !== 2 || range2.length !== 2) return false;
					      
					      const format = 'YYYY-MM-DD';
					      return (
					        dayjs(range1[0]).format(format) === dayjs(range2[0]).format(format) &&
					        dayjs(range1[1]).format(format) === dayjs(range2[1]).format(format)
					      );
					    },
					 // 修改月份选择方法
					  changMonth(item) {
					    let dateRange = []
					    switch(item.value) {
					      case '1': // 本月
					        dateRange = dataHandling.getCurrentMonthRange()
					        break
					      case '2': // 近三月
					        dateRange = dataHandling.getRecentDaysRange(90)
					        break
					      case '3': // 近半年
					        dateRange = dataHandling.getRecentDaysRange(180)
					        break
					    }
						const [start, end] = dateRange;
					    this.currentDate = dateRange
						this.startDate = {year:Number(start.split('-')[0]),month:Number(start.split('-')[1]),day:Number(start.split('-')[2])}
					    this.endDate = {year:Number(end.split('-')[0]),month:Number(end.split('-')[1]),day:Number(end.split('-')[2])}
						
					    this.currentMonth = item.value
					   	this.$emit('comfirm',{currentDate:this.currentDate,current:this.current,...item,timeType:'9'})
					   
					  },
					  changeMonthTime(obj){
						this.monthDate = obj
						this.year = obj.year;
						this.month = obj.year;
						this.showTime1 = false
					},
					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),
					comfirm(){
						if(this.current=='1'){
							this.$emit('comfirm',{year:this.year,month:this.month,current:this.current,timeType:'8'})
						}
						if(this.current=='2'){
							console.log('this.currentDate',this.currentDate);
							if(!this.currentDate.length){
								uni.showToast({
									title: `请选择时间`,
									duration: 1000,
									icon: 'none'
								});
								return
							}
							let newObj = {}
							if(this.monthList.filter(item=>item.value == this.currentMonth).length>0){
								newObj = this.monthList.filter(item=>item.value == this.currentMonth)[0]
							}
							if(this.currentDate.length==1){
								uni.showToast({
									title: `请选择结束日期`,
									duration: 1000,
									icon: 'none'
								});
								return
							}
							if (this.currentDate[1] < this.currentDate[0]) {
								uni.showToast({
									title: `结束日期不能小于起始日期`,
									duration: 1000,
									icon: 'none'
								});
								return
							}
							this.$emit('comfirm',{...newObj,current:this.current,timeType:'10',currentDate:this.currentDate,})
						}
					},
		        },
				mounted() {
					
				}
	}
</script>

<style lang="scss" scoped>
.popupCon{
	box-sizing: border-box;
	width: 100%;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 15rpx 15rpx 0 0;
	.header{
		box-sizing: border-box;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid rgba(242, 242, 242, 1);
		// padding-bottom: 20rpx;
		.headerTab{
			padding: 10rpx 15rpx 0 15rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			.headerTxt{
				margin-right: 40rpx;
				padding-bottom: 20rpx;
				font-size: 28rpx;
				&.active{
					border-bottom: 2px solid rgba(32, 39, 155, 1);
					
				}
			}
		}
	}
	.popupContent{
		.picker-view {
			width: 100%;
			height: 400rpx;
			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;
		        }
		    }
		}
		.zidingyiBox{
			box-sizing: border-box;
			width: 100%;
			padding: 0 15rpx;
			height: 400rpx;
			.commonTitle{
				font-size: 30rpx;
				font-weight: 500;
				color: rgba(34, 34, 34, 1);
				margin: 20rpx 0;
			}
			.one{
				width: 100%;
				box-sizing: border-box;
				.oneCon{
					display: flex;
					align-items: center;
					justify-content: space-between;
					.oneItem{
						border: 1px solid rgba(128, 128, 128, 1);
						padding: 0rpx 40rpx;
						color: rgba(0, 0, 0, 1);
						border-radius: 10rpx;
						font-size: 27rpx;
						&.active{
							border: 1px solid rgba(32, 39, 155, 1);
							color: rgba(32, 39, 155, 1);
						}
					}
				}
			}
			.two{
				.timePickerBox{
					width: 100%;
					box-sizing: border-box;
					.timeHeader{
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin: 40rpx 100rpx;
						box-sizing: border-box;
						.header-time {
							background: rgba(245, 245, 245, 1);
							padding: 10rpx 15rpx;
							width: 300rpx;
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}
		.bottomBtn{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			box-sizing: border-box;
			.bottonTxt{
				text-align: center;
				background-color: rgba(32, 39, 155, 1);
				padding: 20rpx 30rpx;
				border-radius: 60rpx;
				margin: 30rpx 0;
				color: #fff;
				width: 300rpx;
				font-size: 28rpx;
			}
			
		}
	}
	
}
</style>
