<template>
	<view class="facebox">
		<view class="flex1">
			<view class="errortext"><text v-if="errortext != ''">{{ errortext }}</text></view>
			<view class="faces" id="show-content">
				<image :src="lines" class="lines"></image>
				<video class="facevideo"
						src=""
				        id="video"
				        :style="{ width: vwidth + 'px',height: vheight + 'px', display:showVideo}"
				
				        playsinline
				
				        webkit-playsinline
						
						autoplay = true
						
						muted = true
						
						loop = true
						
						controls = false
						show-center-play-btn = false 
						object-fit = fill
				      ></video> 
				<!-- <view class="tit">请保持不动</view> -->
			</view>
			<!-- <video></video> -->
		</view>
		<view class='photitp flexccc'>
			<view >请把脸移入框内并保持不动</view>
			<image :src="phoimg"></image>
		</view>
		<!-- 640 488 -->
		<!-- <view class="button-view" :style="{ display:(openCamera == true?'flex':'none')}">
						
						<view class="click-button"  v-if="startVideoStatus == false">
							<view class="button-btn button-btn2"  style="background-color: #0b4da2;" @tap.bind="startVideo">同意协议，开始拍摄</view>
						</view>
					
					</view> -->
	</view>
</template>

<script>
	import { uploadPhoto } from '@/api/system/user.js';
	import $ from "@/static/collect_face/jquery2.3.js";
	import faceFilter from "@/static/neuralNets/jeelizFaceFilter.module.js"; 
	import JeelizCanvas2DHelper from "@/static/neuralNets/JeelizCanvas2DHelper.js";
	// 引入uni.webview.1.5.2.js
	import '@/static/js/uni.webview.1.5.4.js'
	let VIDEOELEMENT = null;
	var  CVD = null; // return of Canvas2DDisplay
	export default{
		data(){
			return{
				phoimg:require('@/static/images/order/come/phoimg.png'),
				lines:require('@/static/images/order/come/faceline.png'),
				vwidth:215,//215 215
				vheight:215,
				isTest:false,
				againCount:0,
				showUserName:'',
				openCamera:false,
				screenSize:{
					width: window.screen.width,
					height: window.screen.height,
				},
				scanTip:'',
				// errortext:'点击同意按钮开始拍摄',
				errortext:'请保持不动',
				uploadHeadImg:'',
				imgUrl:'',
				pauseStatus:false,
				startCut:false,
				faceCoo:null,
				detectState:null,
				showVideo:'block',
				appendCss:false,
				bgImgClass:'home_wai',
				bgImgClass2:'home_nei',
				mediaStreamTrack:null,
				startVideoStatus:false,
				useCamera:'qian', //qian代表前置摄像头 hou代表后置摄像头
			}
		},
		onLoad(params) {
			if(params.username)
			{
				this.showUserName = params.username;
			}
			if(faceFilter && typeof faceFilter.toggle_pause == 'function')
			{
				faceFilter.destroy();
			}
			var that = this;//a
			that.startVideo()
			setTimeout(function(){
				//初始化的时候给追加上canvas用作载体
				if($('#jeeFaceFilterCanvas').html() == undefined)
				{
					$('#show-content').append('<canvas class="appendcanvas" width="'+that.vwidth+'" height="'+that.vheight+'" id="jeeFaceFilterCanvas"></canvas>');
				}
				if($('#jeeFaceFilterCanvas2').html() == undefined)
				{
					$('#show-content').append('<canvas class="appendcanvas appendcanvas2"  width="'+that.vwidth+'" height="'+that.vheight+'" id="jeeFaceFilterCanvas2"></canvas>');
				}
				if(that.appendCss == false)
				{
					$('uni-page-body').append(`<style>
					#jeeFaceFilterCanvas{
						display:none;
					}
					#jeeFaceFilterCanvas2{
						display:none;
						border-radius:50%
					}
					.uni-video-bar{
						display:none !important; //去除底部菜单栏
					}
					.uni-video-cover{
						display:none !important; //去除中间播放按钮
					}
					video{
						transform: rotateY(180deg);
						-webkit-transform: rotateY(180deg);    /* Safari 和 Chrome */
						-moz-transform: rotateY(180deg);
						border-radius:50% !important;
					}
					.uni-video-container{border-radius:50% !important;}
					.uni-video-video{border-radius:50% !important;}
					.uni-video-cover-play-button{display:none !important; }
					.uni-video-cover-duration{display:none !important; }
					</style>`);
					that.appendCss  = true;
				}
				//uniapp编译过后无法获取video的dom，此处追加id
				$('#video').find('video').prop('id','myVideo');
				//$('#refCanvas').find('canvas').prop('id','jeeFaceFilterCanvas');
				if(that.isTest == true)
				{
					//是否是测试环境 测试环境直接调用视频
					that.openCamera = true;
					that.main();
				}else{
					that.openCamera = true;
					that.bgImgClass = 'home_wai remove_animation';
					that.bgImgClass2 = 'home_nei remove_animation';
					that.errortext = '请保持不动';
				}
			},100)
		}, 
	 
		 
		onUnload(){
			
			this.closeVideo();
			
		},
		methods: {
			closeVideo(){
				try{
					//页面卸载的时候关闭视频播放
					if(this.mediaStreamTrack)
					{
						this.mediaStreamTrack.getTracks()[0].stop();
					}
				}catch{
					console.log('close mediaStreamTrack error')
				}
				try{
					const video = document.getElementsByClassName('uni-video-video')[0];
					video.srcObject = null;
				}catch{
					console.log('close video.srcObject error')
				}
				try{
					faceFilter.toggle_pause(true);
					faceFilter.destroy(); //销毁注册对象
				}catch{
					console.log('close faceFilter toggle_pause error')
				}
			},
			changeUserCamera(type){
				this.useCamera = type;
				if(type == 'hou')
				{
					$('uni-page-body').append(`<style>
					video{
						transform: rotateY(0deg);
						-webkit-transform: rotateY(0deg);    /* Safari 和 Chrome */
						-moz-transform: rotateY(0deg);
						border-radius:50% !important;
					}
					</style>`);
				}else{
					$('uni-page-body').append(`<style>
					video{
						transform: rotateY(180deg);
						-webkit-transform: rotateY(180deg);    /* Safari 和 Chrome */
						-moz-transform: rotateY(180deg);
						border-radius:50% !important;
					}
					</style>`);
				}
				this.playVideo();
			},
			startVideo(){
				// var imgsur='/profile/upload/2025/03/20/1742462163358_20250320171603A001.jpeg'
				// uni.$emit('refreshFace',imgsur)
				// uni.navigateBack({
				// 	delta:1
				// })
				// // http://10.90.90.53:8065/profile/upload/2025/03/20/1742462163358_20250320171603A001.jpeg
				// return
				if(this.startVideoStatus == false)
				{
					
					this.playVideo();
					//faceFilter.toggle_pause(false); //取消暂停
				}else{
					if(this.pauseStatus == false)
					{
						this.$api.msg('当前正在拍照');
						return;
					}
					this.savePause(false)
				}
			},
			savePause(status){
				this.uploadHeadImg = '';
				this.imgUrl = '';
				this.pauseStatus = status;
				if(status == false)
				{
					this.startCut = false;
					this.bgImgClass = 'home_wai';
					this.bgImgClass2 = 'home_nei';
					this.showVideo = 'none';
					//$('#jeeFaceFilterCanvas').hide();
					$('#jeeFaceFilterCanvas2').hide();
				}else{
					this.showVideo = 'block';
					//$('#jeeFaceFilterCanvas').show();
					$('#jeeFaceFilterCanvas2').hide();
				}
				//console.log(status)
				//true 暂停  false 继续执行
				faceFilter.toggle_pause(status);
			},
			playVideo() {
				var that = this;
				that.uploadHeadImg = '';
				that.imgUrl = '';
				that.startVideoStatus = true;
				that.startCut = false;
				var thatUseCamera = that.useCamera;
				if( thatUseCamera == 'qian')
				{
					var facingMode = 'user';
				}else if(thatUseCamera == 'hou'){
					var facingMode = { exact: "environment" };
				}
				if(faceFilter && typeof faceFilter.toggle_pause == 'function')
				{
					faceFilter.destroy();
				}
				setTimeout(function(){
					that.getUserMedia(
						{
							//摄像头拍摄的区域
							video: {
								width: 500,
								height: 500,
								facingMode: facingMode,
							}, /* 前置优先 */
						},
						that.success,
						that.error
					);
				},100)
			},
			// 访问用户媒体设备
			getUserMedia(constrains, success, error) {
				//this.success('11111')
				if(navigator.mediaDevices.getUserMedia){
					navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);//最新标准API
				}else if(navigator.webkitGetUserMedia){
					navigator.webkitGetUserMedia(constrains).then(success).catch(error);//webkit内核浏览器
				}else if(navigator.mozGetUserMedia){
					navagator.mozGetUserMedia(constrains).then(success).catch(error);//Firefox浏览器
				}else if(navigator.getUserMedia){
					navigator.getUserMedia(constrains).then(success).catch(error);//旧版API
				}else{
					this.errortext = "你的浏览器不支持访问用户媒体设备";
				}
			},
			success(stream){
				var that = this;
				that.bgImgClass = 'home_wai';
				that.bgImgClass2 = 'home_nei';
				that.openCamera = true;
				that.errortext = '请把人脸放在圆圈内拍摄脸部';
				that.mediaStreamTrack = stream;
				const video = document.getElementsByClassName('uni-video-video')[0];
				try{
					video.srcObject = stream;
				}catch{
					this.URL = window.URL || window.webkitURL;
					video.src = this.URL.createObjectURL(stream);
				}
				// webkit内核浏览器
				//苹果手机的系统弹框会阻止js的线程的继续执行 手动0.1秒之后自动执行代码
				setTimeout(() => {
			    	try{
						video.play();
					}catch{
						that.errortext = '视频流播放失败';
					}
			        that.main();
			    }, 100);
				
			},
			error(e){
				var that = this;
				that.startVideoStatus = false;
				that.bgImgClass = 'home_wai remove_animation';
				that.bgImgClass2 = 'home_nei remove_animation';
				if(this.useCamera == 'hou')
				{
					that.errortext = "调用后置摄像头失败:"+(e.name?e.name:'')+(e.message?e.message:'');
				}else{
					that.errortext = "调用前置摄像头失败:"+(e.name?e.name:'')+(e.message?e.message:'');
				}
				
			},
			main(){ // entry point
				var that = this;
				VIDEOELEMENT = document.getElementById('myVideo');
			    //that.errortext = '请将完整脸部对准屏幕中央';
				  if (VIDEOELEMENT['currentTime'] && VIDEOELEMENT['videoWidth'] && VIDEOELEMENT['videoHeight']){
						//console.log(VIDEOELEMENT)
						that.start();
				  } else {
					setTimeout(function(){
						that.main();
					}, 100);
					//VIDEOELEMENT['play']();
				  }
			},
			start(){ // launched when the video is loaded
			  
			  var that = this;
			  faceFilter.init({
			    canvasId: 'jeeFaceFilterCanvas',
			    videoSettings: {
			      videoElement: VIDEOELEMENT
			    },
				rotate:-90,
			    NNCPath: '../../../static/neuralNets/', // root of NN_DEFAULT.json file
			    callbackReady: function(errCode, spec){
			      if (errCode){
					//
					that.errortext = '人脸初始化出错'+  errCode;
					that.startVideoStatus = false;
			        console.log('AN ERROR HAPPENS. SORRY BRO :( . ERR =', errCode);
			        return;
			      }
			      CVD = JeelizCanvas2DHelper(spec);
			      CVD.ctx.strokeStyle = 'yellow';
				  //that.errortext = '初始化成功';
			    },
			    // called at each render iteration (drawing loop):
			    callbackTrack: function(detectState){
					//console.log(detectState.detected)
				  that.detectState = '';
				  that.faceCoo = ''; 
				  //console.log(detectState)
			      if (detectState.detected>0.9){
						
						that.detectState = detectState;
						that.showVideo = 'block'; 
						$('#jeeFaceFilterCanvas2').hide();
						var faceCoo = CVD.getCoordinates(detectState);
						that.faceCoo = faceCoo;
						CVD.ctx.clearRect(0,0,CVD.canvas.width, CVD.canvas.height);
						CVD.update_canvasTexture();
						CVD.draw();
						var check = that.checkTrue();
						if(check)
						{
							that.errortext = '请保持不动，即将拍照';
							if( that.startCut == false)
							{
								//console.log('start setTimeout')
								that.startCut = true;
								setTimeout(function(){
									//console.log('setTimeout')
									that.savePause(true);
									that.cutPhoto();
								},1000)
							}
						}
						//that.savePause(true)
			      }else{
					  that.showVideo = 'block';
					  $('#jeeFaceFilterCanvas2').hide();
					  //that.$api.loadingMsg('请将人脸放置框中')
					  that.errortext = '请将完整脸部对准屏幕中央';
				  }
			      
			    }
			  }); //end JEELIZFACEFILTER.init call
			},
			checkTrue(dump){
				//return true;
				var that = this;
				var faceCoo = that.faceCoo;
				var faceCooStr = JSON.stringify(faceCoo);
				var detectState  = that.detectState;
				if(!faceCoo || !detectState || detectState == '' || faceCoo == '')
				{
					return false;
				}
				var x = parseFloat(faceCoo.x).toFixed(2);
				var y = parseFloat(faceCoo.y).toFixed(2);
				var w = parseFloat(faceCoo.w).toFixed(2);
				var h = parseFloat(faceCoo.h).toFixed(2);
				var cw = parseFloat(CVD.canvas.width).toFixed(2);
				var ch = parseFloat(CVD.canvas.height).toFixed(2);
				var xcw = x/cw;
				var ycw = y/ch;
				if(xcw < 0.25 || xcw  > 0.5 || ycw > 0.45 || ycw < 0.1)
				{
					that.errortext = '请将完整脸部对准屏幕中央';
				}else{
					that.errortext = '';
				}
				if(that.errortext && that.errortext != '')
				{
					return false;
				}
				var faceMj = w * h  ;
				var allMj = cw * ch;
				var zhanbi = faceMj / allMj;
				var mianjiObj = {
					faceMj:faceMj,
					zhanbi:zhanbi
				}
				var mianjiobj2 = {
					cw:cw,
					ch:ch,
					allMj:allMj,
				}
				var mianjiStr = JSON.stringify(mianjiObj);
				var mianjiStr2 = JSON.stringify(mianjiobj2);
				if(zhanbi < 0.18)
				{
					that.errortext = '请离脸部近一点'
				}else if(zhanbi > 0.28 )
				{
					that.errortext = '请离脸部远一点'
				}else{
					return true;
				} 
				return false;
			},
			cutPhoto(rectparams){
				var that = this;
				var check = that.checkTrue(true);
				if(check == false)
				{
					that.savePause(false);
					return ;
				}
				that.errortext = '拍照成功';
				that.bgImgClass = 'home_wai remove_animation';
				that.bgImgClass2 = 'home_nei remove_animation';
				
				that.showVideo = 'none';
				//$('#jeeFaceFilterCanvas').hide();
				$('#jeeFaceFilterCanvas2').show();
				CVD.ctx.clearRect(0,0,CVD.canvas.width, CVD.canvas.height);
				CVD.draw();
				/* console.log('oldrect',JSON.stringify(rectparams))
				var rectnew = this.opeRect(rectparams,'canvas',0.5);
				console.log('cutPhoto',JSON.stringify(rectnew)) */
				var clip = $('#jeeFaceFilterCanvas2')[0];
				var context_clip = clip.getContext('2d');
				/* var maxwidth = clip.width;
				var ratio = parseFloat(maxwidth/this.vwidth).toFixed(3);
				console.log(maxwidth,this.vwidth,ratio)
				var rect = this.opeRect(rect,'clipImage',ratio);
				console.log(rect); */
				context_clip.drawImage(
					$('#jeeFaceFilterCanvas')[0], //规定要使用的图像、画布或视频。
					0,0, //开始剪切的 x 坐标位置。
					CVD.canvas.width, CVD.canvas.height,  //被剪切图像的高度。
					0, 0,//在画布上放置图像的 x 、y坐标位置。
					this.vwidth,this.vwidth  //要使用的图像的宽度、高度
				);
				//context_clip.clearRect(0, 0, CVD.canvas.width, CVD.canvas.height);//清除画布
				//位移来做镜像翻转
				if(that.useCamera == 'qian')
				{
					//使用前置摄像头需要反转镜头
					context_clip.translate(this.vwidth, 0);
					context_clip.scale(-1, 1); //左右镜像翻转
					//ctx.translate(0, 160 + posy * 2);
					//ctx.scale(1, -1); //上下镜像翻转
					context_clip.drawImage($('#jeeFaceFilterCanvas2')[0], 0, 0, this.vwidth, this.vwidth);
				}
				
				this.imgUrl = clip.toDataURL("image/jpeg"); 
				//this.uploadHeadImg
				this.useImg();
			},
			useImg(){
				this.imgSize();
			},
			imgSize(){
				var that = this;
				if (this.imgUrl) {
				        	// 获取base64图片byte大小
		        	const equalIndex = this.imgUrl.indexOf("="); // 获取=号下标
		        	let size;
			        if (equalIndex > 0) {
			          const str = this.imgUrl.substring(0, equalIndex); // 去除=号
			          const strLength = str.length;
			          const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
			          size = Math.floor(fileLength / 1024); // 向下取整
			        } else {
			          const strLength = this.imgUrl.length;
			          const fileLength = strLength - (strLength / 8) * 2;
			          size = Math.floor(fileLength / 1024); // 向下取整
			        }
			        if (size >= 200) {
			          	// 图片超过200k 重新再次压缩
						this.imgUrl =  $('#jeeFaceFilterCanvas2')[0].toDataURL("image/jpeg", 0.8);
						this.imgSize();
			        }else{
						that.faceOpeImg();
					}
		      	}
			},
			async faceOpeImg(){
				var that = this;
				//图片上传
				// console.log(this.imgUrl)
				// return
				let data = { name: 'file', filePath: this.imgUrl };
				uploadPhoto(data).then(response => {
					var imgsur=response.fileName;
					uni.$emit('refreshFace',imgsur)
					uni.navigateBack({
						delta:1
					})
				});
			},
			async uplodImg(){
				var that = this;
				var imgRes = await Upload.uploadFileToQiniu([
					{
						path:that.imgUrl
					}
				],200);
				uni.hideLoading();
				if(imgRes.list && imgRes.list.length > 0)
				{
					var headimg = imgRes.list[0]; 
				}else{
					var headimg = '';
				}
				//that.uploadHeadImg = headimg; //保存用户上传到七牛的头像
				if(headimg)
				{
					that.errortext = '上传图片成功';
					uni.showModal({
						title:'上传地址'+headimg
					})
					//that.$api.jeelizSetImg(headimg);
					
				}else{
					that.errortext = '上传图片失败';
					that.startVideoStatus = false;
				}
				//console.log(that.uploadHeadImg)
			},
			
		}
		
	}
