<template>
	<view class="mask" v-if="show" @tap="close">
		<view class="box" @tap.stop="nullFunction">
			<view class="u-flex u-relative u-row-center u-p-30 top" v-if="props.isArea">
				<view class="font-bold u-font-32">{{props.title}}</view>
				<view class="close" @tap="close">
					<uni-icons type="closeempty" size="24"></uni-icons>
				</view>

			</view>
			<view class="u-p-30 u-flex u-flex-wrap gap-20 fastTime" v-if="props.isArea">
				<view class="item" v-for="(item,index) in fastTime" :key="index" @tap="changeTime(item.key)">
					{{item.title}}
				</view>
			</view>
			<picker-view :immediate-change="true" @pickend="pickend" :value="value" @change="bindChange"
				class="picker-view">
				<template v-if="props.mode==='all'||props.mode==='date'">
					<picker-view-column>
						<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
					</picker-view-column>
				</template>
				<template v-if="props.mode==='all'||props.mode==='time'">
					<picker-view-column>
						<view class="item" v-for="(item,index) in hours" :key="index">{{item}}时</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in minutes" :key="index">{{item}}分</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in seconds" :key="index">{{item}}秒</view>
					</picker-view-column>
				</template>
			</picker-view>
			<template v-if="props.isArea">
				<view class="u-text-center color-999">至</view>
				<picker-view :immediate-change="true" :value="value1" @pickend="pickend1" @change="bindChange1"
					class="picker-view">
					<template v-if="props.mode==='all'||props.mode==='date'">
						<picker-view-column>
							<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in days1" :key="index">{{item}}日</view>
						</picker-view-column>
					</template>
					<template v-if="props.mode==='all'||props.mode==='time'">
						<picker-view-column>
							<view class="item" v-for="(item,index) in hours" :key="index">{{item}}时</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in minutes" :key="index">{{item}}分</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in seconds" :key="index">{{item}}秒</view>
						</picker-view-column>
					</template>

				</picker-view>
			</template>


			<!-- 占位 -->
			<view style="height: 80px;"></view>
			<template v-if="props.isArea">
				<view class="fixed_b" >
					<my-button shape="circle" @tap="confirm">确定</my-button>
				</view>
			</template>
			<template v-else>
				<view class="fixed_b u-flex u-row-center">
					<view class="u-m-r-16">
						<my-button type="cancel" @tap="close" width="240">
							<view class="color-999">取消</view>
						</my-button>
					</view>
					<view class="u-m-l-16">
						<my-button @tap="confirm" width="240">确定</my-button>
					</view>
				</view>
			</template>
		</view>

	</view>

</template>

