<template>
	<view class="container">
		<view>
			<!-- #ifdef MP-WEIXIN -->
			<NavigateBar :title="pageTitle" control="back" bgcolor="#a09cc4"></NavigateBar>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<NavigateBar :title="pageTitle" bgcolor="#a09cc4"></NavigateBar>
			<!-- #endif -->
		</view>

		<view class="step-zero" v-if="step===0">
			<view class="tips">
				<u-text align="center" color="#333333" text="根据《治安管理处罚法》要求所有入住宾客和访客必须一人一证实名登记"></u-text>
			</view>
			<u-form labelPosition="left" labelWidth="180rpx">
				<u-form-item label="姓名" prop="name">
					<u-input v-model="name" border="none" clearable fontSize="36rpx"></u-input>
				</u-form-item>
				<u-form-item label="手机号" prop="phone">
					<u-input v-model="phone" border="none" clearable fontSize="36rpx" type="number"></u-input>
				</u-form-item>
				<u-form-item label="身份证" prop="idNumber">
					<u-input v-model="idNumber" border="none" clearable fontSize="36rpx"></u-input>
				</u-form-item>
			</u-form>
			<view class="btn-container">
				<u-button text="立即认证" color="#9e97c3" @click="finishInput"></u-button>
			</view>
		</view>

		<view class="step-one" v-else-if="step===1">
			<view class="upload-container">
				<u-upload @afterRead="afterIdCardRead" name="Front" :maxCount="1" :maxSize="1024*1024*1.5"
					@oversize="oversize">
					<image :src="idCardFrontPicPath" mode="aspectFit"></image>
				</u-upload>
			</view>
			<view class="upload-container">
				<u-upload @afterRead="afterIdCardRead" name="Back" :maxCount="1" :maxSize="1024*1024*1.5"
					@oversize="oversize">
					<image :src="idCardBackPicPath" mode="aspectFit"></image>
				</u-upload>
			</view>
			<view class="btn-container">
				<u-button :disabled="!getAllInfo" text="完成上传" color="#9e97c3" @click="finishIdCardUpload"></u-button>
			</view>
		</view>

		<view class="step-two" v-else-if="step===2">
			<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" :key="img.src">
						<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-container">
				<u-button text="同意并开始验证" @click="start" color="#9e97c3"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		IMG_BASE_URL,
		BASE_URL,
	} from '../../config.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import NavigateBar from '../../components/navigateBar/navigate-bar.vue';
	import moment from 'moment/moment.js';
	export default {
		components: {
			NavigateBar
		},
		data() {
			return {
				isMainCustomer: false,
				//0展示输入姓名、身份证号、手机号页面
				//1展示上传身份证照片页面
				//2展示身份核验页面
				step: 0,
				//步骤 0 需要填入的信息
				name: '',
				idNumber: '',
				phone: '',
				//步骤 1 需要从身份证获取的信息
				idCardInfoInPage: {
					name: '',
					sex: '',
					nation: '',
					birth: '',
					address: '',
					idNumber: '',
					issuingAuthority: '',
					issuingDate: '',
					expiryDate: ''
				},
				idCardFrontPicPath: '../../static/idcard_upload_front.png',
				idCardBackPicPath: '../../static/idcard_upload_back.png',
				infoList: ['address', 'nation', 'sex', 'birth', 'issuingAuthority', 'issuingDate', 'expiryDate'],
				userInfoId: 0,
				// #ifdef MP-WEIXIN
				idCardDirection: '',
				// img: null,
				// imgData: null,
				idCardVKSession: null,
				idCardFrontUploadInfo: {
					imgUrl: '',
					imgWidth: 0,
					imgHeight: 0,
					imgOriginWidth: 0,
					imgOriginHeight: 0,
				},
				idCardFrontDetectInfo: {
					detected: false, //检测是否完成
					detectSuccess: false, //检测是否成功
					isComplete: false, //身份证是否完整
					label: '', //身份证方向，0 人像面，1 国徽面
					orientation: 0, //身份证朝向 （0 朝上 1 朝下 2 朝下 3 朝左）
					box: [], //身份证坐标框点数组 （0 左上点 1 右上点 2 右下点 3 左下点）
				},
				idCardBackUploadInfo: {
					imgUrl: '',
					imgWidth: 0,
					imgHeight: 0,
					imgOriginWidth: 0,
					imgOriginHeight: 0,
				},
				idCardBackDetectInfo: {
					detected: false,
					detectSuccess: false,
					isComplete: false,
					label: '',
					orientation: 0,
					box: [],
				},
				// showAddGuest: true,
				cameraEngine: null,
				VKSession: null,
				showcamera: false,
				tipsText: '开始身份核验',
				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: '脸部无遮挡'
					}
				],
				pageTitle: '身份信息录入'
				// #endif
			};
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['checkinInfo', 'currentHotel', 'idCardInfo']),
			getAllInfo() {
				let getAll = true
				for (const info of this.infoList) {
					if (!this.idCardInfoInPage[info]) {
						getAll = false
						break
					}
				}
				return getAll
			}
		},
		methods: {
			...mapMutations('m_business', ['updateCheckinInfo', 'updateIdCardInfo']),
			...mapMutations('m_user', ['updateUserInfo']),
			async finishInput() {
				//检查格式是否正确
				let nameReg = /\d/
				if (this.name === '' || nameReg.test(this.name)) {
					uni.$showMsg('姓名格式错误！')
					return
				}
				let idNumberReg =
					/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
				if (!idNumberReg.test(this.idNumber)) {
					uni.$showMsg('身份证号格式错误！')
					return
				}
				let phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
				if (!phoneReg.test(this.phone)) {
					uni.$showMsg('手机号格式错误！')
					return
				}
				//检查该顾客是否在当前酒店入住
				let res = await uni.$http.post('/checkinInfo/queryByCondition', {
					userIdNumber: this.idNumber,
					status: 1,
					hotelId: this.currentHotel.hotelId,
					pageNo: 1,
					pageSize: 1
				});
				if (res.data.code == 200 && res.data.data.records.length > 0) {
					uni.$showMsg('该顾客已入住！')
					return
				}

				let pages = getCurrentPages()
				let beforePage = pages[pages.length - 2]

				//判断此顾客信息是否已添加
				if (JSON.stringify(this.checkinInfo) !== '{}' && this.checkinInfo.length > 0) {
					for (let info of this.checkinInfo) {
						if (info.idNumber === this.idNumber) {
							uni.$showMsg('已添加此顾客，请检查填写信息')
							return
						}
					}
				}

				//判断本地缓存是否有顾客身份证信息，有则跳转step 2
				for (const info of this.idCardInfo) {
					if (info.idNumber === this.idNumber && info.name === this.name) {
						this.idCardInfoInPage = info
						this.step = 2
						return
					}
				}

				//本地缓存没有顾客身份信息，到后台查询
				let idCardInfoQueryRes = await uni.$http.post('/idCardInfo/queryByCondition', {
					pageNo: 1,
					pageSize: 1,
					idNumber: this.idNumber,
					name: this.name
				})

				//查询到，写入local storage，跳转step 2
				if (idCardInfoQueryRes.data.data.records.length === 1) {
					let info = idCardInfoQueryRes.data.data.records[0]
					info.birth = info.birthday
					let keys = Object.keys(this.idCardInfoInPage)
					for (const key of keys) {
						//有数据为空则需重新上传
						if (!info[key]) {
							this.step = 1
							return
						}
						this.idCardInfoInPage[key] = info[key]
					}
					let idCardInfoToUpdate = this.idCardInfo
					idCardInfoToUpdate.push(this.idCardInfoInPage)
					this.updateIdCardInfo(idCardInfoToUpdate)
					this.step = 2
					return
				}

				//没查询到，跳转step 1
				this.step = 1
			},
			initIdCardVKSession() {
				this.idCardVKSession = wx.createVKSession({
					track: {
						IDCard: {
							mode: 2 // 照片模式
						}
					},
					version: 'v1',
					gl: this.gl
				})
				// VKSession start
				this.idCardVKSession.start(err => {

					this.idCardVKSession.on('updateAnchors', anchors => {
						// console.log('updateAnchors')

						// 处理返回的身份证信息
						if (anchors && anchors[0]) {
							// 存在数组，证明存在身份证信息
							const anchor = anchors[0];

							// console.log(anchor.isComplete, anchor.label, anchor.orientation, anchor.box);

							let info = {
								detected: true,
								detectSuccess: true,
								isComplete: anchor.isComplete,
								label: anchor.label,
								orientation: anchor.orientation,
								box: anchor.box,
							}
							this['idCard' + this.idCardDirection + 'DetectInfo'] = info

							// 裁剪信息
							const affineImgWidth = anchor.affineImgWidth;
							const affineImgHeight = anchor.affineImgHeight;
							const affineMat = anchor.affineMat;

							// 存在裁剪信息，进行身份证裁剪处理
							if (affineImgWidth && affineImgHeight && affineMat) {

								// console.log(affineImgWidth, affineImgHeight, affineMat);

								const cropIDcardImg = this.getCropIDcard(affineImgWidth, affineImgHeight,
									affineMat);
								// console.log(cropIDcardImg)
							}
						}

					})
					this.idCardVKSession.on('removeAnchors', anchors => {
						// console.log("anchor remove")

						// 图片没有识别到身份证
						this['idCard' + this.idCardDirection + 'DetectInfo'].detected = true
						this['idCard' + this.idCardDirection + 'DetectInfo'].detectSuccess = false
					})

				});
			},
			async setImageUploadInfo(url) {
				const fixWidth = 300
				let imageInfo = await uni.getImageInfo({
					src: url
					// ,
					// success: (image) => {
					// 	console.log(image)
					// 	let height = image.height
					// 	let width = image.width
					// 	let info = {
					// 		imgUrl: url,
					// 		imgWidth: fixWidth,
					// 		imgHeight: (fixWidth / width) * height,
					// 		imgOriginWidth: width,
					// 		imgOriginHeight: height
					// 	}
					// 	this['idCard' + this.idCardDirection + 'UploadInfo'] = info
					// }
				})
				let height = imageInfo[1].height
				let width = imageInfo[1].width
				let uploadInfo = {
					imgUrl: url,
					imgWidth: fixWidth,
					imgHeight: (fixWidth / width) * height,
					imgOriginWidth: width,
					imgOriginHeight: height
				}
				this['idCard' + this.idCardDirection + 'UploadInfo'] = uploadInfo
			},
			getCropIDcard(affineImgWidth, affineImgHeight, affineMat) {
				// console.log('start getCropIDcard')
				let infoName = 'idCard' + this.idCardDirection + 'UploadInfo'
				const canvas = wx.createOffscreenCanvas({
					type: '2d',
					width: affineImgWidth,
					height: affineImgHeight,
				})
				const context = canvas.getContext('2d')

				context.clearRect(0, 0, affineImgWidth, affineImgHeight);
				/*
				 * affineMat 3x3仿射变换矩阵，行主序
				 *  [0 1 2
				 *   3 4 5
				 *   6 7 8]
				 */
				/*
				 * canvas 2d setTransform
				 * setTransform(a, b, c, d, e, f)
				 *  [a c e
				 *   b d f
				 *   0 0 1]
				 */
				context.setTransform(
					Number(affineMat[0]), Number(affineMat[3]), Number(affineMat[1]),
					Number(affineMat[4]), Number(affineMat[2]), Number(affineMat[5])
				);
				// console.log(this.img, this[infoName].imgOriginWidth, this[infoName].imgOriginHeight)
				context.drawImage(this.img, 0, 0, this[infoName].imgOriginWidth, this[infoName].imgOriginHeight)
				const imgUrl = canvas.toDataURL()
				this[infoName].imgUrl = imgUrl
				this['idCard' + this.idCardDirection + 'PicPath'] = imgUrl
				return imgUrl;
			},
			async detectIdCard() {
				let infoName = 'idCard' + this.idCardDirection + 'UploadInfo'
				if (this[infoName].imgUrl) {
					const canvas = wx.createOffscreenCanvas({
						type: '2d',
						width: this[infoName].imgOriginWidth,
						height: this[infoName].imgOriginHeight,
					})
					const context = canvas.getContext('2d')
					const img = canvas.createImage()
					// 使用中的 图片对象
					this.img = img;
					await new Promise(resolve => {
						img.onload = resolve
						img.src = this[infoName].imgUrl
					})

					context.clearRect(0, 0, this[infoName].imgOriginWidth, this[infoName].imgOriginHeight)
					context.drawImage(img, 0, 0, this[infoName].imgOriginWidth, this[infoName].imgOriginHeight)

					// 使用中的 image ArrayBuffer
					this.imgData = context.getImageData(0, 0, this[infoName].imgOriginWidth, this[infoName]
						.imgOriginHeight)

					// console.log('[frameBuffer] --> ', this.imgData.data.buffer)
					// console.log('this.session.detectIDCard', this.idCardVKSession.detectIDCard)
					// console.log('width', this[infoName].imgOriginWidth)
					// console.log('height', this[infoName].imgOriginHeight)
					this.idCardVKSession.detectIDCard({
						// 识别身份证图片的信息
						frameBuffer: this.imgData.data.buffer,
						width: this[infoName].imgOriginWidth,
						height: this[infoName].imgOriginHeight,
						// 是否获取裁剪图片信息
						getAffineImg: true,
					})
				}
			},
			async afterIdCardRead(event) {
				console.log(event)
				//正面还是反面
				this.idCardDirection = event.name
				await this.setImageUploadInfo(event.file.url)
				await this.detectIdCard()
				let detectInfo = this['idCard' + this.idCardDirection + 'DetectInfo']
				//图片中不包含身份证
				if (!detectInfo.detectSuccess) {
					uni.showModal({
						title: '图片中不包含身份证，请重新上传',
						showCancel: false
					})
					return
				}
				if (!detectInfo.isComplete) {
					uni.showModal({
						title: '身份证照片不完整，请重新上传',
						showCancel: false
					})
					return
				}
				if ((this.idCardDirection === 'Front' && detectInfo.label !== 0) ||
					(this.idCardDirection === 'Back' && detectInfo.label !== 1)) {
					uni.showModal({
						title: '身份证面错误，请重新上传',
						showCancel: false
					})
					return
				}
				let baseUrl = BASE_URL.slice(0, -11)
				uni.showLoading({
					title: '上传中',
					mask: true
				})
				let filePath = this['idCard' + this.idCardDirection + 'PicPath']
				// uni.getFileSystemManager().readFile({
				// filePath: filePath, //选择图片返回的相对路径
				// encoding: 'base64',
				// success: res => {
				let data = {
					image: filePath.split(',')[1],
					imageType: 'BASE64',
				}
				data.ocrType = detectInfo.label
				uni.request({
					url: baseUrl + '/verification/idCardOcr',
					method: 'POST',
					data: data,
					success: res => {
						console.log(res)
						if (res.data.data.imageStatus !== 'normal') {
							uni.showModal({
								content: '获取信息失败，请检查图片并重新上传',
								showCancel: false,
							})
						}
						if (event.name === 'Front' && (res.data.data.cardNum != this.idNumber || res.data
								.data.name != this.name)) {
							uni.showModal({
								content: '填写信息与身份证不一致',
								showCancel: false,
								complete: () => {
									this.step = 0
									this.idCardFrontPicPath =
										'../../static/upload_front.png'
									return
								}
							})
						}
						this['idCard' + this.idCardDirection + 'Base64'] = data.image
						if (event.name === 'Front') {
							this.idCardInfoInPage.name = res.data.data.name
							this.idCardInfoInPage.sex = res.data.data.sex
							this.idCardInfoInPage.nation = res.data.data.nation
							this.idCardInfoInPage.birth = res.data.data.birth
							this.idCardInfoInPage.address = res.data.data.address
							this.idCardInfoInPage.idNumber = res.data.data.cardNum
						} else {
							this.idCardInfoInPage.issuingAuthority = res.data.data.issuingAuthority
							this.idCardInfoInPage.issuingDate = res.data.data.issuingDate
							this.idCardInfoInPage.expiryDate = res.data.data.expiryDate
						}
					},
					fail: err => {
						uni.$showMsg('上传失败')
					},
					complete: () => {
						console.log('complete')
						uni.hideLoading()
					}
				})
				// 	},
				// 	complete: () => {
				// 		uni.hideLoading()
				// 	}
				// })

			},
			oversize() {
				uni.$showMsg('图片超出允许大小（1.5M）')
			},

			async gotoCheckFace() {
				//静态检测
				if (this.userInfo.staticFaceCheck === true) {
					uni.navigateTo({
						url: `/subpkg_checkin/staticFaceCheck/staticFaceCheck?idNumber=${this.idNumber}&name=${this.name}&phone=${this.phone}`
					})
				} else {
					// #ifdef MP-WEIXIN
					// const accountInfo = wx.getAccountInfoSync();
					// const env = accountInfo.miniProgram.envVersion
					// if (env !== "release") {
					// 	let faceRes = await uni.request({
					// 		url: IMG_BASE_URL + '/test_face_base64.txt',
					// 		method: 'GET'
					// 	})
					// 	let faceBase64 = faceRes[1].data
					// 	this.checkinInfo[this.checkinInfo.length] = {
					// 		name: this.name,
					// 		idNumber: this.idNumber,
					// 		phone: this.phone,
					// 		faceData: faceBase64
					// 	}
					// 	this.updateCheckinInfo(this.checkinInfo)
					// 	uni.navigateTo({
					// 		url: '/subpkg_checkin/confirmOrder/confirmOrder'
					// 	})
					// } 
					// #endif

					// #ifdef MP-ALIPAY
					uni.navigateTo({
						url: '/subpkg_checkin/alipayCheckPic/alipayCheckPic?idNumber=' + this.idNumber +
							'&name=' + this.name + '&phone=' + this.phone
					})
					// #endif
				}
			},

			finishIdCardUpload() {
				if (this.getAllInfo) {
					this.step = 2
				} else {
					uni.$showMsg('请检查身份证照片')
				}
			},
			// #ifdef MP-WEIXIN
			start() {
				console.log('调用start');
				this.idCardVKSession.destroy()
				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.faceVKSession.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.faceVKSession = wx.createVKSession({
					version: 'v1',
					track: {
						plane: {
							mode: 1,
						},
						face: {
							mode: 2,
						},
					},
				});
				//启动VK对象
				that.faceVKSession.start((errno) => {
					console.log('faceVKSession.start errno', errno);
					if (errno) {
						wx.showModal({
							title: '提示',
							content: '网络错误,请退出后重试',
							showCancel: false,
							confirmText: '确定',
							success(res) {
								console.log(res);
								if (res.confirm) {
									wx.navigateBack();
								}
							},
						});
						return
					}

					console.log('faceVKSession start')
					that.faceVKSession.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);
						this.showcamera = false
					},
				});
			},
			//上传
			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) {
								uni.showModal({
									content: '图片检查通过！',
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确定');
											let infoFromIdCard = {}
											that.infoList.forEach(info => {
												infoFromIdCard[info] = that[info]
											})
											let currentCheckinInfo = {
												name: that.name,
												idNumber: that.idNumber,
												phone: that.phone,
												faceData: mybase64
											}
											currentCheckinInfo = {
												...currentCheckinInfo,
												...infoFromIdCard
											}
											that.checkinInfo.push(currentCheckinInfo)
											that.updateCheckinInfo(that.checkinInfo)

											let currentGuestInfo = {
												name: that.name,
												idNumber: that.idNumber,
											}

											let i
											for (i = 0; i < that.guestInfo.length; i++) {
												if (that.guestInfo[i].idNumber == that.idNumber) {
													that.guestInfo[i] = {
														...currentGuestInfo,
														...infoFromIdCard
													}
													that.updateGuestInfo(that.guestInfo)
												}
											}
											if (i === that.guestInfo.length) {
												that.guestInfo.push({
													...currentGuestInfo,
													...infoFromIdCard
												})
												that.updateGuestInfo(that.guestInfo)
											}

											setTimeout(() => uni.reLaunch({
												url: '/subpkg_checkin/confirmOrder/confirmOrder'
											}), 1000);
										}
									},
								});
							} else {
								uni.showLoading({
									title: '正在身份核验，请稍后',
								});
								let yunjiFaceCheckInfo = {
									idNo: that.idNumber,
									name: that.name,
									image: mybase64,
								};
								let checkRes = await uni.$http.post(
									'/faceVerification/yunjiVerification',
									yunjiFaceCheckInfo
								);

								if (checkRes.data.success === true) {
									let infoFromIdCard = {}
									that.infoList.forEach(info => {
										infoFromIdCard[info] = that.idCardInfoInPage[info]
									})
									let currentCheckinInfo = {
										name: that.name,
										idNumber: that.idNumber,
										faceData: mybase64,
										phone: that.phone,
										...infoFromIdCard
									}
									//更新local storage 中的入住信息
									let checkinInfoToUpdate = that.checkinInfo
									checkinInfoToUpdate.push(currentCheckinInfo)
									that.updateCheckinInfo(checkinInfoToUpdate)
									//更新local storage 中的身份证信息
									let idCardInfoToUpdate = that.idCardInfo
									idCardInfoToUpdate.push(that.idCardInfoInPage)
									that.updateIdCardInfo(idCardInfoToUpdate)
									//如果上传过照片则更新服务器中的身份证信息
									if (that.idCardFrontDetectInfo.detected && that.idCardBackDetectInfo
										.detected) {
										uni.$http.post('/idCardInfo', {
											...that.idCardInfoInPage,
											birthday: that.idCardInfoInPage.birth,
											idCardFrontBase64: that.idCardFrontPicPath.split(',')[1],
											idCardBackBase64: that.idCardBackPicPath.split(',')[1]
										})
									}
									//如果是主入住人，且当前账号姓名和身份证号信息与所传身份证不一致，则更新账号信息为主入住人信息
									if (this.isMainCustomer && (this.userInfo.name !== this.name || this
											.userInfo.idNumber !== this.idNumber)) {
										this.userInfo.name = this.name
										this.userInfo.idNumber = this.idNumber
										this.updateUserInfo(this.userInfo)
										uni.$http.put(`/userInfo/${this.userInfo.id}`, this.userInfo)
									}
									uni.hideLoading();
									uni.$showMsg('身份核验通过！')
									setTimeout(() => uni.reLaunch({
										url: '/subpkg_checkin/confirmOrder/confirmOrder'
									}), 1000)
								} else {
									uni.hideLoading()
									uni.showModal({
										content: '身份核验失败,请重试',
										showCancel: false,
										success: function(res) {
											if (res.confirm) {
												console.log('用户点击确定');
												that.initData();
											}
										},
									});
								}
							}
						} else {
							uni.hideLoading()
							uni.showModal({
								content: '身份核验失败,请重试',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										that.initData();
									}
								},
							});
						}
						console.log('checkPicRes', res);
					});
			},
			// #endif
		},
		onLoad() {
			let pages = getCurrentPages()
			let beforePage = pages[pages.length - 2]
			//不是从确定订单页面点击添加顾客跳转过来，设置信息为当前账户的信息，清空入住信息
			if (beforePage.route !== 'subpkg_checkin/confirmOrder/confirmOrder') {
				this.name = this.userInfo.name
				this.idNumber = this.userInfo.idNumber
				this.phone = this.userInfo.phone
				this.updateCheckinInfo([])
				this.isMainCustomer = true
			} else {
				this.isMainCustomer = false
			}

			// #ifdef MP-WEIXIN
			this.isVKSupport = wx.isVKSupport('v1')
			if (!this.isVKSupport) {
				uni.showModal({
					content: '微信版本过低，请升级至最新版本',
					showCancel: false,
				})
			}
			// #endif
		},
		// #ifdef MP-WEIXIN
		onShow() {
			this.showAddGuest = true
			this.pageTitle = '身份信息录入'
		},
		onReady() {
			this.initIdCardVKSession()
		},
		onShareAppMessage(info) {
			return {
				title: '源享住',
				path: 'pages/quickLogin/quickLogin',
				imageUrl: '/static/logo.png'
			}
		}
		// #endif
	}
</script>

<style lang="scss">
	.btn-container {
		position: fixed;
		bottom: 90rpx;
		left: 30rpx;
		right: 30rpx;

		.u-button__text {
			font-size: 30rpx !important;
		}
	}

	page {
		background: #EFEFF4;

		.container {
			.step-zero {
				.tips {
					margin: 30rpx;
				}

				.u-form {
					margin-top: 10rpx;
					background-color: #FFFFFF;

					.u-form-item {
						line-height: 50rpx;

						.u-form-item__body {
							margin-left: 32rpx;
							border-bottom: 2rpx solid #E5E5E5;

							.u-form-item__body__right__content__slot {
								display: flex;
								flex-direction: row;
								justify-content: space-between;
								margin-right: 20rpx;
								align-items: center;
							}
						}

						.u-form-item__body__left__content__label {
							font-size: 30rpx;
						}
					}
				}
			}

			.step-one {
				.upload-container {
					width: 500rpx;
					margin: 30rpx auto;

					.u-upload {
						image {
							width: 500rpx;
							height: 350rpx;
							margin: 0 auto;
						}
					}
				}
			}

			.step-two {
				.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;
							}
						}
					}
				}
			}
		}
	}
</style>