<!-- 人脸识别 -->
<template>
	<view class="human-face">
		<!-- 自定义导航栏 -->
		<uni-nav-bar dark :fixed="true" shadow background-color="var(--main-color)" status-bar left-icon="left"
			title="人脸识别" @clickLeft="$utils.navigateBack" />

		<!-- 人脸识别说明标题 -->
		<view class="human-face-title">为保证本人操作，请进行人脸验证</view>

		<!-- 人脸识别图片 -->
		<view class="human-face-img">
			<image v-if="!isPhoto"
				src="../static/1.png" mode="widthFix">
			</image>
			
			<image v-else-if="!!tempImg"
			:src="tempImg" mode="widthFix">
			</image>
			
			<camera 
			v-else 
			:device-position="devicePosition ?'front': 'back'" 
			class="camera"
			flash="off" 
			resolution='high' />
		</view>

		<!-- 人脸识别说明 -->
		<view class="human-face-desc"
		v-if="!isPhoto">
			人脸认证仅能由<text class="name">{{ userInfo.auth.name }}</text>本人完成验证时，请将镜头对准您的脸部
		</view>
		
		<view class="human-face-desc"
		v-else>
			<!-- {{ tipsText }} -->
		</view>

		<!-- 说明 -->
		<view class="desc">
			<view class="desc-item">
				<image src="../static/2.png"
					mode="widthFix"></image>
				<view class="text">避免遮挡</view>
			</view>
			<view class="desc-item">
				<image src="../static/3.png"
					mode="widthFix"></image>
				<view class="text">光线充足</view>
			</view>
			<view class="desc-item">
				<image src="../static/4.png"
					mode="widthFix"></image>
				<view class="text">正对充足</view>
			</view>
		</view>
		
		<!-- tipsText == successText -->
		
		<!-- 实名认证 -->
		<view class="btn"
		@click="handleTakePhotoClick"
		v-if="type == 'auth'">
			立即核验
		</view>
		
		<!-- 人脸核验 -->
		<view class="btn"
		v-else-if="!isVerifyFace"
		@click="handleTakePhotoClick">
			立即核验
		</view>
		
		<!-- <view class="btn">
			<uv-upload 
			multiple 
			:maxCount="1" 
			capture="camera"
			height="180rpx"
			@afterRead="afterRead">
				<view style="display: flex;justify-content: center;
				width: 600rpx;">
					拍照打卡
				</view>
			</uv-upload>
		</view> -->
		
		
		<uv-popup ref="successPopup" :round="30"
		>
			<view class="successPopup">
				
				<image src="/static/image/success.png" 
				style="width: 320rpx;"
				mode="widthFix"></image>
				
				<view class="text">
					核验成功
				</view>
				
				<view class="btn">
					<uv-upload 
					multiple 
					:maxCount="1" 
					capture="camera"
					height="180rpx"
					@afterRead="afterRead">
						<view style="display: flex;justify-content: center;
						width: 600rpx;">
							拍照打卡
						</view>
					</uv-upload>
				</view>
			</view>
		</uv-popup>
		

	</view>
</template>