<script setup>
	import myButton from "@/components/my-components/my-button.vue"
	import {
		reactive,
		nextTick,
		ref
	} from 'vue';
	const props = defineProps({
		selTime:{
			type: [String,Number],
		},
		defaultIndex: {
			type: Array,
			default: () => {
				return []
			}
		},
		defaultTime: {
			type: Array,
			default: () => {
				return []
			}
		},
		title: {
			type: String,
			default: '筛选日期时间'
		},
		isArea: {
			//是否选中范围时间
			type: Boolean,
			default: true
		},
		mode: {
			//all date time
			type: String,
			default: 'time'
		},
		yearsLen:{
			type: Number,
			default:30
		}
	})
	const $nowDate = new Date()
	const nowDate = {
		year: $nowDate.getFullYear(),
		month: $nowDate.getMonth() + 1,
		day: $nowDate.getDate(),
		hours: $nowDate.getHours(),
		minutes: $nowDate.getMinutes(),
		seconds: $nowDate.getSeconds()
	}
	const yearsLen = props.yearsLen

	function returnYears() {
		if(props.isArea){
			return new Array(yearsLen).fill(1).map((v, index) => {
				return nowDate.year - index
			}).reverse()
		}else{
			return new Array(yearsLen).fill(1).map((v, index) => {
				return nowDate.year-Math.floor(yearsLen/2) + index
			})
		}
	}
	const years = returnYears()

	const months = new Array(12).fill(1).map((v, index) => {
		return index + 1
	})
	const days = ref(new Array(getMonthArea($nowDate, 'end').getDate()).fill(1).map((v, index) => {
		return index + 1
	}))
	const days1 = ref(new Array(getMonthArea($nowDate, 'end').getDate()).fill(1).map((v, index) => {
		return index + 1
	}))
	const hours = new Array(24).fill(1).map((v, index) => {
		return index
	})
	const minutes = new Array(60).fill(1).map((v, index) => {
		return index
	})
	const seconds = new Array(60).fill(1).map((v, index) => {
		return index
	})
	const fastTime = reactive([{
			title: '今日',
			key: 'now'
		},
		{
			title: '昨日',
			key: 'prve'
		},
		{
			title: '本月',
			key: 'nowMonth'
		},
		{
			title: '上月',
			key: 'prveMonth'
		}
	])



	function setPrveDay() {

	}

	function setNowMoneth() {

	}

	function setprveMoneth() {

	}


	function setDay(start, end) {
		value.value = [
			start.year,
			start.month,
			start.day,
			0,
			0,
			0,
		]
		value1.value = [
			end.year,
			end.month,
			end.day,
			23,
			59,
			59,
		]
	}

	function changeTime(key) {
		const yearIndex = years.findIndex(v => v == nowDate.year)
		const prveyearIndex = years.findIndex(v => v == nowDate.year) - 1
		const nowMonthIndex = nowDate.month - 1
		const nowDayIndex = nowDate.day - 1
		const dataMap = {
			now: function() {
				return {
					start: {
						year: yearIndex,
						month: nowMonthIndex,
						day: nowDayIndex
					},
					end: {
						year: yearIndex,
						month: nowMonthIndex,
						day: nowDayIndex
					}
				}
			},
			prve: function() {
				const oneDay = 1000 * 60 * 60 * 24
				const date = new Date(new Date(nowDate.year, nowDate.month, nowDate.day, 0, 0, 0).getTime() -
					oneDay)
				return {
					start: {
						year: years.findIndex(v => v == date.getFullYear()),
						month: date.getMonth() - 1 < 0 ? 11 : date.getMonth() - 1,
						day: date.getDate() - 1
					},
					end: {
						year: years.findIndex(v => v == date.getFullYear()),
						month: date.getMonth() - 1 < 0 ? 11 : date.getMonth() - 1,
						day: date.getDate() - 1
					}
				}
			},
			nowMonth: function() {
				return {
					start: {
						year: yearIndex,
						month: nowMonthIndex,
						day: 0
					},
					end: {
						year: yearIndex,
						month: nowMonthIndex,
						day: new Date(nowDate.year, nowDate.month, 0).getDate() - 1
					}
				}
			},
			prveMonth: function() {
				const oneDay = 1000 * 60 * 60 * 24
				const date = new Date(new Date(nowDate.year, nowDate.month - 1, 0, 0, 0).getTime() - oneDay)
				console.log(date.getMonth());
				return {
					start: {
						year: years.findIndex(v => v == date.getFullYear()),
						month: date.getMonth(),
						day: 0
					},
					end: {
						year: years.findIndex(v => v == date.getFullYear()),
						month: date.getMonth(),
						day: date.getDate()
					}
				}
			}
		}
		const data = dataMap[key]()
		setDay(data.start, data.end)
		changeDays(false, value.value)
		changeDays(true, value1.value)

		console.log(value1.value);
		const start = returnDateString(value.value)
		const end = returnDateString(value1.value)

		emits('confirm', {
			text: `${start}——${end}`,
			start,
			end
		})
		close()
	}
	let value = ref([])
	let value1 = ref([])
	initValue()


	function returnFindIndex(arr) {
		const yearIndex = years.findIndex(v => v == arr[0])
		const monthIndex = arr[1]
		const dayIndex = arr[2] - 1
		const hIndex = arr[3]
		const mIndex = arr[4]
		const sIndex = arr[5]
		return [
			yearIndex, monthIndex, dayIndex, hIndex, mIndex, sIndex
		]
	}

	function initValue() {
		if (props.defaultTime.length && !props.isArea) {
			value.value = returnFindIndex(props.defaultTime)
		} else {
			const yearIndex = years.findIndex(v => v == nowDate.year)
			value.value = [
				yearIndex,
				nowDate.month - 1,
				nowDate.day - 1,
				0,
				0,
				0,
			]
			value1.value = [
				yearIndex,
				nowDate.month - 1,
				nowDate.day - 1,
				23,
				59,
				59,
			]
		}
	}

	let show = ref(false)
	const emits = defineEmits('close', 'open', 'confirm')

	function toggle() {
		show.value = !show.value
		if (show.value) {
			open()
		} else {
			close()
		}
	}

	function close() {
		show.value = false
		// emits('close', false)
	}
	
	
	function open() {
		if(typeof props.selTime==='number'){
			const d=new Date(props.selTime)
			value.value[0]=years.findIndex(v=>v===d.getFullYear())
			value.value[1]=months.findIndex(v=>v===d.getMonth())+1
			value.value[2]=days.value.findIndex(v=>v===d.getDate())
		}
		show.value = true
		// emits('open', true)
	}

	function returnDateString(arr, isObj) {
		const year = years[arr[0]]
		const month = arr[1] + 1
		const day = arr[2] + 1
		const hour = ('0' + (arr[3]||0)).slice(-2)
		console.log(hour)
		const min = ('0' + (arr[4]||0)).slice(-2)
		const sen = ('0' +  (arr[5]||0)).slice(-2)
		if (isObj) {
			return new Date(year, month, day, hour, min, sen)
		}
		return `${year}-${month}-${day} ${hour}:${min}:${sen}`
	}


	function confirm(e) {
		console.log(value.value);
		const start = returnDateString(value.value)
		console.log(start);
		const end = returnDateString(value1.value)
		if (!props.isArea) {
			emits('confirm', start)
		} else {
			emits('confirm', {
				text: `${start}——${end}`,
				start,
				end
			})
		}

		close()
	}

	function returnMonthStart(arr) {
		return new Date(years[arr[0]], months[arr[1]] - 1, 1).getDate();
	}

	function returnMonthEnd(arr) {
		return new Date(years[arr[0]], months[arr[1]], 0).getDate();
	}

	//防抖
	function debounce(fn, wait) {
		let timeout = null;
		return function() {
			let context = this;
			let args = arguments;
			if (timeout) clearTimeout(timeout);
			let callNow = !timeout;
			timeout = setTimeout(() => {
				timeout = null;
			}, wait);
			if (callNow) fn.apply(context, args);
		};
	}

	/**
	 * @param {Object} isDays1 //是否是结束时间选择
	 * @param {Object} arr
	 */
	function changeDays(isDays1, arr) {
		const end = returnMonthEnd(arr)
		if (end) {
			if (isDays1) {
				days1.value = new Array(end).fill(1).map((v,
					index) => {
					return index + 1
				})
			} else {
				days.value = new Array(end).fill(1).map((v,
					index) => {
					return index + 1
				})
			}

		}
	}



	function bindChange(e) {
		const startTotal = returnDateString(e.detail.value, true).getTime()
		const endTotal = returnDateString(value1.value, true).getTime()
		value.value = e.detail.value
		setTimeout(()=>{
			if (props.isArea) {
				value.value = startTotal > endTotal ? value1.value : e.detail.value
			}
			debounce(changeDays(false, value.value), 100)
		},10)
		// nextTick(() => {
		// 	if (props.isArea) {
		// 		value.value = startTotal > endTotal ? value1.value : e.detail.value
		// 	}
		// 	console.log(value.value);
		// 	debounce(changeDays(false, value.value), 100)
		// })
	}

	function bindChange1(e) {
		const startTotal = returnDateString(value.value, true).getTime()
		const endTotal = returnDateString(e.detail.value, true).getTime()
		value1.value = e.detail.value
		nextTick(() => {
			if (props.isArea) {
				value1.value = endTotal < startTotal ? value.value : e.detail.value
			}
			debounce(changeDays(true, value1.value), 100)
		})
	}

	function getDayDate(date = new Date(), type) {
		const now = date
		if (type === 'start') {
			const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
			return startOfDay
		}
		if (type === 'end') {
			const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
			return endOfDay;
		}
	}

	function getMonthArea(date = new Date(), type) {
		let now = date
		let currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
		let currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
		if (type === 'start') {
			return currentMonthStart
		}
		if (type === 'end') {
			return currentMonthEnd;
		}
		return {
			start: currentMonthStart,
			end: currentMonthEnd
		};
	}

	function nullFunction() {
	
	}

	function pickend(e) {
		console.log(e);
	}

	function pickend1(e) {
		console.log(e);
	}
	defineExpose({
		close,
		open,
		confirm,
		toggle
	})
</script>

<style lang="scss" scoped>
	.fastTime {
		.item {
			background-color: rgb(247, 247, 247);
			padding: 6rpx 40rpx;
			border-radius: 6rpx;
			font-size: 32rpx;
		}
	}

	.top {
		border-bottom: 1px solid #eee;
	}

	.close {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: 30rpx;
	}

	.mask {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		z-index: 999;
		background-color: rgba(51, 51, 51, .5);

		.item {
			line-height: 34px;
			text-align: center;
		}

		.box {
			position: absolute;
			background-color: #fff;
			bottom: 0;
			left: 0;
			right: 0;
			border-radius: 16rpx 16rpx 0 0;
		}
	}

	.fixed_b {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 30rpx;
		z-index: 100;
		background-color: #fff;
	}

	.picker-view {
		width: 750rpx;
		height: 300rpx;
	}
</style>