<template>
	<view>
		<view class="top">
			<NavigateBar title="身份核验" bgcolor="#a09cc4" control="back"></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 v-if="showcamera" class="camera" device-position="front" flash="off" resolution="low"></camera>
			</view>
			<view class="info">
				<u-text v-if="showcamera" :text="tipsText" align="center"></u-text>
			</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="start" color="#9e97c3"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	export default {
		data() {
			return {
				cameraEngine: null,
				VKSession: null,
				showcamera: false,
				tipsText: "开始身份核验",
				idNumber: '',
				name: '',
				duringCameraAuth: false,
				isVKSupport: 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: '脸部无遮挡'
					}
				]
			};
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['currentHotel', 'checkinInfo']),
		},

		methods: {
			...mapMutations('m_business', ['updateCheckinInfo']),
			start() {
				if (!this.duringCameraAuth && this.isVKSupport) {
					this.getCameraAuth()
				}
			},
			getCameraAuth() {
				console.log('getCameraAuth')
				this.duringCameraAuth = true
				let that = this
				wx.getSetting({
					success: (res) => {
						console.log('getSetting, res : ')
						console.log(res)

						if (!res.authSetting["scope.camera"]) {
							wx.authorize({
								scope: "scope.camera",
								success(res) {
									console.log('authorize success, res : ')
									console.log(res)
									that.showcamera = true
								},
								fail: (res) => {
									console.log('authorize fail, res : ')
									console.log(res)
									wx.showModal({
										title: "提示",
										content: "尚未进行授权，功能将无法使用",
										cancelText: "取消",
										confirmText: "授权",
										success(res) {
											console.log(res);
											if (res.confirm) {
												wx.openSetting({
													//这里的方法是调到一个添加权限的页面，这里可以测试在拒绝授权的情况下设置中是否存在相机选项
													success: (res) => {
														if (!res.authSetting[
																"scope.camera"
															]) {
															this.getCameraAuth()
														} else {
															that.showcamera =
																true
														}
													},
													fail: function() {
														console.log(
															"相机授权设置失败");
													},
												});
											} else if (res.cancel) {
												console.log("用户点击取消");
												wx.showToast({
													title: "您已取消授权",
													icon: "error",
													duration: 1000,
												});
												setTimeout(function() {
													wx.navigateBack();
												}, 1000);
											}
										}
									})
								}
							})
						} else {
							that.showcamera = true
						}
						that.initData()
					}
				})
				this.duringCameraAuth = false
			},
			//visionkit人脸必须函数
			async detectFace(frame) {
				console.log("frame", frame.data);
				this.VKSession.detectFace({
					frameBuffer: frame.data,
					width: frame.width,
					height: frame.height,
					scoreThreshold: 0.8,
					sourceType: 0,
					modelMode: 1,
				});
			},

			//初始化相机引擎
			initData() {
				let that = this;
				console.log('before createCameraContext')
				//使用visionkit
				that.cameraEngine = wx.createCameraContext();
				console.log('before createCameraContext')
				let count = 0;
				//初始化相机
				const listener = that.cameraEngine.onCameraFrame((frame) => {
					count++;
					//每十帧分析一次
					if (count === 10) {
						this.detectFace(frame);

						count = 0;
					}
				});
				//开始监听数据帧
				listener.start();
				//创建VK对象
				that.VKSession = wx.createVKSession({
					version: "v1",
					track: {
						plane: {
							mode: 1,
						},
						face: {
							mode: 2,
						},
					},
				});
				//启动VK对象
				that.VKSession.start((errno) => {
					console.log("VKSession.start errno", errno);
					if (errno) {
						wx.showModal({
							title: "提示",
							content: "网络错误,请退出后重试",
							showCancel: false,
							confirmText: "确定",
							success(res) {
								console.log(res);
								if (res.confirm) {
									wx.navigateBack();
								}
							},
						});
						return
					} else {
						console.log('VKSession start')
						that.VKSession.on("updateAnchors", (anchors) => {
							console.log("anchors", anchors);
							console.log("anchors.length", anchors.length);
							anchors.forEach((anchor) => {
								console.log("anchor.points", anchor.points);
								console.log("anchor.origin", anchor.origin);
								console.log("anchor.size", anchor.size);
								console.log("anchor.angle", anchor.angle);
								console.log("anchor", anchor.confidence);
								if (anchors.length > 1) {
									that.tipsText = "请保证只有一个人";
								} else {
									const {
										pitch,
										roll,
										yaw
									} = anchor.angle;
									const standard = 0.3;

									if (
										Math.abs(pitch) >= standard ||
										Math.abs(roll) >= standard ||
										Math.abs(yaw) >= standard
									) {
										that.tipsText = "请平视摄像头";
									} else if (
										anchor.origin.x < 0.15 ||
										anchor.origin.x > 0.3 ||
										anchor.origin.y < 0.2 ||
										anchor.origin.y > 0.45
									) {
										this.tipsText = "请将人脸对准中心位置";
									} else if (
										anchor.confidence[0] <= 0.8 ||
										anchor.confidence[1] <= 0.8 ||
										anchor.confidence[2] <= 0.8 ||
										anchor.confidence[3] <= 0.8 ||
										anchor.confidence[4] <= 0.8
									) {
										that.tipsText = "请勿遮挡五官";
									} else {
										listener.stop();
										that.tipsText = "即将拍照，请保持！";
										setTimeout(function() {
											that.handleTakePhotoClick();
										}, 1000);
										return;
									}
								}
							});
						});
					}
				});
			},

			// 拍照
			handleTakePhotoClick() {
				this.tipsText = "";
				uni.showLoading({
					title: "正在身份核验，请稍后",
				});
				this.cameraEngine.takePhoto({
					quality: "normal",
					success: ({
						tempImagePath
					}) => {
						let mybase64 = wx
							.getFileSystemManager()
							.readFileSync(tempImagePath, "base64");
						this.afterRead(mybase64);
					},
				});
			},
			//上传
			async afterRead(mybase64) {
				let that = this;
				uni.$http.post("/faceVerification/checkPic", {
						hotelId: that.currentHotel.hotelId,
						faceData: mybase64,
					})
					.then(async (res) => {
						uni.hideLoading();
						console.log("mybase64", mybase64);
						if (res.data.code === 200 && res.data.success === true) {
							if (that.userInfo.skipIdMatching === true) {
								that.showcamera = false
								uni.showModal({
									content: "图片检查通过！",
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											console.log("用户点击确定");
											let guestInfo = {
												name: that.name,
												idNumber: that.idNumber,
												faceData: mybase64
											}
											that.checkinInfo.push(guestInfo)
											that.updateCheckinInfo(that.checkinInfo)
											setTimeout(() => uni.reLaunch({
												url: '/subpkg_checkin/confirmOrder/confirmOrder'
											}), 1000);
										}
									},
								});
							} else {
								uni.showLoading({
									title: "正在身份核验，请稍后",
								});
								let yunjiFaceCheckInfo = {
									idNo: that.idNumber,
									name: that.name,
									image: mybase64,
								};
								let res = await uni.$http.post(
									"/faceVerification/yunjiVerification",
									yunjiFaceCheckInfo
								);
								uni.hideLoading();
								if (res.data.success === true) {
									let guestInfo = {
										name: that.name,
										idNumber: that.idNumber,
										faceData: mybase64
									}
									that.checkinInfo.push(guestInfo)
									that.updateCheckinInfo(that.checkinInfo)
									uni.$showMsg('身份核验通过！')
									setTimeout(() => uni.reLaunch({
										url: '/subpkg_checkin/confirmOrder/confirmOrder'
									}), 1000)
								} else {
									uni.showModal({
										content: "身份核验失败,请重试",
										showCancel: false,
										success: function(res) {
											if (res.confirm) {
												console.log("用户点击确定");
												that.initData();
											}
										},
									});
								}
							}
						} else {
							uni.showModal({
								content: "身份核验失败,请重试",
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log("用户点击确定");
										that.initData();
									}
								},
							});
						}
						console.log("checkPicRes", res);
					});
			},
		},
		onShow() {

		},
		onLoad(options) {
			this.isVKSupport = wx.isVKSupport('v1')
			if (!this.isVKSupport) {
				uni.showModal({
					content: '微信版本过低，请升级至最新版本',
					showCancel: false,
					success() {
						uni.navigateBack()
					},
				})
			} else {
				this.name = options.name
				this.idNumber = options.idNumber
			}
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage(info) {
			return {
				title: '源享住',
				path: 'pages/login/login',
				imageUrl: "/static/logo.png"
			}
		}
		// #endif
	};
