<template>
	<view class="container">
		<view class="notes">
			拍摄您本人人脸，确保对准手机，光线充足
		</view>
		<view class="msg">
			{{name}} {{cardNumber}}
		</view>
		<view class="info">
			<span v-if="tipsText">{{tipsText}}</span>
		</view>
		<view class="photo">
			<camera class="img" v-if='isAuthCamera' device-position="front" flash="off" resolution='high' />
			<img v-else :src="tempImg">
		</view>
		<view class="button" @click="handleTakePhotoClick">
			开启身份认证
		</view>

		<!-- 认证结果弹窗 -->
		<uni-popup ref="popup" :is-mask-click="false">
			<view class="popup-content">
				<view class="title">
					<view class="icon">
						<img src="./imgs/success.png">
					</view>
					<view class="title_info">
						打卡成功
					</view>
				</view>
				<view class="time">
					{{nowTime}}
				</view>
				<view class="popup_button" @click="handleGoHome">
					我知道了
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 错误文案提示
				tipsText: '',
				// 当前时间
				nowTime: "",
				// 本地图片路径 被匹对照片
				tempImg: '',
				// 场景照片
				sceneImage: "",
				// 经纬度
				lat: "",
				lng: "",
				// 地址
				location: "",
				// 规则id
				id: "",
				// 相机引擎
				cameraEngine: null,
				// 是否拥有相机权限
				isAuthCamera: true,
				// 姓名
				name: "",
				// 身份证号
				cardNumber: ""
			};
		},
		onLoad(options) {
			this.id = options.id
			this.lat = options.latitude
			this.lng = options.longitude
			this.location = options.address
			this.sceneImage = options.imgUrl
			this.initData()
			let userInfo = uni.getStorageSync("userInfo")
			if (userInfo) {
				this.name = userInfo.name
				this.cardNumber = userInfo.cardNumber
			}
		},
		methods: {
			// 初始化相机引擎
			initData() {
				// #ifdef MP-WEIXIN
				// 1、初始化人脸识别
				wx.initFaceDetect()
				// 2、创建 camera 上下文 CameraContext 对象
				this.cameraEngine = wx.createCameraContext()
				// 3、获取 Camera 实时帧数据
				const listener = this.cameraEngine.onCameraFrame((frame) => {
					if (this.tempImg) {
						return;
					}
					// 4、人脸识别，使用前需要通过 wx.initFaceDetect 进行一次初始化，推荐使用相机接口返回的帧数据
					wx.faceDetect({
						frameBuffer: frame.data,
						width: frame.width,
						height: frame.height,
						enablePoint: true,
						enableConf: true,
						enableAngle: true,
						enableMultiFace: true,
						success: (faceData) => {
							let face = faceData.faceInfo[0]
							if (faceData.x == -1 || faceData.y == -1) {
								this.tipsText = '检测不到人'
							}
							if (faceData.faceInfo.length > 1) {
								this.tipsText = '请保证只有一个人'
							} else {
								const {
									pitch,
									roll,
									yaw
								} = face.angleArray;
								const standard = 0.5
								if (Math.abs(pitch) >= standard || Math.abs(roll) >= standard ||
									Math.abs(yaw) >= standard) {
									this.tipsText = '请平视摄像头'
								} else if (face.confArray.global <= 0.8 || face.confArray.leftEye <=
									0.8 || face.confArray.mouth <= 0.8 || face.confArray.nose <= 0.8 ||
									face.confArray.rightEye <= 0.8) {
									this.tipsText = '请勿遮挡五官'
								} else {
									this.tipsText = '请点击下方按钮开始认证'
									// 这里可以写自己的逻辑了
								}
							}
						},
						fail: (err) => {
							if (err.x == -1 || err.y == -1) {
								this.tipsText = '检测不到人'
							} else {
								this.tipsText = err.errMsg || '网络错误，请退出页面重试'
							}
						},
					})
				})
				// 5、开始监听帧数据
				listener.start()
				// #endif
			},

			// 拍照点击
			handleTakePhotoClick() {
				if (this.tipsText != "" && this.tipsText != "请点击下方按钮开始认证") {
					return;
				}
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.camera']) {
							this.isAuthCamera = true
							uni.openSetting({
								success: (res) => {
									if (res.authSetting['scope.camera']) {
										this.isAuthCamera = true;
									}
								}
							})
						}
					}
				})
				this.cameraEngine.takePhoto({
					quality: "high",
					success: ({
						tempImagePath
					}) => {
						this.tempImg = tempImagePath
						this.isAuthCamera = false
						this.tipsText = ""
						this.handleOkClick()
					}
				})
			},
			// 上传
			handleOkClick() {
				//  这里的 this.tempImg 是经过人脸检测后  拍照拿到的路径  
				this.upLoadOne()
			},
			upLoadOne() {
				uni.showLoading({
					title: "检测中，请稍后...",
				});
				setTimeout(async () => {
					let res = await this.$myRequest_clockIn({
						url: "/attendance/api/sign/check/in/update",
						method: "put",
						header: {
							'Authorization': uni.getStorageSync("token")
						},
						data: {
							id: this.id,
							lat: this.lat,
							lng: this.lng,
							location: this.location,
							matchFaceImage: this.tempImg,
							sceneImage: this.sceneImage,
						}
					})
					// console.log(res);
					if (res.code == 200) {
						this.getNowTime()
						this.$refs.popup.open()
					}
				}, 2000)
			},
			// 点击 我知道了按钮 跳回首页
			handleGoHome() {
				this.$refs.popup.close()
				uni.reLaunch({
					url: "/pagesClockIn/home/home"
				})
			},
			// 获取当前时间
			getNowTime() {
				let date = new Date()
				let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
				let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
				let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
				this.nowTime = hours + ':' + minutes + ':' + seconds
			}
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		.notes {
			margin-top: 110rpx;
			text-align: center;
			font-size: 28rpx;
		}

		.msg {
			margin-top: 10rpx;
			text-align: center;
			font-size: 28rpx;
		}

		.info {
			margin-top: 100rpx;
			height: 40rpx;
			text-align: center;
		}

		.photo {
			margin: 0 auto;
			margin-top: 40rpx;
			width: 375rpx;
			height: 375rpx;
			border-radius: 188rpx;
			overflow: hidden;

			.img {
				width: 100%;
				height: 100%;
				border-radius: 50%;
			}

			img {
				width: 100%;
				height: 100%;
			}
		}

		.button {
			margin: 0 auto;
			margin-top: 127rpx;
			width: 430rpx;
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			color: #fff;
			border-radius: 21rpx;
			font-size: 32rpx;
			background: linear-gradient(180deg, rgba(0, 172, 252, 1) 0%, rgba(0, 130, 252, 1) 100%);
		}

		.popup-content {
			display: flex;
			flex-direction: column;
			justify-content: space-around;
			align-items: center;
			width: 630rpx;
			height: 376rpx;
			border-radius: 33rpx;
			background-color: #fff;

			.title {
				display: flex;
				justify-content: center;
				align-items: center;

				.icon {
					width: 40rpx;
					height: 40rpx;

					img {
						width: 100%;
						height: 100%;
					}
				}

				.title_info {
					margin-left: 8rpx;
					font-size: 36rpx;
					font-weight: 800;
					color: #0082FC;
				}
			}

			.time {
				font-size: 32rpx;
			}

			.popup_button {
				width: 50%;
				text-align: center;
				font-size: 32rpx;
				color: #0082FC;
			}
		}
	}
</style>
