<script setup>
	/**
	 * 闹钟组件 仅对nvue兼容
	 */

	import {
		onMounted,
		ref,
		reactive,
		getCurrentInstance,
		watch,
		defineExpose,
		computed,
	} from 'vue';
	// 工具库
	import util from '@/common/js/util';
	// api
	import api from '@/api/index.js'
	import {
		before,
		result
	} from 'lodash';

	const {
		proxy
	} = getCurrentInstance()
	// 类型列表
	const typeList = reactive([{
		name: '倒计时闹钟',
		key: 'countDown',
		type: '2',
	}, {
		name: '时间闹钟',
		key: 'time',
		type: '1',
	}, ])
	const typeIndex = ref(0)
	// 小时
	const hour = reactive([])
	// 小时下标
	const hourIndex = ref(0)
	// 分钟
	const minute = reactive([])
	// 分钟下标
	const minuteIndex = ref(0)
	// 闹铃时间
	const alarm = computed(() => {
		let result = uni.$store.state.alarmTime
		if (result) result = util.formatTime('yyyy-MM-dd HH:mm:ss', result)
		return result
	})
	// 获取年月日
	const yMd = ref('')
	// 解决动态设置indicator-style不生效的问题
	const visible = ref(true)

	onMounted(() => {
		// 打开弹窗
		// open()
		const date = new Date()
		// 年月日
		yMd.value = `${date.getFullYear()}-${util.toTwo(date.getMonth() + 1)}-${util.toTwo(date.getDate())}`

		// 初始化
		init()

		util.isLogin().then(() => {
			// 设置
			getAlarm()
		})

		// 
		uni.$on('login', () => {
			// 设置
			getAlarm()
		})

		// 清空
		uni.$on('logout', () => {
			uni.$store.commit('setState', {
				key: 'alarmTime',
				value: '',
			})
		})
	})

	// 获取设置的倒计时
	function getAlarm() {
		api.video.getAlarm().then(rs => {
			if (rs.code == 200) {
				const result = rs.data
				if (!result) return
				const findIndex = typeList.findIndex(item => item.type == result.type)
				if (findIndex != -1) typeIndex.value = findIndex
				// 结束时间
				setTime(result.timestamp)
				return
			}
		})
	}

	/**
	 * 设置闹钟提醒方式
	 * @param {Object} ev 默认事件
	 */
	function handleType(ev) {
		const index = ev.detail.value
		if (typeIndex.value === index) return
		typeIndex.value = index

		// 时间
		if (typeList[index].key == 'time') {
			const date = new Date()
			hourIndex.value = hour.findIndex(node => node == date.getHours())
			minuteIndex.value = minute.findIndex(node => node == date.getMinutes())
		} else if (typeList[index].key == 'countDown') {
			hourIndex.value = 0
			minuteIndex.value = 0
		}
	}

	// 初始化
	function init() {
		// 小时
		for (let i = 0; i < 24; i++) {
			hour.push(i)
		}
		// 分钟
		for (let i = 0; i < 60; i++) {
			minute.push(i)
		}
	}

	// 设置时间
	function setTime(endTime) {
		// 当前时间
		const currentTime = new Date(util.formatTime('yyyy-MM-dd HH:mm:ss')).valueOf()
		// 闹钟时间
		const alarmTime = new Date(endTime).valueOf()
		// 如果闹钟时间小于当前时间
		if (alarmTime < currentTime) return

		// 
		setTimeout(() => {
			util.alert({
				content: '闹钟提醒时间到',
				showCancel: false,
			})

			uni.$store.commit('setState', {
				key: 'alarmTime',
				value: '',
			})
		}, alarmTime - currentTime)

		uni.$store.commit('setState', {
			key: 'alarmTime',
			value: endTime,
		})
	}

	/**
	 * 滑动小时
	 * @param {Object} ev 默认对象
	 */
	function handleHour(ev) {
		const index = ev.detail.value[0]
		if (hourIndex.value === index) return
		hourIndex.value = index
	}

	/**
	 * 滑动分钟
	 * @param {Object} ev 默认对象
	 */
	function handleMinute(ev) {
		const index = ev.detail.value[0]
		if (minuteIndex.value === index) return
		minuteIndex.value = index
	}

	// 打开弹窗
	function open() {
		proxy.$refs.time.open()
	}

	// 关闭弹窗
	function close() {
		proxy.$refs.time.close()
	}

	// 提交
	function handleSubmit() {
		// 当前下标
		const type = typeList[typeIndex.value]

		// 当前时间
		let endTime = yMd.value

		// 如果是倒计时闹钟
		if (type.key == 'countDown') {
			// 如果是当前时间
			if (hourIndex.value === 0 && minuteIndex.value === 0) {
				util.alert('当前时间已到')
				return
			}

			// 
			endTime = util.strtotime(`+${hour[hourIndex.value]} hour`, new Date().getTime())
			endTime = util.strtotime(`+${minute[minuteIndex.value]} minute`, endTime)
			endTime = new Date(endTime).setSeconds(0)
			// endTime = util.formatTime('yyyy-MM-dd HH:mm:ss', endTime)
		} else if (type.key == 'time') {
			// 时间闹钟
			endTime += ` ${util.toTwo(hour[hourIndex.value])}:${util.toTwo(minute[minuteIndex.value])}:00`
			// 当前时间
			const currentTime = new Date(util.formatTime('yyyy-MM-dd HH:mm:ss')).valueOf()
			// 闹钟时间
			endTime = new Date(endTime).valueOf()

			// 如果闹钟时间小于当前时间
			if (endTime < currentTime) {
				util.alert('设置闹钟时间应大于当前时间')
				return
			}
		}

		// 闹钟
		api.video.setAlarm({
			data: {
				// 类型
				type: type.type,
				// 时间
				timestamp: endTime,
			}
		}).then(rs => {
			if (rs.code == 200) {
				util.alert('设置成功')

				// 
				setTime(endTime)
				close()
				return
			}

			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	// 关闭闹钟
	function handleClose() {
		util.alert({
			content: '确定关闭闹钟提醒?',
			success: (rs) => {
				if(!rs.confirm) return
				api.video.delAlarm({}).then(rs => {
					if (rs.code == 200) {
						uni.$store.commit('setState', {
							key: 'alarmTime',
							value: '',
						})
						close()
						return
					}
					util.alert({
						content: rs.msg,
						showCancel: false,
					})
				})
			}
		})
	}

	// 
	defineExpose({
		open,
		close,
	})
</script>

<template>
	<uni-popup ref="time" type="bottom">
		<view class="popBot plr60 bfff">
			<view class="close" @click="$refs.time.close()">
				<uni-icons type="close" size="36rpx" color="#333" />
			</view>

			<!-- 标题 -->
			<view class="title mtb40">
				<picker class="df fdr jcc aic" :range="typeList" @change="handleType" :value="typeIndex"
					range-key="name">
					<text class="tac f40">{{typeList[typeIndex].name}}</text>
					<uni-icons type="right" color="#999" size="32rpx" />
				</picker>
			</view>
			<!-- 副标题 -->
			<view class="">
				<text class="f32">闹钟提醒时间:{{alarm || '未设置'}}</text>
			</view>

			<!-- 操作台 -->
			<view class="oclockBox aic mtb25">
				<view class="oclock">
					<!-- 选择器 -->
					<view class="f1">
						<picker-view v-if="visible" class="select f1" :value="[hourIndex]"
							indicator-class="option active" indicator-style="height: 56rpx;" @change="handleHour">
							<picker-view-column>
								<view v-for="(item,index) in hour" :key="index" class="option fdr aic jcc">
									<text class="text">{{item}}</text>
									<text class="text" v-if="index === hourIndex">时</text>
								</view>
							</picker-view-column>
						</picker-view>
					</view>

					<view class="jcc">
						<text>:</text>
					</view>

					<view class="f1">
						<picker-view v-if="visible" class="select f1" :value="[minuteIndex]"
							indicator-class="option active" indicator-style="height: 56rpx;" @change="handleMinute">
							<picker-view-column>
								<view v-for="(item,index) in minute" :key="index" class="option fdr aic jcc">
									<text class="text">{{item}}</text>
									<text class="text" v-if="index === minuteIndex">分</text>
								</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>

				<!-- 文字提示 -->
				<view class="mt10">
					<text class="c666 f20">预先设置观影时间,到时自动提醒</text>
				</view>

				<view class="btns mtb25">
					<view class="button jcc confirm mtb10" @click="handleSubmit">
						<text class="text">确认</text>
					</view>
					<view class="button jcc cancel mtb10" @click="handleClose" v-if="alarm">
						<text class="text">关闭闹钟</text>
					</view>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<style lang="scss" scoped>
	// 
	.close {
		position: absolute;
		right: 20rpx;
		top: 5rpx;
	}

	// 容器
	.oclock {
		flex-direction: row;
		width: 460rpx;
		height: 210rpx;
		padding: 5rpx;
		box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.3);
		border-radius: 25rpx;

		// 选择器
		.select {

			// 文字
			.text {
				font-size: 48rpx;
				color: #333;
			}
		}
	}

	.btns {
		.button {
			width: 460rpx;
			height: 72rpx;
			border-radius: 10rpx;

			&.confirm {
				background-color: #111;

				.text {
					color: #fff;
				}
			}

			&.cancel {
				background-color: #dcdcdc;

				.text {
					color: #333;
				}
			}

			.text {
				text-align: center;
			}
		}
	}
</style>