</script>

<style lang="scss">
	page {
		background-color: #EFEFF4;

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

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

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

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

			.face-area--line {
				margin-left: 40rpx;
				margin-bottom: 20rpx;
				width: 30rpx;
				border-bottom: solid 6rpx #9e97c3;
			}

			.camera-container {
				width: 80%;
				height: 80vw;
				margin: 0 auto;
				margin-bottom: 30rpx;

				.camera {
					width: 100%;
					height: 80vw;
					margin: 0 auto;
					margin-bottom: 30rpx;
					border: 2rpx solid black;
					border-radius: 50%;
					// box-sizing: border-box;
				}
			}

		}

		.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;
				margin-bottom: 20rpx;
				width: 30rpx;
				border-bottom: solid 6rpx #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;
		}
	}

	.content {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;

		.camera-box {
			position: relative;
			width: 100%;
			height: 100%;
		}

		.camera-bg-box {
			position: relative;
			width: 100%;
			height: 100%;
			overflow: hidden;

			&::after {
				content: "";
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%) translateY(-50%);
				border-radius: 100%;
				width: 600rpx;
				height: 600rpx;
				border: 1000rpx solid rgba(255, 255, 255, 0.998);
			}
		}

		.camera {
			width: 100%;
			height: 100%;
			border-top: 200rpx solid black;
			border-bottom: 200rpx solid black;
			box-sizing: border-box;
		}

		.camera-tip {
			position: absolute;
			bottom: 220rpx;
			left: 50%;
			color: rgb(0, 0, 0);
			transform: translateX(-50%);
			// .text-40-fff-600();
		}
	}
</style>