<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">请将人脸置于圆圈内</text>
		</view>
		<div class="livefater">
			<div style="width: 350px;height: 350px;border-radius: 350px;overflow: hidden;background-color: #CCCCCC;">
				<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="snapshot">
				<text class="alltext">拍照/上传</text>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		basePath,
		loginUser,
	} from '../../../common/tool.js';
	export default {
		data: {
			USER_ID: '',
			fil: true,
			imgList: [""],
			statusBar: '',
			CustomBar: 0,
			startPreviewTimer: null
		},
		onLoad() {
			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)
					})
				}
			})
		},
		methods: {
			Timer() {},
			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
				uni.showLoading({
					title: "加载中..."
				}); //加载中动画
				this.context.snapshot({
					success: (e) => {
						console.log(JSON.stringify(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.log("livePusher.startPreview:" + JSON.stringify(a));
						// that.Timer = setInterval(function() {
						// 	that.snapshot()
						// 	if (that.imgList.length > 3) {
						// 		clearInterval(that.Timer)
						// 	}
						// }, 2000)
					}
				});
			},
			// 使用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/editUserFace',
									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
												});

											that.goback()
											} else if ("error" == result) {
												uni.showToast({
													icon: 'none',
													title: "人脸图像不符合要求,请重新上传!",
													duration: 2000
												});
											} else {
												uni.showToast({
													icon: 'none',
													title: "登录错误！请联系管理员",
													duration: 2000
												});
											}
										}
									}
								})
								console.log(speech);
								// this.imgList.push(speech);
							};
							//一定要使用plus.io.convertLocalFileSystemURL将target地址转换为本地文件地址，否则readAsDataURL会找不到文件
							reader.readAsDataURL(plus.io.convertLocalFileSystemURL(zipRes.target));
						}, 1000);
					},
					function(error) {
						console.log('Compress error!', error);
					}
				);
			},
			BackPage() {
				uni.navigateBack({
					delta: 1
				});
			},
			goback(){
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 1});
				uni.hideLoading();
			},

		}
	}
</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;
	}

	.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>
