<template>
	<view class="allbox">
		<div class="custom" :style="{height: CustomBar+'px'}">
			<view class="navcontent" :style="[{top:statusBar + 'px'}]">
				<text style="color: #FFFFFF;font-size: 16px;line-height: 45px;position: absolute;" class="iconfont icon-xiangzuo"
					@click="BackPage">返回</text>
				<text style="color: #FFFFFF;font-size: 16px;line-height: 45px;text-align: center;">人脸识别</text>
				<text></text>
			</view>
		</div>
		<view class="fat">
			<text class="fatt">{{msg}}</text>
		</view>

		<div class="livefater">
			<div style="width: 350px;height: 350px;border-radius: 350px;background-color:#ccc;position: relative;overflow:hidden;z-index:2">
<!--				<view style="background:rgba(0,0,0,0.4);height: 80px; text-align: center; width: 344px;z-index:99">-->
<!--					<text style="color: #fff; font-size: 16px;padding-top: 34px;margin-left: 132px;">人脸未识别</text>-->
<!--				</view>-->
				<live-pusher id='livePusher' ref="livePusher" class="livePusher" url="" mode="SD" :muted="true"
					:enable-camera="true" :auto-focus="true" :beauty="1" whiteness="2" aspect="1:1"
					@statechange="statechange" @netstatus="netstatus" @error="error"></live-pusher>

			</div>
			<cover-image src="../../../../static/image/gaiz.png" class="gaiimg"></cover-image>
		</div>
<!--		<view class="allfoot">-->
<!--			<view class="allbtn bg-green" @click="startPreview">-->
<!--				<text class="alltext">打开摄像头进行人脸识别</text>-->
<!--			</view>-->
<!--		</view>-->
<!--        <view>-->
<!--            <button class="cu-btn round sm" @click="goStudy">继续观看</button>-->
<!--        </view>-->
	</view>
