<template>
	<view class="time-range">
		<uni-datetime-picker v-model="dateRange" type="daterange" start="2000-01-01" :end="defaultDateRange[1]"
			:clear-icon="false" rangeSeparator="至" @change="changeTime" />
		<view class="btns-container">
			<button size="mini" class="small" :disabled="loading" @click="reset">重置</button>
			<button type="primary" class="small" size="mini" :disabled="loading" @click="search">搜索</button>
			<button type="primary" class="large" size="mini" :disabled="loading"
				@click="timeLine('before')">上一时段</button>
			<button type="primary" class="large" size="mini" @click="timeLine('next')"
				:disabled="loading || disabledNextBtn">下一时段</button>
		</view>
	</view>
</template>

<script>
	import {
		formatDate
	} from '@/utils/filters'
	export default {
		computed: {
			disabledNextBtn() {
				return new Date(this.dateRange[1]) >= new Date(this.defaultDateRange[1])
			}
		},
		data() {
			return {
				loading: false,
				dateRange: [],
				defaultDateRange: [],
			}
		},
		methods: {
			init() {
				const now = new Date(),
					formatNow = formatDate(now);
				const weekAgo = formatDate(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000))
				this.dateRange = [weekAgo, formatNow];
				this.defaultDateRange = [weekAgo, formatNow];
				this.$emit('updateDate', this.dateRange)
			},
			changeTime(val) {
				this.dateRange = val || []
			},
			showBtnLoading(status) {
				this.loading = status
			},
			resetDate() {
				this.dateRange = this.defaultDateRange
			},
			//重置 设置时间范围为初始化时间段
			reset() {
				this.resetDate()
				this.$emit('updateDate', this.dateRange)
			},
			// 搜索
			search() {
				this.$emit('updateDate', this.dateRange)
			},
			timeLine(type) {
				//baseTime,maxTime 毫秒数
				let baseTime = type === 'before' ? new Date(this.dateRange[0]).getTime() - (24 * 60 * 60 * 1000) :
					new Date(this.dateRange[1]).getTime() + (24 * 60 * 60 * 1000),
					maxTime = new Date(this.defaultDateRange[1]).getTime()
				//updateTime 毫秒数
				let updateTime = type === 'before' ? baseTime - 7 * 24 * 60 * 60 * 1000 : baseTime + 7 * 24 * 60 * 60 *
					1000
				if (type === 'next' && updateTime >= maxTime) updateTime = maxTime
				const start = formatDate(type === 'before' ? updateTime : baseTime)
				const end = formatDate(type === 'before' ? baseTime : updateTime)
				this.dateRange = [start, end]
				this.$emit('updateDate', this.dateRange)
			},
		}
	}
</script>
<style lang="scss" scoped>
	.time-range {
		padding: 10rpx 22rpx;

		.btns-container {
			margin-top: 20rpx;
			margin-bottom: 40rpx;

			uni-button {
				padding-left: 0;
				padding-right: 0;
				text-align: center;

				&:not(:last-child) {
					margin-right: 20rpx;
				}
			}

			.small {
				width: 120rpx;
			}

			.large {
				width: 180rpx;
			}
		}
	}
</style>