<template>
	<view>
		<view class="have-reservation" v-if="showCheckinInfo">
			<view class="info">
				<view class="title">
					<view class="hotel-name">
						<!-- <u-text :text="hotelStore.hotel.name" bold color="#333333" size="30rpx"></u-text> -->
						<text>{{hotelStore.hotel.name}}</text>
					</view>
					<view class="tips">
						<!-- <u-text text="入住信息" color="#666666" size="24rpx"></u-text> -->
						<text>入住信息</text>
					</view>
				</view>
				<view class="checkin-info">
					<view class="checkin-info--item">
						<view class="checkin-info--item--text">
							<!-- <u-text text="所在楼层: " color="#999999" size="26rpx"></u-text> -->
							<text>所在楼层：</text>
						</view>
						<view class="checkin-info--item--text">
							<!-- <u-text :text="checkinInfo.floor + '楼'" color="#999999" size="26rpx"></u-text> -->
							<text>{{`${checkinInfo.floor}楼`}}</text>
						</view>
					</view>
					<view class="checkin-info--item">
						<view class="checkin-info--item--text">
							<!-- <u-text text="房间信息 : " color="#999999" size="26rpx"></u-text> -->
							<text>房间信息：</text>
						</view>
						<view class="checkin-info--item--text">
							<!-- <u-text :text="checkinInfo.room" color="#999999" size="26rpx"></u-text> -->
							<text>{{checkinInfo.room}}</text>
						</view>
					</view>
					<view class="checkin-info--item">
						<view class="checkin-info--item--text">
							<!-- <u-text text="起始时间 : " color="#999999" size="26rpx"></u-text> -->
							<text>起始时间：</text>
						</view>
						<view class="checkin-info--item--text">
							<!-- <u-text :text="formatDateTime(checkinInfo.startTime)" color="#999999" size="26rpx"></u-text> -->
							<text>{{formatDateTime(checkinInfo.startTime)}}</text>
						</view>
					</view>
					<view class="checkin-info--item">
						<view class="checkin-info--item--text">
							<!-- <u-text text="结束时间 : " color="#999999" size="26rpx"></u-text> -->
							<text>结束时间：</text>
						</view>
						<view class="checkin-info--item--text">
							<!-- <u-text :text="formatDateTime(checkinInfo.endTime)" color="#999999" size="26rpx"></u-text> -->
							<text>{{formatDateTime(checkinInfo.endTime)}}</text>
						</view>
					</view>
				</view>
			</view>

			<view class="qrcode" :style="{width: qrCodeWidth, height: qrCodeWidth, display: showQrCode ? '' : 'none'}">
				<img style="width: 100%; height: 100%;" :src="qrCodeDataUrl" />
			</view>

			<view class="prompt" :style="{width: diaplayWidth}">
				<view class="prompt--text" v-if="showPrompt">
					<text>
						请将梯控二维码正对扫描框进行梯控识别
					</text>
					<text style="margin-top: 10rpx;">
						{{ `该二维码将在${waitTime}分钟后失效` }}
					</text>
				</view>
				<view v-if="!showPrompt">
					<button class="prompt--count-down__button" @click="rerenderQrCode">二维码失效，点击重新生成二维码</button>
				</view>
			</view>
			<view class="mobile-elevator">
				<button :loading="buttonLoading" @click="mobileElevator">
					手机乘梯
				</button>
			</view>

		</view>

		<view v-else class="not-checkin">
			<view class="not-checkin-text">
				<text>您还未入住！</text>
			</view>
			<view class="not-checkin-text">
				<text>若已退房或房间到期,请至前台办理</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from "vue";
	import {
		getCheckinInfo,
		getElevatorQRCode,
		moveElevator
	} from "../../utils/api"
	import {
		useHotelStore
	} from '@/store/hotelStore.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import moment from "moment";
	import {
		useUserStore
	} from "../../store/userStore";
	import {
		IMG_BASE_URL
	} from "../../config";
	import {
		QRCodeSVG
	} from "../../utils/qrCode/qrcode.mjs"

	const hotelStore = useHotelStore()
	const userStore = useUserStore()
	const showCheckinInfo = ref(false)
	const checkinInfo = ref(null)
	const diaplayWidth = ref("")
	const qrCodeWidth = ref("")
	const qrCodeData = ref("")
	const qrCode = ref("")
	const showQrCode = ref(false)
	const waitTime = ref(10)
	const showPrompt = ref(false)
	const logoBase64 = ref("")
	const buttonLoading = ref(false)

	const timeCountDown = () => {
		const intervalId = setInterval(() => {
			waitTime.value--
			if (waitTime.value === 0) {
				showPrompt.value = false
				showQrCode.value = false
				clearInterval(intervalId)
			}
		}, 60000)
	}

	const qrCodeDataUrl = computed(() => {
		if (qrCodeData.value !== "" && logoBase64.value !== "") {
			const qrSvg = new QRCodeSVG(
				qrCodeData.value, {
					level: "H",
					image: {
						source: logoBase64.value,
						width: '25%',
						height: '25%',
						x: 'center',
						y: 'center',
						border: 1
					}
				}
			)
			qrCode.value = qrSvg.toString()
			const encoded = encodeURIComponent(qrCode.value)
				.replace(/'/g, '%27')
				.replace(/"/g, '%22')
			const header = 'data:image/svg+xml,'
			const dataUrl = header + encoded

			showQrCode.value = true
			showPrompt.value = true
			timeCountDown()
			return dataUrl
		}
	})

	const rerenderQrCode = async () => {
		const qrCodeMsg = await getElevatorQRCode({
			hotelId: hotelStore.hotel.hotelId,
			building: 1,
			floor: checkinInfo.value.floor,
			customerId: userStore.userInfo.idNumber,
			customerType: 1,
			status: 1,
			activeTime: moment().add(10, "m")
		})
		console.log("获取梯控二维码信息", qrCodeMsg);

		if (!qrCodeMsg.data || !qrCodeMsg.success) {
			return
		}

		qrCodeData.value = qrCodeMsg.data.data

		const qrSvg = new QRCodeSVG(
			qrCodeData.value, {
				level: "H",
				image: {
					source: logoBase64.value,
					width: '25%',
					height: '25%',
					x: 'center',
					y: 'center',
					border: 1
				}
			}
		)
		qrCode.value = qrSvg.toString()
		showQrCode.value = true
		showPrompt.value = true
		waitTime.value = 10
		timeCountDown()
	}

	const mobileElevator = async () => {
		const scan = await uni.scanCode({
			scanType: ['qrCode']
		})
		// console.log("二维码扫描结果", scan);
		const deviceSn = scan.result

		buttonLoading.value = true
		uni.showLoading({
			title: '联系电梯中...',
			mask: true
		})
		// const eleRes = await moveElevator(deviceSn, checkinInfo.floor)
		const eleRes = await moveElevator(deviceSn, 7)
		console.log("乘梯结果", eleRes);
		if (!eleRes.data || !eleRes.success) {
			uni.hideLoading()
			buttonLoading.value = false
			uni.showModal({
				content: '操控电梯失败，请稍后重试。',
				showCancel: true,
			})
			return
		}

		uni.hideLoading()
		buttonLoading.value = false
		uni.showModal({
			content: '操控电梯成功。',
			showCancel: true,
		})

	}

	onLoad(async (options) => {
		console.log("onLoad", options);
		try {
			const infoRes = await getCheckinInfo(hotelStore.hotel.hotelId)
			// console.log("获取入住记录结果", infoRes);
			if (!infoRes.data || !infoRes.success) {
				return
			}
			checkinInfo.value = infoRes.data
			showCheckinInfo.value = true

			const systemIfo = await uni.getSystemInfo()
			console.log("系统信息：", systemIfo);
			diaplayWidth.value = (systemIfo.screenWidth - 40).toFixed() + "px"
			qrCodeWidth.value = (systemIfo.screenWidth * 3 / 5).toFixed() + "px"
		} catch (err) {
			console.log("获取入住记录异常", err);
			return
		}

		try {
			const qrCodeMsg = await getElevatorQRCode({
				hotelId: hotelStore.hotel.hotelId,
				building: 1,
				floor: checkinInfo.value.floor,
				customerId: userStore.userInfo.idNumber,
				customerType: 1,
				status: 1,
				activeTime: moment().add(10, "m")
			})
			console.log("获取梯控二维码信息", qrCodeMsg);

			if (!qrCodeMsg.data || !qrCodeMsg.success) {
				return
			}

			qrCodeData.value = qrCodeMsg.data.data
		} catch (err) {
			console.log("获取梯控二维码信息异常", err);
			return
		}

		const pic = await uni.request({
			url: `${IMG_BASE_URL}/yun_xiang_zhu_square.png`,
			responseType: 'arraybuffer',
		})
		// console.log("云享住logo", pic.data);
		logoBase64.value = "data:image/png;base64," + uni.arrayBufferToBase64(pic.data);
		// console.log("字符串",uni.arrayBufferToBase64(pic.data));
	})

	const formatDateTime = (dateTime) => {
		return moment(dateTime).format("YYYY年MM月DD日HH时mm分")
	}
</script>

<style lang="scss">
	.have-reservation {

		.info {
			background: #F5F8FE;
			box-shadow: -6px 17px 21px 0px rgba(112, 152, 246, 0.14);
			margin-bottom: 80rpx;

			.title {
				display: flex;
				justify-content: space-between;
				padding: 0 40rpx;
				line-height: 80rpx;
				border-bottom: 2rpx solid #E0E8FB;
			}

			.checkin-info {
				margin: 20rpx auto;

				.checkin-info--item {
					display: flex;
					margin: 0 40rpx;

					.checkin-info--item--text {
						margin: 10rpx;
						margin-left: 0;
					}

					&:last-child {
						padding-bottom: 20rpx;
					}
				}
			}
		}

		.qrcode {
			display: flex;
			margin: 10rpx auto;
			padding: 10rpx 20rpx;
			background: #ffffff;
			border-radius: 10rpx;
		}

		.prompt {
			margin: 0 auto;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.prompt--text {
				background-color: #fff;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin: 0 20rpx;
				padding: 10rpx 20rpx;
				border-radius: 10rpx;
			}

			.prompt--count-down__button {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 40rpx;
			}
		}

		.mobile-elevator {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin: 0 20rpx;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
		}
	}

	.not-checkin {
		margin-top: 40vh;

		.not-checkin-text {
			display: flex;
			justify-content: center;
		}
	}
</style>