<template>
	<view class="page-content">
		<!-- #ifdef MP-WEIXIN -->
		<!-- <u-navbar title="人脸识别" :is-back="true" :background="{backgroundColor: '#ffffff'}"></u-navbar> -->
		<topNavbar title="人脸识别"></topNavbar>
		<!-- #endif -->

		<view class="containerV">
			<view class="headerV">
				<view class="top-tips1">
					<view>请将正对手机，头部匹配摄像区域</view>
				</view>
				<view class="top-tips2">
					为了便于识别认证，请拍摄本人头像
				</view>
			</view>
			<!-- <u-circle-progress active-color="#2979ff" :percent="80"> -->
			<view class="contentV">
				<view class="mark"></view>
				<image v-if="tempImg" mode="widthFix" :src="tempImg" />
				<camera v-if='isAuthCamera' class="camera" :device-position="devicePosition ?'front': 'back'"
					flash="off" resolution='high'>
				</camera>
				<view v-show="!tempImg && tipsText" class="tipV">{{ tipsText }}</view>
			</view>
			<!-- </u-circle-progress> -->
			<view class="footerV">
				<view style="width: 100%;">
					<view v-if="!tempImg" style="width: 100%;">
						<view class="bottom-tips-2">该照片仅作为你认证的凭证</view>
					</view>

				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import { WX_API, H5_API, prefix } from '@/config/site.config.js';
	import { createconsult } from '@/config/api.js'
	var _url =  H5_API+ WX_API
	export default {
		name: 'index',
		components: {},
		data() {
			return {
				tipsText: '', // 错误文案提示
				tempImg: '', // 本地图片路径
				BASE_API: '',
				cameraEngine: null, // 相机引擎
				devicePosition: true, // 摄像头朝向
				isAuthCamera: true, // 是否拥有相机权限
				uploadUrl: _url + 'app-api/infra/file/upload',
				faceGetResult: '',
				count: 0,
				isload:false,//判断连拍
			}
		},

		onLoad(options) {
			this.initData()
		},
		mounted() {

		},
		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 = '请拍照'
									// 这里可以写自己的逻辑了
									this.handleTakePhotoClick()
								}
							}
						},
						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;
				// }
				if(this.isload) return
				this.isload = true
				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.isAuthCamera = false
						uni.showLoading({
							title: '人脸核身中，请耐心等待....'
						})
						this.upLoad(tempImagePath)
						console.log('tempImagePath', tempImagePath)
					}
				})
			},
			async upLoad(imgPath) {
				console.log('然后这里imgPath1111', imgPath)
				// this.againEvent()
				//             return
				const url = await this.UpImgResolve(imgPath, this.uploadUrl)
				this.faceGetResultEvent(url)
				console.log('然后这里imgPath', url, '9d1b7998-4949-46c7-a39f-726aad966664')
				//  然后这里imgPath 传过来的是 要上传的临时本地图片的路径
				//  具体上传方法根据自己的请求方式   请求自己的接口
			},
			UpImgResolve(file, url) {
				let that = this
				let token = 'Bearer '+ this.$store.state.user.vuex_loginInfo.accessToken
				let _this = this
				let timer = new Date() * 1
				
				// 处理接口超时异常
				setTimeout((res => {
					console.log('3122223')
					uni.hideLoading();
					that.againEvent()
				}), 10000)
				return new Promise(function(resolve, reject) {
					uni.uploadFile({
						url: _url + 'app-api/infra/file/upload',//接口
						filePath: file,//要上传的图片的本地路径
						name: 'file',
								
						formData: {
							path: 'complain/'+ uni.$u.date(timer, 'yyyy-mm-dd')+timer,
							type: 1,
							fileSuffix: "png"
						},
						header: {
							Authorization: token,
							'tenant-id': 1
						},
						success: function(uploadFileRes) {
							if (!uploadFileRes.data) return that.againEvent()
							
							const urlJosn = JSON.parse(uploadFileRes.data)
							console.log('拿到照片地址---',urlJosn.data)
							resolve(urlJosn.data)
						},
						error(res) {
							console.log('313', res)
							uni.hideLoading();
							that.againEvent()
						},
						catach(res) {
							console.log('3122223', res)
							uni.hideLoading();
							that.againEvent()
						}
					});
				})

			},
			faceGetResultEvent(url) {
				let that = this
				console.log('走进核身---',url)
				uni.request({
					url: that.faceGetResult,
					method: "post",
					data: {
						'livenessType': 'SILENT',
						'type': 3,
						'imageUrl': url,
						'identityType':2,
						'url':url
					},
					header: {
						'token': uni.getStorageSync('accessToken')
					},
					success: (res) => {
						uni.hideLoading()
						console.log('走进核身返回数据---',res )
						if (res.data.code != 200) {
							uni.showToast({
								title: '核身失败',
								icon: "none",
								mask: true,
							})
							that.againEvent()
							return
						} else {
							that.$u.route({
								type: 'tab',
								url: '/pages/tabbar/index/index'
							});
						}
						console.log('res', 1111, res)
					},
					fail:(res)=>{
							console.log('核身失败原因---', res)
					}

				})

			},
			// 失败后重新拉起人脸识别
			againEvent() {
				uni.hideLoading()
				this.count++
				if (this.count >= 5) {
					uni.showToast({
						title: '核身失败',
						icon: "none",
						mask: true,
					})
					return uni.navigateBack()

				}
				setTimeout((res => {
					this.isload = false
					this.tempImg = false
					this.isAuthCamera = true
					this.devicePosition = true
				}), 1500)
			}

		}
	}
