<template>
	<view class="selectTime">
		<view class="selectTime-time" :class="{'selectTime-time-y': startTime}" @click="openPicker(startTime, 0)">
			{{ startTime || '开始时间' }}
		</view>
		<view class="selectTime-time" :class="{'selectTime-time-y': endTime}" @click="openPicker(endTime, 1)">
			{{ endTime || '结束时间' }}
		</view>
		<timeDatePicker ref="timePopup" @confirmTime="confirmTime" v-model="timeValue" :timeIndex="timeIndex"
			:timeList="value" :type="type"></timeDatePicker>
	</view>
</template>

<script>
	import timeDatePicker from 'components/time-picker/time-date-picker.vue';
	export default {
		data() {
			return {
				startTime: null,
				endTime: null, // 修复拼写错误：endTiem → endTime
				timeValue: null,
				timeIndex: 0,
			};
		},
		components: {
			timeDatePicker,
		},
		props: {
			value: {
				type: Array,
				default: () => [] // 确保默认值是数组
			},
			disabled: {
				type: Boolean,
				default: false,
			},
			type: {
				type: String,
				default: 'datetimerange', // 身份证有效期默认用日期范围
			}
		},
		watch: {
			// 监听父组件传入的value变化，同步到子组件
			value: {
				immediate: true, // 初始化时立即执行
				handler(newVal) {
					if (Array.isArray(newVal) && newVal.length === 2) {
						this.startTime = newVal[0];
						this.endTime = newVal[1];
					}
				}
			}
		},
		methods: {
			openPicker(time, index) {
				if (this.disabled) return;
				this.timeIndex = index;
				this.timeValue = time;
				this.$refs.timePopup.openTimePopup();
			},
			confirmTime(e) {
				// 更新对应的值
				if (this.timeIndex === 0) {
					this.startTime = e;
				} else {
					this.endTime = e;
				}

				// 确保数组格式正确
				const timeArry = [this.startTime || '', this.endTime || ''];
				// 触发父组件更新
				this.$emit("input", timeArry);
				// 额外触发change事件，方便父组件处理
				this.$emit("change", timeArry);
			}
		}
	};
</script>

<style scoped lang="less">
	.selectTime {
		width: 100%;
		flex: 1;
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
		column-gap: 22rpx;

		.selectTime-time {
			width: 100%;
			font-weight: 400;
			font-size: 28rpx;
			color: #CACCCC;
			line-height: 40rpx;
			text-align: left;
			font-style: normal;
			height: 72rpx;
			border: 1rpx solid #E5E5E5;
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			border-radius: 10rpx;
			transition: all 0.3s; // 增加过渡效果
		}

		.selectTime-time-y {
			color: #333;
			border-color: #409EFF; // 选中时改变边框颜色
		}

		// 禁用状态样式
		&.disabled {
			.selectTime-time {
				background-color: #f5f5f5;
				cursor: not-allowed;
			}
		}
	}
</style>