<script>
	import position from '@/utils/position.js'
	import {
		mapState
	} from 'vuex'
	export default {
		name: "HumanFace",
		data() {
			return {
				isPhoto: false,
				form : {
					pic : '',
				},
				isLocationSubmit : false,//定位完成时提交
				
				
				tipsText: '', // 错误文案提示
				tempImg: '', // 本地图片路径
				
				cameraEngine: null, // 相机引擎
				devicePosition: true, // 摄像头朝向
				isAuthCamera: true, // 是否拥有相机权限
				
				type : '',
				
				isVerifyFace : false,//人脸核验是否成功
				
				successText : '请保持不动',//成功文案
			}
		},
		computed: {
			...mapState(['teamList', 'userInfo', 'authInfo']),
		},
		onLoad(args) {
			if(args.type){
				this.type = args.type
			}
			this.initData()
		},
		onShow() {
			let self = this
			position.getLocationDetail()
			.then(res => {
				console.log(res);
				self.form.lat = res.latitude
				self.form.lon = res.longitude
				self.form.address = res.address
				if(self.isLocationSubmit){
					self.submit()
				}
			})
		},
		methods: {
			afterRead(e) {
				let self = this
				e.file.forEach(file => {
					self.$Oss.ossUpload(file.url).then(url => {
						self.form.pic = url
						if(self.form.lat){
							self.submit()
						}else{
							uni.showLoading({
								title: '定位中...'
							})
							self.isLocationSubmit = true
						}
					})
				})
			},
			async submit(){
				this.form.pic = ''
				if (this.$utils.verificationAll(this.form, {
						lat : '经纬度缺失，请打开GPS',
						lon : '经纬度缺失，请打开GPS',
						address : '获取地址失败',
						// pic : '请拍照',
					})) {
					return
				}
				
				this.$api('clock', this.form, res => {
					if(res.code == 200){
						
						uni.showToast({
							title: '打卡成功',
							icon:'none'
						})
						
						setTimeout(uni.navigateBack, 1000, -1)
					}else{
						this.$nextTick(() => {
							this.form.image = ''
							this.tempImg = ''
						})
					}
				})
			},
			// 初始化相机引擎
			initData() {
				
				let createTime = new Date().getTime()
				let num = 0
				
				// #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
								
								let faseP = 0.8
								
								if (Math.abs(pitch) >= standard || Math.abs(roll) >= standard ||
									Math.abs(yaw) >= standard) {
									this.tipsText = '请平视摄像头'
								} else if (face.confArray.global <= faseP || face.confArray.leftEye <=
									faseP || face.confArray.mouth <= faseP || face.confArray.nose <= faseP ||
									face.confArray.rightEye <= faseP) {
									this.tipsText = '请勿遮挡五官'
								} else {
									this.tipsText = this.successText
									// 这里可以写自己的逻辑了
									// this.handleTakePhotoClick()
									
									// if(num > 2){
									// 	uni.showToast({
									// 		title: '人脸核验'
									// 	})
									// 	return
									// }
									
									// if(createTime - new Date().getTime() > 2000){
										
									// }
								}
								
							}
							// 不管是否有人脸都是成功
							this.tipsText = this.successText
						},
						fail: (err) => {
							if (err.x == -1 || err.y == -1) {
								// this.tipsText = '检测不到人'
							} else {
								this.tipsText = err.errMsg || '网络错误，请退出页面重试'
							}
						},
					})
				})
				// 5、开始监听帧数据
				listener.start()
				
				this.isPhoto = true
				// #endif
			},

			// 拍照 && this.tipsText != this.successTextthis.tipsText != ""
			handleTakePhotoClick() {
				console.log('handleTakePhotoClick');
				
				if (this.tempImg) {
					console.log('handleTakePhotoClick return', this.tempImg);
					return;
				}
				
				uni.showLoading({
					title: '打卡中...'
				})

				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.camera']) {
							this.isAuthCamera = false
							uni.openSetting({
								success: (res) => {
									if (res.authSetting['scope.camera']) {
										this.isAuthCamera = true;
									}
								}
							})
						}
					}
				})
				this.cameraEngine.takePhoto({
					quality: "high",
					success: ({
						tempImagePath
					}) => {
						this.tempImg = tempImagePath
						
						// 上传图片
						this.$Oss.ossUpload(tempImagePath).then(url => {
							
							// 实名认证，上传人脸
							if(this.type == 'auth'){
								let form = {
									...this.authInfo,
									pic : url
								}
								this.$api('authApply', form, res => {
									if(res.code == 200){
										setTimeout(uni.reLaunch, 1000, {
											url: '/pages/index/index'
										})
									}else{
										setTimeout(uni.navigateBack, 1000, -1)
									}
								})
								return
							}
							
							this.form.image = url
							
							if(!this.isVerifyFace){
								this.clockVerifyFace()
							}
						})
					}
				})
			},
			
			// 人脸核验
			clockVerifyFace(){
				let self = this
				this.$api('clockVerifyFace',
				this.form, res => {
					if(res.code == 200){
						// uni.showToast({
						// 	title: '核验成功！',
						// 	icon: 'icon'
						// })
						this.isVerifyFace = true
						// this.$refs.successPopup.open()
						
						if(self.form.lat){
							self.submit()
						}else{
							uni.showLoading({
								title: '定位中...'
							})
							self.isLocationSubmit = true
						}
					}else{
						this.tempImg = ''
						this.form.pic = ''
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.human-face {
		min-height: 100vh;
		background: white;
		
		.successPopup{
			display: flex;
			align-items: center;
			flex-direction: column;
			justify-content: center;
			width: 520rpx;
			color: #20D76D;
			gap: 50rpx;
			padding: 40rpx;
			.text{
				font-weight: 900;
				font-size: 40rpx;
			}
		}


		// 人脸识别说明标题
		.human-face-title {
			font-size: 35rpx;
			font-weight: bold;
			margin: 60rpx 0rpx;
			text-align: center;
		}

		// 人脸识别图片
		.human-face-img {
			display: flex;
			justify-content: center;
			image {
				width: 500rpx;
				border-radius: 50%;
			}
			.camera{
				width: 500rpx;
				height: 500rpx;
				border-radius: 50%;
			}
		}

		// 人脸识别说明
		.human-face-desc {
			color: #707070;
			width: 55%;
			font-size: 30rpx;
			margin: 30rpx auto;
			text-align: center;

			.name {
				color: $main-color;
			}
		}

		// 说明
		.desc {
			width: 80%;
			display: flex;
			flex-wrap: wrap;
			margin: 100rpx auto;

			.desc-item {
				width: 33.33%;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				image {
					width: 50%;
				}

				.text {
					font-size: 30rpx;
					color: #707070;
					margin-top: 10rpx;
				}
			}
		}

		// 立即核验
		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 83%;
			background: $main-color;
			color: white;
			height: 100rpx;
			border-radius: 50rpx;
			margin: 0rpx auto;
		}
	}
</style>