<template>
	<view class="date-range-selector">
		<u-subsection :list="dateRangeList" keyName="label" :current="selected" @change="handleSubsectionChange" />
		<uni-datetime-picker :value="internalDateRange" type="daterange" @change="handleDatePickerChange" />
	</view>
</template>

<script>
	export default {
		props: {
			// Vue2 中使用 value 作为 v-model 的 prop
			value: {
				type: Array,
				required: true
			},
			dateRangeList: {
				type: Array,
				default: () => [{
						label: "今日",
						value: "day"
					},
					{
						label: "本周",
						value: "week"
					},
					{
						label: "本月",
						value: "month"
					}
				]
			}
		},
		data() {
			return {
				selected: 0,
				internalDateRange: this.value
			};
		},
		watch: {
			value(newVal) {
				if (JSON.stringify(newVal) !== JSON.stringify(this.internalDateRange)) {
					this.internalDateRange = newVal;
					this.resetSelectedIndex();
				}
			},
			internalDateRange(newVal) {
				this.$emit('input', newVal); // Vue2 中使用 input 事件
				this.$emit('subsection-change', newVal);
			}
		},
		methods: {
			// 获取日期范围
			getDateRange(type) {
				const now = new Date()
				let start, end

				if (type === 'week') {
					// 获取本周的开始（周一）和结束（周日）
					const day = now.getDay() || 7 // Sunday 为 0，设为 7
					start = new Date(now)
					start.setDate(now.getDate() - day + 1)

					end = new Date(start)
					end.setDate(start.getDate() + 6)
				} else if (type === 'month') {
					// 获取本月的开始和结束
					start = new Date(now.getFullYear(), now.getMonth(), 1)
					end = new Date(now.getFullYear(), now.getMonth() + 1, 0) // 本月最后一天
				} else if (type === 'day') {
					// 获取当天的开始和结束（00:00:00 到 23:59:59）
					start = new Date(now)
					start.setHours(0, 0, 0, 0)

					end = new Date(now)
					end.setHours(23, 59, 59, 999)
				} else {
					console.warn('不支持的类型:', type)
					return []
				}

				return [
					this.formatDateCus(start),
					this.formatDateCus(end)
				]
			},

			// 格式化日期
			formatDateCus(date) {
				const y = date.getFullYear()
				const m = (date.getMonth() + 1).toString().padStart(2, '0')
				const d = date.getDate().toString().padStart(2, '0')
				return `${y}-${m}-${d}`
			},

			handleSubsectionChange(index) {
				this.selected = index;
				const {
					value
				} = this.dateRangeList[index];
				this.internalDateRange = this.getDateRange(value);
			},
			handleDatePickerChange(newRange) {
				this.internalDateRange = newRange;
				this.resetSelectedIndex();
			},
			resetSelectedIndex() {
				const isPreset = this.dateRangeList.some((item, index) => {
					const range = this.getDateRange(item.value);
					return JSON.stringify(range) === JSON.stringify(this.internalDateRange);
				});

				if (!isPreset) {
					this.selected = -1; // 如果日期范围不匹配任何预设，取消选中状态
				}
			}
		},
		created() {
			// 默认选择今日
			if (!this.value || this.value.length === 0) {
				this.internalDateRange = this.getDateRange('day');
			} else {
				this.resetSelectedIndex();
			}
		}
	};
</script>

<style scoped>
	.date-range-selector {
		/* 可以写样式 */
	}
</style>