<template>
	<view>
		<view class="title">
			{{type == 1 ? '正在识别中，请看向摄像头!' : type == 2 ? '人脸识别成功' : '人脸识别失败'}}
		</view>

		<cover-view class="img">
			<video id="video_1" ref="video" class="video" stylautoplay :show-center-play-btn="false"
				:show-play-btn="false" :controls="false"></video>
			<cover-image v-show="faceImgData" :src="faceImgData" class="image" ></cover-image>
		</cover-view>

		<view class="reload">
			<text>{{type == 1 ? '识别中' : type == 2 ? this.nameTwo : '重新识别'}}
				<u-icon class="ic" name="reload" color="#8C8C8C" size="40rpx" @click="refresh"></u-icon>
			</text>
		</view>

		<view class="reload">
			<!-- <image v-show="faceImgData" :src="faceImgData" style="width: 100px;height: 100px;"></image> -->
			<!-- <canvas  ref="canvas" canvas-id="cvs" v-show="true" width="520" height="520"></canvas> -->
			<!-- <text>Messis <u-icon class="ic" name="reload" color="#8C8C8C" size="40rpx"></u-icon></text> -->
		</view>

		<view class="submit">
			<u-button :disabled="type != 2" shape="circle" type="primary" text="确定" color="#7B5DF0"
				style="width: 550rpx;" @click="toAdd">
			</u-button>
		</view>

		<view class="skip">
			<text @click="skip">跳过</text>
		</view>

	</view>

</template>