</script>

<style lang="scss" scoped>
.facebox{min-height: 100vh;background: #ffffff;padding: 100rpx 0 130rpx; box-sizing: border-box;display: flex;flex-direction: column;}
.photitp{flex: 0 0 auto;margin-top: 60rpx;
	image{width: 82rpx;height: 132rpx;}
	view{font-weight: 500;font-size: 26rpx;color: #0391FD;margin-bottom: 40rpx;}
}
.faces{
	width: 244px;height: 244px;margin: 0 auto;position: relative;padding:15px;
	.lines{width: 244px;height: 244px;position: absolute;left:0rpx;top: 0rpx;}
	.facevideo{border-radius: 50% !important;margin: 0 auto;}
}
.errortext{
	width: 100%;
	height: 40rpx;
	line-height: 40rpx;
	//color: #e03030;
	color: #333333;
	text-align: center;
	font-size: 30rpx;
}
.button-view{
	width: 100%;
	margin-top:100rpx;
	height: 80rpx;
	display: -webkit-box; /* 老版本语法: Safari, iOS, Android browser, older WebKit browsers. */
	  display: -moz-box; /* 老版本语法: Firefox (buggy) */
	  display: -ms-flexbox; /* 混合版本语法: IE 10 */
	
	  display: -webkit-flex; /* 新版本语法: Chrome 21+ */
	display: flex;
	justify-content: center;
	align-items: center;
	.click-button{
		width: 90%;
		height: 100%;
		.button-btn{
			border-radius:20rpx ;
			width: 80%;
			margin-left: 10%;
			text-align: center;
			height: 100%;
			line-height: 80rpx;
			font-size: 28rpx;
			color: rgb(229, 81, 29);
			    border-color: rgb(240, 202, 182);
			    background: rgb(255, 228, 208);
		}
		.button-btn2{
			    color: rgb(255, 255, 255);
			    border-color: rgb(255, 68, 0);
			    background: rgb(255, 68, 0);
		}
	}
}

</style>