</script>
<style lang="scss" scoped>
	page {
		background: #fff;
	}

	.page-content {
		width: 100%;
		height: 100%;

		.containerV {
			width: 100%;
			height: 100%;

			.headerV {
				.top-tips1 {
					margin-top: 60rpx;
					color: #1C1C1C;
					font-size: 36rpx;
					text-align: center;
				}

				.top-tips2 {
					margin-top: 20rpx;
					color: #00AAFF;
					font-size: 28rpx;
					text-align: center;
				}
			}

			.contentVLine {
				// border-radius:50%;
				// width: 450rpx;
				// height: 450rpx;
				// overflow: hidden;
				// margin: 0 auto;
				//             border:100rpx solid #fff;
				// position: absolute;
				// left: 0;
				// top: 0;
				// z-index: 99;
			}

			.contentV {
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				margin-top: 30rpx;
				width: 450rpx;
				height: 450rpx;
				margin: 80rpx auto;
				border-radius: 50%;
				border: 20px solid #eee;
				border-radius: 50%;

				.tipV {
					bottom: 30rpx;
					position: absolute;
					line-height: 90rpx;
					padding-left: 24rpx;
					padding-right: 24rpx;
					max-width: calc(100vw - 50rpx * 2);
					text-align: center;
					font-size: 30rpx;
					background: #000000;
					opacity: 0.75;
					color: #FFFFFF;
					border-radius: 16rpx;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					z-index: 5;
				}

				.camera {
					width: 450rpx !important;
					height: 450rpx !important;
					border-radius: 50% !important;
					overflow: hidden;
					position: absolute;
					left: -38rpx;
					top: -38rpx;
					z-index: -1;
				}

				.mark {
					position: absolute;
					left: 0;
					top: 0;
					z-index: 2;
					width: 100%;
					height: 100%;
					// background:deeppink;
					background-size: 750rpx 661rpx;
				}

				image {
					position: absolute;
					width: 450rpx;
					height: 450rpx;
					z-index: 3;
					border-radius: 50%;
				}
			}

			.footerV {
				width: 100%;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.privacyV {
					padding-top: 30rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: center;

					.text {
						font-size: 30rpx;
						color: #1C1C1C;
						text-align: center;
						line-height: 42rpx;
						margin-left: 15rpx;

						text {
							font-size: 30rpx;
							color: #00AAFF;
							text-align: center;
							line-height: 42rpx;
						}
					}

					.icon {
						width: 40rpx;
						height: 47rpx;
						background: green;
						background-size: 100% auto;
					}
				}

				.bottom-tips-2 {
					margin-top: 20rpx;
					color: #999999;
					text-align: center;
					font-size: 26rpx;
				}

				.take-photo-bgV {
					width: 100%;
					margin-top: 30rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: center;

					.btn-take-photo {
						margin: 0rpx 80rpx 0rpx 80rpx;
						width: 196rpx;
						height: 196rpx;
						background: yellow;
						background-size: 100% auto;
					}

					.btn-change-upload {
						left: 130rpx;
						width: 80rpx;
						height: 80rpx;
						background: blue;
						background-size: 100% auto;
					}

					.btn-change-camera {
						right: 130rpx;
						width: 80rpx;
						height: 80rpx;
						background: red;
						background-size: 100% auto;
					}
				}

				.confirmV {
					margin: 200rpx 100rpx 0rpx 100rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: space-between;

					.btn-cancel {
						font-size: 32rpx;
						color: #1C1C1C;
					}

					.btn-ok {
						font-size: 32rpx;
						color: #00AAFF;
					}
				}
			}
		}
	}
</style>
