<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>
	import {
		getDateRange
	} from "@/utils/utils";

	export default {
		props: {
			// Vue2 中使用 value 作为 v-model 的 prop
			value: {
				type: Array,
				required: true
			},
			dateRangeList: {
				type: Array,
				default: () => [{
						label: "本日",
						value: "day"
					},
					{
						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: {
			handleSubsectionChange(index) {
				this.selected = index;
				const {
					value
				} = this.dateRangeList[index];
				this.internalDateRange = getDateRange(value);
			},
			handleDatePickerChange(newRange) {
				this.internalDateRange = newRange;
			},
			resetSelectedIndex() {
				const isPreset = this.dateRangeList.some((item, index) => {
					const range = getDateRange(item.value);
					return JSON.stringify(range) === JSON.stringify(this.internalDateRange);
				});

				if (!isPreset) {
					this.selected = 0;
				}
			}
		},
		created() {
			this.resetSelectedIndex();
		}
	};
</script>

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