<template>
	<view>
		<view class="top">
			<NavigateBar title="身份核验" bgcolor="#a09cc4"></NavigateBar>
		</view>
		<view class="face-area">
			<view class="face-area--tips">
				<view class="face-area--tips--title">
					<u-text text="身份核验" color="#333333" bold size="34rpx"></u-text>
				</view>
				<view class="face-area--tips--context">
					<u-text text="请根据页面提示进行操作" color="#CBCBCB" size="28rpx"></u-text>
				</view>
			</view>
			<view class="face-area--line"></view>
			<view class="camera-container">
				<camera id="check-pic--cam__cam" flash="off" device-position="front" @ready="cameraContext" 
				:style="[cameraStyle]"/>
				<cover-image src="../../static/cover.png" :style="[coverImageStyle]"></cover-image>
			</view>
			<view v-if="!showTips" class="check-pic-result">
				{{ result }}
			</view>
		</view>

		<view class="precautions">
			<view class="precautions--tips">
				<view class="precautions--tips--title">
					<u-text text="注意事项" color="#333333" bold size="34rpx"></u-text>
				</view>
				<view class="precautions--tips--context">
					<u-text text="请遵守需注意事项" color="#CBCBCB" size="28rpx"></u-text>
				</view>
			</view>
			<view class="precautions--line"></view>
			<view class="precautions--context">
				<u-text :text="'确认'+name+'本人操作；保持正脸在取景框中根据屏幕指示完成'" color="#666666" size="24rpx"></u-text>
			</view>
			<view class="img-list">
				<view class="img-list--item" v-for="img in imgList">
					<view class="img">
						<u-image :src="img.src" :height="img.height" :width="img.width"></u-image>
					</view>
					<view class="tips">
						<u-text :text="img.tips" color="#666666" size="20rpx"></u-text>
					</view>
				</view>
			</view>
		</view>

		<view class="btn">
			<u-button text="同意并开始验证" @click="takePhoto" :disabled="isCheckingFace" color="#9e97c3"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import NavigateBar from "../../components/navigateBar/navigate-bar.vue";
	export default {
		components: {
			NavigateBar
		},
		data() {
			return {
				name: '',
				idNumber: '',
				camContext: null,
				result: "身份核验中....",
				photoBase64: null,
				fs: null,
				checkFaceRes: false,
				showTips: true,
				isCheckingFace: false,
				imgList: [{
						src: '/static/check-face-phone.png',
						width: '48rpx',
						height: '70rpx',
						tips: '正对手机'
					},
					{
						src: '/static/check-face-light.png',
						width: '78rpx',
						height: '70rpx',
						tips: '光线充足'
					},
					{
						src: '/static/check-face-face.png',
						width: '80rpx',
						height: '80rpx',
						tips: '脸部无遮挡'
					}
				],
				faceAreaTipsHeight: 0,
				faceAreaLineHeight: 0,
				menuButtonTop: 0,
				menuButtonHeight: 0,
				menuButtonBottom: 0,
				width: 0,
				phone: ""
			}
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['currentHotel', 'checkinInfo']),
			cameraStyle() {
				let style = {}
				// 设置相机显示区域左右边框距屏幕左右边框为20px
				let camWidth = this.width === 0 ? 0 : this.width - 20 * 2
				style.width = camWidth + 'px'
				style.height = camWidth + 'px'
				return style
			},
			coverImageStyle() {
				let style = {}
				// 设置相机遮罩图片的左右边框距屏幕左右边框为16px
				let imgWidth = this.width === 0 ? 0 : this.width - 16 * 2
				style.width = imgWidth + 'px'
				style.height = imgWidth + 'px'
				style.left = "16px"
				let top = 0
				if (this.faceAreaTipsHeight && this.faceAreaLineHeight && this.menuButtonTop
					&& this.menuButtonHeight && this.menuButtonBottom
				) {
					top = this.faceAreaTipsHeight + this.faceAreaLineHeight + this.menuButtonTop
					+ this.menuButtonHeight + this.menuButtonBottom + 2
					// console.log("顶部距离", top);
				}
				// console.log("computed");
				style.top = top + "px"
				return style
			}
		},
		methods: {
			...mapMutations('m_business', ['updateCheckinInfo']),
			async cameraContext() {
				this.camContext = my.createCameraContext('check-pic--cam__cam');
			},
			async takePhoto() {
				const userSetting = await uni.getSetting()
				// console.log("userSetting", userSetting);
				let camAuth = userSetting[1].authSetting['camera'] ? userSetting[1].authSetting['camera'] : false
				while (!camAuth) {
					await new Promise(async (resolve, reject) => {
						await uni.showModal({
							title: "温馨提示",
							content: "身份核验功能需要使用您的相机，请授权后重新点击核验。",
							success: async (res) => {
								if (res.confirm) {
									await uni.openSetting().then(res => {
										console.log("openSetting", res);
										camAuth = res[1].authSetting['camera'] ? res[1]
											.authSetting['camera'] : false
										resolve()
									})
								}
							}
						})
					})
					setTimeout(() => {}, 200)
				}
				// console.log("进行了相机授权操作");
				this.result = "身份核验中...."
				this.showTips = false
				this.isCheckingFace = true

				// console.log("this.camContext",this.camContext);
				while (!this.checkFaceRes) {
					// console.log("开始takePhoto进行人脸检测");

					let photo = await this.camContext.takePhoto({
						quality: 'normal',
					})
					// console.log("完成takePhoto", this.photo.tempImagePath);
					this.photoBase64 = await this.fs.readFile({
						filePath: photo.tempImagePath,
						encoding: "base64"
					})
					// console.log("photoBase64", photoBase64);

					let checkPicRes = await uni.$http.post("/faceVerification/checkPic", {
						hotelId: this.currentHotel.hotelId,
						faceData: this.photoBase64.data,
					})
					// console.log("checkPicRes", checkPicRes);
					if (!checkPicRes.data.success) {
						// console.log("checkPicRes.data", checkPicRes.data.msg.split("原因：")[1]);
						this.result = checkPicRes.data.msg.split("原因：")[1] + "请将面部完整放入拍摄区域。"
					} else {
						this.checkFaceRes = checkPicRes.data.success
					}
					setTimeout(() => {}, 100)
				}
				// 进行云极人证比对
				await this.afterSuccessCheckPic()
			},
			async afterSuccessCheckPic() {
				if (this.userInfo.skipIdMatching === true) {
					this.result = "身份核验成功，将跳转确认订单页面"
					let guestInfo={
						name:this.name,
						idNumber:this.idNumber,
						faceData: this.photoBase64.data,
						phone: this.phone,
					}
					this.checkinInfo.push(guestInfo)
					this.updateCheckinInfo(this.checkinInfo)
					setTimeout(() => {
						uni.reLaunch({
							url: '/subpkg_checkin/confirmOrder/confirmOrder'
						})
					}, 500)
				} else {
					let yunjiFaceCheckInfo = {
						idNo: this.idNumber,
						name: this.name,
						image: this.photoBase64.data,
					}
					uni.showLoading({
						title: "正在身份核验，请稍后",
					});
					let res = await uni.$http.post(
						"/faceVerification/yunjiVerification",
						yunjiFaceCheckInfo
					);
					if (res.data.success === true) {
						uni.hideLoading();
						this.result = "身份核验成功，将跳转确认订单页面"
						this.checkinInfo.push({
							name:this.name,
							idNumber:this.idNumber,
							faceData: this.photoBase64.data,
							phone: this.phone,
						})
						this.updateCheckinInfo(this.checkinInfo)
						setTimeout(() => {
							this.isCheckingFace = false
							uni.reLaunch({
								url: '/subpkg_checkin/confirmOrder/confirmOrder'
							})
						}, 500)
					} else {
						uni.hideLoading();
						this.isCheckingFace = false
						this.result = "身份核验失败，请重新进行"
					}
				}
			}
		},
		async onLoad(options) {
			this.name=options.name
			this.idNumber=options.idNumber
			this.phone = options.phone

			this.fs = my.getFileSystemManager();

			let alipaySystemInfo = await uni.getSystemInfo()
			this.width = alipaySystemInfo[1].screen.width
			const menuButton = uni.getMenuButtonBoundingClientRect()
			this.menuButtonTop = menuButton.top
			this.menuButtonHeight = menuButton.height
			this.menuButtonBottom = 8
		},
		onShow() {
			this.result = "身份核验中...."
			this.showTips = true
			this.isCheckingFace = false
		},
		async beforeMount() {
			let faceAreaTipsSize = await uni.$u.getRect('.face-area--tips')
			// console.log("faceAreaTipsSize", faceAreaTipsSize);
			this.faceAreaTipsHeight = faceAreaTipsSize.height
			let faceAreaLineSize = await uni.$u.getRect('.face-area--line')
			this.faceAreaLineHeight = faceAreaLineSize.height
			// console.log("faceAreaLineSize", faceAreaLineSize);
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #EFEFF4;
		.top {
			position: sticky;
			background-color: #fff;
			width: 100%;
			top: 0;
			z-index: 999;
		}

		.face-area {
			display: flex;
			flex-direction: column;
			background-color: #FFFFFF;
			border-radius: 50rpx;
			overflow: hidden;

			.face-area--tips {
				display: flex;
				padding: 10rpx 20rpx;
				height: 60rpx;
				align-items: flex-end;

				.face-area--tips--title {
					margin: 10rpx;
				}

				.face-area--tips--context {
					margin: 10rpx;
				}
			}

			.face-area--line {
				margin-left: 40rpx;
				width: 30rpx;
				height: 6rpx;
				margin-bottom: 4rpx;
				background-color: #9e97c3;
			}

			.camera-container {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				padding-bottom: 30rpx;

				cover-image {
					margin: 0;
					padding: 0;
					position: absolute;
				}
			}

			.check-pic-result {
				width: 100%;
				padding: 10rpx 20rpx;
				display: flex;
				justify-content: center;
				box-sizing: border-box;
				color: red;
			}
		}

		.precautions {
			overflow: hidden;

			.precautions--tips {
				display: flex;
				padding: 10rpx 20rpx;
				align-items: flex-end;

				.precautions--tips--title {
					margin: 10rpx;
				}

				.precautions--tips--context {
					margin: 10rpx;
				}
			}

			.precautions--line {
				margin-left: 40rpx;
				width: 30rpx;
				height: 6rpx;
				margin-bottom: 4rpx;
				background-color: #9e97c3;
			}

			.precautions--context {
				margin: 0 20rpx;
				margin-bottom: 20rpx;
			}

			.img-list {
				display: flex;
				justify-content: space-around;

				.img-list--item {
					display: flex;
					flex-direction: column;
					align-items: center;
					width: 20%;

					.img {
						display: flex;
						flex-direction: row;
						border-radius: 20rpx;
						background-color: #dcdce9;
						width: 100%;
						height: 140rpx;
						justify-content: center;
						align-items: center;
					}
				}
			}
		}

		.btn {
			margin: 20rpx;
		}
	}
</style>