<script>
	import html2Cvs from 'html2canvas'
	export default {
		data() {
			return {
				isnotbtn: true,
				isnotcanvas: false,
				intervalTakeImg: null,
				image: '',
				faceData: '',
				faceImgData: '',
				proxy: null,
				show: false,
				msg: '',
				canvasCtx: null,
				type: '1',
				name: '', // 人脸识别成功数据
				nameTwo: '载入中', // 识别成功后人名
			}
		},
		mounted() {
			this.canvasCtx = uni.createCanvasContext('cvs', this);
			if (window.frames.length != parent.frames.length) {
				this.iFramePostMessage()
				window.addEventListener('message', (msg) => { //接受数据
					alert(msg)
					console.log(msg)
					const _this = this
					this.msg = JSON.stringify(msg.data)
					if (msg.data.isIframe) {}
					if (msg.data.userId) {
						_this.isnotbtn = false
						// _this.image = imgBase64
						Api.faceData(msg.data.userId)
							.then(reslove => {
								// console.log('%cHealthEduOnline.vue line:115 reslove', 'color: white; background-color: #26bfa5;', reslove);
								if (reslove.data.data === null) {
									// imgBase64 = ''
									// _this.noLogin()
									_this.$emit('timeOutLogin')
									this.show = false
									return
								}
								_this.faceData = reslove.data.data
								this.inLogin()
								this.show = false
								_this.closeCamera()
							})
							.catch(err => {
								this.show = false
								// console.log('%cHealthEduOnline.vue line:200 err', 'color: white; background-color: #26bfa5;', err);
							})
						// clearInterval(_this.intervalTakeImg)
						// _this.intervalTakeImg = null
					}
				}, false)
			} else {
				this.callCamera()
			}
		},

		methods: {

			//开启融梦人脸识别
			iFramePostMessage(name = 'toFaceLogin') { //调用父页面方法
				window.parent.postMessage(name, '*')
			},
			inLogin() {
				Api.getToken({
					name: this.faceData.name,
					sn: this.faceData.childNo,
					gender: this.faceData.sex == 1 ? '男' : '女',
					grant_type: 'student'
				}).then((res) => {

					if (res.data != undefined) {
						window.localStorage.setItem('Blade-Auth', res.data.access_token)
						Api.getStudentInfo(res.data.user_id).then((user) => {
							if (user.data && user.data.code == 200 && user.data.data) {
								this.$store.dispatch('setUserInfo', user.data.data)
								window.localStorage.setItem('userInfo', JSON.stringify(user.data.data))
								const userSig = genTestUserSig(user.data.data.id).userSig
								// this.$cookies.set('userId',)
								const userId = user.data.data.id
								window.localStorage.setItem('userId', userId)
								window.localStorage.setItem('userSig', userSig)
								this.$store.commit('userLoginSuccess')
								this.$store.commit('setLoginUserInfo', {
									userId,
									userSig
								})
								Api.loginSuccess(getCookie('SCREENID')).then(res => {
										window.location.reload()
									})
									.catch(err => {
										window.location.reload()
									})
								// 登录 trtcCalling
								// console.log(this.proxy);
								this.$emit('successLogin')
							} else {
								localStorage.clear()
							}
						})
					}
				}).catch(ss => {})
			},
			/**
			 * 重新识别
			 */
			noLogin() {
				this.faceData = ''
				this.image = ''
				this.callCamera()
			},

			callCamera() {
				const _this = this
				var videoObj = {
					"video": true
				};
				let platform = uni.getSystemInfoSync().platform
				console.log(platform)
				if(platform == 'ios') {
				    this.test()
				    return
				}
				//初始化摄像头参数
				if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
					navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator
						.mozGetUserMedia;
					navigator.getUserMedia(videoObj, (stream) => {
						this.isnotbtn = true
						// 摄像头开启成功
						this.$refs["video"].srcObject = stream;
						// // 实时拍照效果
						this.$refs["video"].play();
						this.show = true
						this.type = 1
						this.test()
						this.photograph()
						setTimeout(() => {
							// debugger
							if (!this.faceData && !this.image) {
								_this.closeCamera()
								_this.show = false
								clearInterval(_this.intervalTakeImg)
								_this.intervalTakeImg = null
								_this.$emit('timeOutLogin')
							}
							// this.noLogin()
						}, 15000)
					}, (err) => {
						console.log("Video capture error: ", err.code);
						this.show = false
						this.$emit('err')
					});
				}
			},
			test() {
				var video = document.querySelector('video');
				// 兼容代码
				window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
				if (navigator.mediaDevices === undefined) {
					navigator.mediaDevices = {};
				}
				if (navigator.mediaDevices.getUserMedia === undefined) {
					navigator.mediaDevices.getUserMedia = function(constraints) {
						var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator
							.msGetUserMedia;
						if (!getUserMedia) {
							return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
						}
						return new Promise(function(resolve, reject) {
							getUserMedia.call(navigator, constraints, resolve, reject);
						});
					}
				}
				//摄像头调用配置
				var mediaOpts = {
					audio: false,
					video: {
						facingMode: "user"
					}

				}

				let that = this;
				navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
					that.mediaStreamTrack = stream;
					video = document.querySelector('video');
					if ("srcObject" in video) {
						video.srcObject = stream

					} else {
						video.src = window.URL && window.URL.createObjectURL(stream) || stream

						this.canvasCtx.drawImage(window.URL.createObjectURL(stream), 0, 0, 520, 520);
					}

					video.play();
					that.type = 1
					that.photograph();
				}).catch(function(err) {
					console.log(err)
				});
			},
			// 拍照
			photograph() {
				// let ctx = document.createElement('canvas').getContext("2d")
				let ctx = uni.createCanvasContext('cvs', this);
				// let ctx = this.$refs.canvas.getContext("2d");
				const _this = this
				this.intervalTakeImg = setInterval(() => {
					// 把当前视频帧内容渲染到canvas上
					// ctx.drawImage(document.createElement('canvas'), 0, 0, 520, 520);
					html2Cvs(document.querySelector('video'), {
						backgroundColor: null,
						useCORS: true
					}).then(cvs => {
						let imgData = cvs.toDataURL('image/png')
						this.faceImgData = imgData
						// this.type = 2
						this.faceRecognition()
						// this.intervalTakeImg = null
						// clearInterval(this.intervalTakeImg)
						// ctx.drawImage(imgData, 0, 0, 520, 520);
					})
					// 转base64格式、图片格式转换、图片质量压缩
					// console.log('canvas', document.createElement('canvas').toDataURL("image/jpeg", 0.7))
					// return
					let imgBase64 = document.createElement('canvas').toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小
					// let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小
					// console.log('canver', this.$refs["canvas"])

					// console.log('%cHealthEduOnline.vue line:92 imgBase64', 'color: white; background-color: #26bfa5;', imgBase64);
					let str = imgBase64.replace("data:image/jpeg;base64,", "");
					let strLength = str.length;
					let fileLength = parseInt(strLength - (strLength / 8) * 2); // 图片尺寸  用于判断
					let size = (fileLength / 1024).toFixed(2);
					console.log(size); // 上传拍照信息  调用接口上传图片 .........

					// 保存到本地
					this.dialogCamera = false;
					// this.faceRecognition()
					clearInterval(this.intervalTakeImg)
				}, 4000)
				// let ADOM = document.createElement("a");
				// ADOM.href = imgBase64 ;
				// ADOM.download = new Date().getTime() + ".jpeg";
				// ADOM.click();
			},

			// 上传人脸识别图片
			faceRecognition() {
				this.$request({
					url: '/face_check/faceRecognition',
					header: {
						contentType: "application/json"
					},
					data: {
						image: this.faceImgData,
					},
					method: 'POST',
				}).then(res => {
					console.log(res)
					if(res.data.length != 0){
						if(res.data[0].name != null){
							// this.type = 3
							this.type = 2
							this.name = res.data[0].name
							this.getBasics()
						}else{
							// this.toAdd(res.data[0].name)
							console.log('w')
							this.type = 3
						}
					}else{
						console.log('w')
						this.type = 3
					}
					
				})

			},

			// 人脸识别成功获取基础信息
			getBasics() {
				this.$request({
					url: this.$api.addHandle.student,
					data: {
						id: this.name,
					},
				}).then(res => {
					console.log(res)
					this.nameTwo = res.data.name
				})
			},

			// 关闭摄像头
			closeCamera() {
				if (!this.$refs["video"].srcObject) {
					this.dialogCamera = false;
					return;
				}
				this.this.intervalTakeImg = null
				let stream = this.$refs["video"].srcObject;
				let tracks = stream.getTracks();
				tracks.forEach((track) => {
					track.stop();
				});
				this.$refs["video"].srcObject = null;
				this.isnotbtn = false
			},

			// 刷新人脸
			refresh() {
				this.faceImgData = null
				this.type = 1
				this.callCamera()
			},


			//跳过
			skip() {
				console.log('跳过')
				this.toAdd()
			},

			// 确认
			confirm() {
				this.toAdd('w')
			},

			// 跳转新增
			toAdd() {
				uni.redirectTo({
					url: `/pages/addHandle/index?idt=${this.name}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		/* background-color: #D9D9D9; */
		// background-color: #F5F5F5 !important;
		overflow: hidden;
	}

	.title {
		margin-top: 126rpx;
		text-align: center;
		color: rgba(0, 0, 0, 0.90);
		font-size: 40rpx;
	}

	.img {
		width: 280rpx;
		height: 280rpx;
		border-radius: 100%;
		margin: 0 auto;
		margin-top: 40rpx;
		margin-bottom: 46rpx;
		overflow: hidden;
		position: relative;
		background-color: #ccc;

		.video {
			width: 380rpx;
			height: 380rpx;
			top: -50rpx;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}

		.image {
			width: 380rpx;
			height: 380rpx;
			top: -50rpx;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
	}

	.reload {
		color: #6241D5;
		font-size: 40rpx;
		display: flex;
		justify-content: center;

		text {
			display: inline-block;
			position: relative;

			.ic {
				position: absolute;
				top: 10rpx;
				right: -60rpx;
			}
		}
	}

	.submit {
		margin-top: 580rpx;
	}

	.skip {
		text-align: center;
		margin-top: 26rpx;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.90);
	}


	.active {
		background: #fff;
	}

	.imagbtn {
		display: flex;
		align-content: center;
		justify-content: start;
	}

	.face-bottom {
		position: absolute;
		bottom: 21px;
		background-color: #fff;
		left: 50%;
		transform: translateX(-50%);
		height: 41px;
		width: 306px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 29px;
		font-size: 16px;
		color: black;

		img {
			margin-right: 11px;
		}
	}

	.querybtn {
		width: 50px;
		height: 50px;
		margin: auto 0;
		border-radius: 15px;
		/* font-size:30px; */
	}

	.face-data {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 20px;

		.face-data-name {
			margin-top: 24px;
			margin-bottom: 48px;
		}
	}

	.btn {
		--hue: 190;
		--btn-bg-color: hsl(var(--hue), 100%, 50%);
		--btn-bg-color-darker: hsl(var(--hue), 100%, 45%);
		position: relative;
		padding: 0.75rem 1.5rem;
		margin: 1rem;
		font-size: 1rem;
		font-family: Lato, sans-serif;
		line-height: 1.5;
		color: white;
		text-decoration: none;
		background-color: var(--btn-bg-color);
		border: 1px solid var(--btn-bg-color);
		border-radius: 4px;
		box-shadow: 0 0.1px 0.7px rgba(233, 30, 99, 0.141), 0 0.1px 1.7px rgba(233, 30, 99, 0.202), 0 0.3px 3.1px rgba(233, 30, 99, 0.25), 0 0.4px 5.6px rgba(233, 30, 99, 0.298), 0 0.8px 10.4px rgba(233, 30, 99, 0.359), 0 2px 25px rgba(233, 30, 99, 0.5);
		outline: transparent;
		overflow: hidden;
		cursor: pointer;
		user-select: none;
		white-space: nowrap;
		transition: 0.25s;
	}

	.btn-pink {
		--hue: 330;
	}

	.btn-bubbles {
		overflow: visible;
		transition: transform ease-in 0.1s, background-color ease-in 0.1s, box-shadow ease-in 0.25s;
	}

	.btn-bubbles::before {
		position: absolute;
		content: "";
		left: -2em;
		right: -2em;
		top: -2em;
		bottom: -2em;
		transition: ease-in-out 0.5s;
		background-repeat: no-repeat;
		background-image: radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, transparent 20%, var(--btn-bg-color) 20%, transparent 30%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, transparent 20%, var(--btn-bg-color) 20%, transparent 30%), radial-gradient(circle, transparent 20%, var(--btn-bg-color) 20%, transparent 30%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, transparent 20%, var(--btn-bg-color) 20%, transparent 30%), radial-gradient(circle, transparent 20%, var(--btn-bg-color) 20%, transparent 30%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%), radial-gradient(circle, var(--btn-bg-color) 20%, transparent 20%);
		background-size: 13% 14%, 15% 19%, 11% 19%, 17% 14%, 16% 20%, 11% 18%, 16% 10%, 19% 17%, 18% 19%, 18% 18%, 15% 11%, 17% 19%, 17% 11%, 16% 16%, 16% 15%, 20% 11%;
		background-position: 18% 40%, 20% 31%, 30% 30%, 40% 30%, 50% 30%, 57% 30%, 65% 30%, 80% 32%, 15% 60%, 83% 60%, 18% 70%, 25% 70%, 41% 70%, 50% 70%, 64% 70%, 80% 71%;
		animation: bubbles ease-in-out 0.75s forwards;
	}

	.btn-bubbles:active {
		transform: scale(0.95);
		background: var(--btn-bg-color-darker);
	}

	.btn-bubbles:active::before {
		animation: none;
		background-size: 0;
	}

	@keyframes bubbles {
		0% {
			background-position: 18% 40%, 20% 31%, 30% 30%, 40% 30%, 50% 30%, 57% 30%, 65% 30%, 80% 32%, 15% 60%, 83% 60%, 18% 70%, 25% 70%, 41% 70%, 50% 70%, 64% 70%, 80% 71%;
		}

		50% {
			background-position: 10% 44%, 0% 20%, 15% 5%, 30% 0%, 42% 0%, 62% -2%, 75% 0%, 95% -2%, 0% 80%, 95% 55%, 7% 100%, 24% 100%, 41% 100%, 55% 95%, 68% 96%, 95% 100%;
		}

		100% {
			background-position: 5% 44%, -5% 20%, 7% 5%, 23% 0%, 37% 0, 58% -2%, 80% 0%, 100% -2%, -5% 80%, 100% 55%, 2% 100%, 23% 100%, 42% 100%, 60% 95%, 70% 96%, 100% 100%;
			background-size: 0% 0%;
		}
	}

	.animation {
		position: absolute;
		top: 0px;
		left: 0px;
		width: 100%;
		height: 100%;
		background:
			linear-gradient(rgba(167, 223, 255, 0.63), rgba(167, 223, 255, 0.63)),
			/* linear-gradient(90deg, #ffffff33 1px,transparent 0,transparent 19px),
	
	linear-gradient( #ffffff33 1px,transparent 0,transparent 19px), */
			linear-gradient(transparent, rgba(167, 223, 255, 0.63));
		/* background: linear-gradient(170deg,rgba(167,223,255,0.63) 0%, rgba(251,254,111,0.00) 100%); */
		background-size: 100% 1.5%, 10% 100%, 100% 8%, 100% 100%;
		background-repeat: no-repeat, repeat, repeat, no-repeat;
		background-position: 0% 0%, 0 0, 0 0, 0 0;
		/* 初始位置 */
		clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
		/* 添加动画效果 */
		animation: move 2s infinite linear;
		/* animation-direction: alternate; */
	}

	@keyframes move {
		to {
			background-position: 0 100%, 0 0, 0 0, 0 0;
			/* 终止位置 */
			clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
		}
	}

	.video .uni-video-cover {
		display: none !important
	}

	//播放按钮
	video::-webkit-media-controls-play-button {
		display: none;
	}

	//进度条
	video::-webkit-media-controls-timeline {
		display: none;
	}
</style>