</template>
<script>
	import {basePath,loginUser} from "../../../../common/tool";

	export default {
		data: {
			msg:'请将人脸置于圆圈内',
			USER_ID:'',
			fil: true,
			imgList: [""],
			statusBar: '',
			CustomBar: 0,
			out_timer:null,
			timer: null,
			seconds: 0,
			pd: {
                COURSEWAREINDEX: '',
			    CURRICULUM_ID: '',
			    STAGESTUDENTRELATION_ID: '',
                CURRENTCOURSEWAREID: '',
				// COURSEWARECHAPTERID: '',
                COURSEWARECAPTURE: '',
                COURSEWAREFILES: '',
                PLAYTIME: ''
			},
			startPreviewTimer:null
		},
		onLoad(event) {
            this.pd.CURRICULUM_ID = event.CURRICULUM_ID
            this.pd.STAGESTUDENTRELATION_ID = event.STAGESTUDENTRELATION_ID
			// this.pd.COURSEWARECHAPTERID = event.COURSEWARECHAPTERID
            this.pd.CURRENTCOURSEWAREID = event.CURRENTCOURSEWAREID
            this.pd.COURSEWARECAPTURE = event.COURSEWARECAPTURE
            this.pd.COURSEWAREFILES = event.COURSEWAREFILES
            this.pd.PLAYTIME = event.PLAYTIME
            this.pd.COURSEWAREINDEX = event.COURSEWAREINDEX
			var that = this
			uni.getStorage({
				key: 'USER',
				success: function (res) {
					that.USER_ID = res.data.USER_ID
					if(!res.data.USER_ID){
						uni.clearStorage()
						uni.reLaunch({
							url: '/pages/login/home'
						});
					}
				}
			})
			// this.startPreview()
		},
		onReady() {
			// 注意:需要在onReady中 或 onLoad 延时
			this.context = uni.createLivePusherContext("livePusher", this);
			var that = this
			uni.getSystemInfo({
				success: function(e) {
					// 计算导航栏高度
					that.statusBar = e.statusBarHeight
					// #ifndef MP
					if (e.platform == 'android') {
						that.CustomBar = e.statusBarHeight + 50
					} else {
						that.CustomBar = e.statusBarHeight + 45
					}
					console.log(that.statusBar)
					// #endif
					// #ifdef MP-WEIXIN
					let custom = wx.getMenuButtonBoundingClientRect()
					that.CustomBar = custom.bottom + custom.top - e.statusBarHeight

					// #endif

					// #ifdef MP-ALIPAY
					that.CustomBar = e.statusBarHeight + e.titleBarHeight
					// #endif
					that.$nextTick(() => {
						// that.startPreview()
						that.startPreviewTimer = setInterval(() => {
							that.startPreview()
						}, 1000)
					})
				}
			})
			if(this.out_timer) {
				clearTimeout(this.out_timer);
				this.out_timer = null
			}
			if(this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
			this.out_timer = setTimeout(() => {
				uni.redirectTo({
					// url: '/pages/application/onlinexxks/my-study?CURRICULUM_ID=' + this.pd.CURRICULUM_ID + '&STAGESTUDENTRELATION_ID=' + this.pd.STAGESTUDENTRELATION_ID +'&isNoPass=true'
					url: '/pages/application/onlinexxks/home'
				})
			}, 30000)
		},
		beforeDestroy() {
			// 如果定时器在运行则关闭
			if(this.out_timer) {
				clearTimeout(this.out_timer);
				this.out_timer = null
			}
			if(this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
		},
		methods: {
			statechange(e) {
				console.log("statechange:" + JSON.stringify(e));
			},
			netstatus(e) {
				console.log("netstatus:" + JSON.stringify(e));
			},
			error(e) {
				console.log("error:" + JSON.stringify(e));
			},
			start: function() {
				this.context.start({
					success: (a) => {
						console.log("livePusher.start:" + JSON.stringify(a));
					}
				});
			},
			close: function() {
				this.context.close({
					success: (a) => {
						console.log("livePusher.close:" + JSON.stringify(a));
					}
				});
			},
			// 拍照事件
			snapshot: function() {
				var that = this
				this.context.snapshot({
					success: (e) => {
						that.getMinImage(e.message.tempImagePath)
					}
				});
			},
			// 开启摄像头
			startPreview() {
				this.$forceUpdate()
				var that = this
				that.context.stopPreview()
				this.context.startPreview({

					success: (a) => {
						that.startPreviewTimer && clearInterval(that.startPreviewTimer)
						console.info(1)
						that.timer = setInterval(function() {
							console.log("livePusher.startPreview:" + JSON.stringify(a));
							that.snapshot()
							// if (that.imgList.length > 3) {
							// 	console.log("3")
							// 	clearInterval(that.Timer)
							// }
						}, 2000)
					},
					fail(b) {

						console.info(2)
						console.log(JSON.stringify(b));
					},
					complete(c){

						console.info(3)
						console.log(JSON.stringify(c));
					}
				});
				console.info(5)
			},
			// 使用plus.zip.compressImage压缩图片并转换成base64
			getMinImage(imgPath) {
				var that = this
				plus.zip.compressImage({
						src: imgPath,
						dst: imgPath,
						overwrite: true,
						quality: 40
					},
					zipRes => {
						setTimeout(() => {
							var reader = new plus.io.FileReader();
							reader.onloadend = res => {
								var speech = res.target.result; //base64图片
								var USERAVATARPREFIX = speech.substring(0, speech.indexOf('base64,') + 7)
								var USERAVATARURL = speech.substring(speech.indexOf('base64,') + 7)

								uni.request({
									url: basePath +'/app/user/compareFace',
									method: 'POST',
									dataType: 'json',
									header: {
										'Content-type':'application/x-www-form-urlencoded'
									},
									data: {
										USERAVATARPREFIX:USERAVATARPREFIX,
										USERAVATARURL:USERAVATARURL,
										USER_ID : that.USER_ID,
                                        CORPINFO_ID:loginUser.CORPINFO_ID,
									},
									success: (res) => {
										uni.hideLoading();//结束加载中动画
										if (res.data != null) {
											var result = res.data.result;
											if ("success" == result) {
												uni.showToast({
													title: "验证成功",
													duration: 1000
												});
												this.goStudy()

											} else if ("error" == result) {
												this.msg = res.data.msg
											}else{
												uni.showToast({
													icon: 'none',
													title: "人脸信息更新,请重新登陆",
													duration: 2000
												});
											}
										}
									}
								})
							};
							//一定要使用plus.io.convertLocalFileSystemURL将target地址转换为本地文件地址,否则readAsDataURL会找不到文件
							reader.readAsDataURL(plus.io.convertLocalFileSystemURL(zipRes.target));
						}, 1000);
					},
					function(error) {
						console.log('Compress error!', error);
					}
				);
			},
			goStudy(){
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-study?CURRICULUM_ID=' + this.pd.CURRICULUM_ID
					 + '&STAGESTUDENTRELATION_ID=' + this.pd.STAGESTUDENTRELATION_ID + '&CURRENTCOURSEWAREID=' + this.pd.CURRENTCOURSEWAREID

					 // + '&COURSEWARECHAPTERID=' + this.pd.COURSEWARECHAPTERID
					 + '&COURSEWARECAPTURE=' + this.pd.COURSEWARECAPTURE + '&COURSEWAREFILES=' + this.pd.COURSEWAREFILES
					 + '&PLAYTIME=' + this.pd.PLAYTIME + '&COURSEWAREINDEX=' + this.pd.COURSEWAREINDEX
				})
			},
			BackPage() {
				uni.redirectTo({
					url: '/pages/application/onlinexxks/my-tasks'
				})
			}

		}
	}
</script>

<style>
	.allbox {
		background-color: #fff;
	}

	.allfoot {
		padding: 0 20px 0 20px;
	}

	.cu-btn {
		color: #fff;
	}

	.custom {
		background-color: #2C65F7;
	}

	.navcontent {
		height: 45px;
		padding: 0 24px;
		color: #FFFFFF;
		position: relative;
	}

	.livePusher {
		width: 350px;
		height: 350px;
	}

	.livefater {
		display: -ms-flex;
		display: -webkit-flex;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		margin-bottom: 50rpx;
		height: 350px;
		position: relative;
	}
	.fat{
		margin: 50rpx;
	}
	.fatt{
		text-align: center;
		font-size: 18px;
	}
	.gaiimg {
		width: 350px;
		height: 350px;
		margin-top: -350px;
	}

	.allbtn {
		color: #fff;
		border-radius: 10upx;
	}

	.alltext {
		text-align: center;
		color: #FFFFFF;
		font-size: 16px;
		line-height: 45px;

	}
</style>