<template>
	<view>
		<u-popup v-model="isShow" mode="bottom" border-radius="40" :mask-close-able="false">
			<view class="photoBox" v-if="isShow">
				<view class="photoTop">
					<view class="centersq">请正视手机屏幕 <button @click="showenter" type="primary" style="margin-left: 20px;">{{showCenter?"收起":"隐藏"}}</button></view>
				</view>
				<view class="photoCenter" v-show="showCenter">
					<view class="center_camera" v-if="isTaking">
						<!-- #ifdef MP-WEIXIN -->
						<camera device-position="front" flash="off" @error="error"
							style="width: 400px; height: 400px;margin: 0 auto;">
							<!-- 加人脸框 -->

						</camera>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<video :controls="false" v-show="status !== 3" id="video" width="400" height="400"
							class="photo_v"></video>
						<video id="video1" v-show="status === 3" class="photo_v2" autoplay controls :src="url"></video>
						<view class="mask" v-if="false"></view>
						<!-- #endif -->
					</view>
					<view class="custom" v-if="!isTaking">
						<!-- #ifdef MP-WEIXIN -->
						<image :src="avatarUrl" mode=""></image>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<image :src="faceUrl" mode=""></image>
						<!-- #endif -->
					</view>
				</view>
				<view class="btns">
					<!-- <view class="btnResult" v-if="isTaking" @click="takePhoto"
              >拍照</view
            > -->
					<view v-if="isTaking" class="takePhoto_btn">
						<view style="width: 100rpx; height: 2rpx"></view>
						<view class="">
							<button style="float: left;" :type="status === 3 ? 'primary' : 'primary'" class="pos"
								@click="luzhi" :disabled="status === 2">{{
            status === 1 ? "开始录制3秒" : status === 2 ? "录制中" : "提交"
          }}</button>
							<button @click="again" type="primary" style="float: left;
    margin-left: 20px;" v-if="status === 3">重录</button>
							<!-- <view class="btnResult" @click="luzhi()">重拍</view> -->
							<!-- <view class="square"></view> -->
						</view>
						<view class="rights" @click="takePhTips()">
							<text>抽查提示</text>
							<u-icon name="arrow-right" color="#FFFFFF" size="30"></u-icon>
						</view>
					</view>
					<view class="btnResult" v-if="!isTaking" @click="reTake">重拍</view>
					<view class="btnResult" v-if="!isTaking" @click="submit">确认</view>
				</view>
			</view>
		</u-popup>
		<!-- 播放前拍照end -->
		<u-popup v-model="showSet" :mask-close-able="false" mode="center" border-radius="24">
			<view style="
          align-items: center;
          padding: 0 40rpx;
          display: flex;
          flex-direction: column;
          justify-content: center;
        ">
				<view style="
            font-weight: bold;
            color: #333333;
            font-size: 30rpx;
            margin-top: 30rpx;
          ">温馨提示</view>
				<view style="
            width: 457rpx;
            color: #666666;
            font-size: 30rpx;
            margin-top: 30rpx;
          ">学习过程中需要拍照验证学员身份， 拍照功能需要使用您的相机。
					是否授权使用？</view>
				<view style="margin: 40rpx 0">
					<button open-type="openSetting" @bindopensetting="openSetting" class="btnSet">
						去授权
					</button>
				</view>
			</view>
		</u-popup>
		<!-- 拍照提示 -->
		<u-popup v-model="popupPhotoShow" mode="bottom" border-radius="30" :mask-close-able='false'>
			<view class="popup_box">
				<view class="head">
					<image src="/static/learn/photo_head.png" class="photo_head"></image>
				</view>
				<view class="warn">温馨提示</view>
				<view class="contents">
					<view class="words">1、本次为抽查检测，需要录制3秒的视频。</view>
					<view class="words">2、请保证摄像头正对自己，避免头像偏左或者偏右。</view>
					<view class="words">3、请保证拍照环境光线充足（照片太暗或曝光会降低验证通过率）。</view>
					<view class="words">4、请保证整个头像在人脸识别区域内，脸部无遮挡装饰物（佩戴眼镜会降低通过率）。</view>
					<view class="words">5、如果下面视频中出现黑屏，摄像头可能被其他进程占用，请关闭其他调用摄像头的程序，重新刷新当前页面重新拍照识别。</view>
				</view>
				<view class="take_photo" @click="openCamera">
					去录像
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import myCompressImage from "@/common/compressPhoto.js";
	import PopupPhoto from "./index.vue";
	export default {
		name: "SaasMiniprogramCamera",
		inject: ["paramsFn"],
		props: {
			visible: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				isShow: false,
				isTaking: true,
				avatarUrl: "",
				isCameraAuth: false,
				showSet: false,
				popupPhotoShow: false,
				status: 1, //1未录制 2录制中 3录制完成
				takeVideoModal: false,
				mediaRecorder: null,
				videoblob: null,
				url: null,
				faceUrl: null,
				showCenter:true
			};
		},
		methods: {
			showcenter(){
				this.showCenter=!this.showCenter;
			},
			error(err) {
				console.log(err)
			},
			async submit() {
				if (this.uploadLock) {
					return;
				}
				this.uploadLock = true;
				let imgUrl = await this.imageInfos()
				let compareFaceData = await this.faceRecognition(imgUrl);
				if (compareFaceData.code === 200) {
					this.$emit("submitTakeVideo", this.videoblob);
					this.closeCamera();
				} else {
					uni.showToast({
						title: compareFaceData.msg,
						icon: "none",
						duration: 2000,
					});

					setTimeout(() => {
						if (!this.isTaking) {
							this.reTake();
						}
					}, 2000);
				}
			},
			async imageInfos() {
				let resPath = await myCompressImage(this.avatarUrl || this.faceUrl, 50);
				const waitUpload = await this.$method.uploadFile(resPath, 0);
				return waitUpload;
			},
			closeCamera() {
				this.isShow = false;
				this.showSet = false;
				this.popupPhotoShow = false;
				this.status=1;
			},

			openCamera() {
				console.log("openCamera");
				this.uploadLock = false;
				this.popupPhotoShow = false;
				// 同一个商品只谈一次提示
				// let popupList = uni.getStorageSync("popupList") || [];
				// if (!popupList.includes(this.goodsId)) {
				// 	popupList.push(this.goodsId);
				// 	uni.setStorageSync("popupList", popupList);
				// 	this.popupPhotoShow = true;
				// 	return;
				// }
				// #ifdef MP-WEIXIN
				// 屏幕亮度
				uni.setKeepScreenOn({
					keepScreenOn: true,
				});
				uni.getSetting({
					success: (res) => {
						if (res.authSetting["scope.camera"]) {
							this.isCameraAuth = true;
							this.showCamera();
						} else {
							wx.authorize({
								scope: "scope.camera",
								success: () => {
									this.isCameraAuth = true;
									this.showCamera();
								},
								fail: () => {
									this.isCameraAuth = false;
									this.showSet = true;
								},
							});
						}
					},
					fail: (res) => {},
				});
				// #endif
				// #ifdef H5
				if (
					(window.navigator.mediaDevices &&
						window.navigator.mediaDevices.getUserMedia) ||
					window.navigator.getUserMedia ||
					window.navigator.webkitGetUserMedia ||
					window.navigator.mozGetUserMedia
				) {
					console.log("getUserMedia----");
					// 调用用户媒体设备, 访问摄像头
					this.getUserMedia({
							video: {
								width: 400,
								height: 400,
								facingMode: "user",
							},
						},
						this.photographSuccess,
						this.photographError
					);
				} else {
					console.log("1111没有摄像");
					this.photographError();
				}
				// #endif
			},
			showCamera() {
				this.isTaking = true;
				this.isShow = true;
				this.showCenter=true;
			},
			//确认拍照
			takePhoto() {
				// #ifdef MP-WEIXIN
				const ctx = uni.createCameraContext();
				ctx.startRecord
				ctx.takePhoto({
					quality: "high",
					success: (res) => {
						this.avatarUrl = res.tempImagePath;
						console.log("开始拍照this.avatarUrl:", this.avatarUrl);
						this.isTaking = false;
					},
					fail: (err) => {},
				});
				// #endif
				// #ifdef H5
				this.luzhi();
				// const canvas = document.createElement("canvas");
				// canvas.width = 400;
				// canvas.height = 400;
				// const context = canvas.getContext("2d");
				// const box = document.querySelector(".photo_v");
				// const video = box.querySelector("video");
				// context.drawImage(video, 0, 0, 400, 400);
				// this.faceUrl = canvas.toDataURL("image/png");
				// this.isTaking = false;
				// #endif
			},
			takePhTips() {
				this.popupPhotoShow = true;
				this.isShow = false;
				this.isTaking = false;
			},
			/**
			 * 人脸匹配
			 */
			faceRecognition(url) {
				return new Promise((resolve) => {
					// // #ifdef MP-WEIXIN
					// let fileSystem = uni.getFileSystemManager();
					// fileSystem.readFile({
					// 	filePath: `${this.avatarUrl}`,
					// 	encoding: "base64",
					// 	position: 0,
					// 	success: (res) => {
					// 		let base64 = "data:image/jpg;base64," + res.data;
					// 		this.CompareFace(base64, resolve);
					// 	},
					// 	fail(err) {
					// 		// this.$u.toast('人脸识别错误!')
					// 		console.error(err, "err-----人脸识别错误");
					// 	},
					// });
					// // #endif
					// // #ifdef H5
					// this.CompareFace(this.faceUrl, resolve);
					// // #endif
					this.CompareFace(url, resolve);
				});
			},
			CompareFace(url, resolve) {
				let timer = setTimeout(() => {
					uni.showToast({
						icon: "none",
						title: "录像超时，请重新录制视频",
						duration: 2000,
						success: () => {
							setTimeout(() => {
								uni.navigateBack();
							}, 1000);
						},
					});
				}, 10 * 1000);

				this.$api
					.faceCertificationCompareFace({
						urlA: url,
						// imageA: url,
						orderGoodsId: this.params.orderGoodsId,
						gradeId: this.params.gradeId,
					})
					.then((res) => {
						clearTimeout(timer);
						console.log(res, "人脸识别成功res");
						resolve(res.data);
					})
					.catch((err) => {
						clearTimeout(timer);
						// 当前网络延迟，
						console.log("人脸识别错误:", err);
						uni.showModal({
							content: "当前网络延迟",
							showCancel: false,
							success: (resultst) => {
								if (resultst.confirm) {
									uni.navigateBack();
								}
							},
						});
					});
			},
			photographSuccess(stream) {
				console.log("有摄像头---", stream);
				this.isCameraAuth = true;
				this.showCamera();
				this.$nextTick(() => {
					const box = document.querySelector(".photo_v");
					const video = box.querySelector("video");
					video.srcObject = stream;
					this.mediaRecorder = new MediaRecorder(stream);
					video.play();
				});
			},
			photographError(err) {
				console.log("没有摄像头：", err);
				uni.showModal({
					title: "提示",
					content: "课程学习需要开启摄像头进行拍照，经检测您的设备无摄像头可使用，请检测环境是否支持。",

					cancelText: "取消",
					confirmText: "确定",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack();
						} else if (res.cancel) {}
					},
				});
			},
			getUserMedia(constraints, success, error) {
				console.log("getUserMedia===", constraints);
				if (window.navigator.mediaDevices.getUserMedia) {
					// 最新的标准API
					window.navigator.mediaDevices
						.getUserMedia(constraints)
						.then(success)
						.catch(error);
				} else if (window.navigator.webkitGetUserMedia) {
					// webkit核心浏览器
					window.navigator.webkitGetUserMedia(constraints, success, error);
				} else if (window.navigator.mozGetUserMedia) {
					// firfox浏览器
					window.navigator.mozGetUserMedia(constraints, success, error);
				} else if (window.navigator.getUserMedia) {
					// 旧版API
					window.navigator.getUserMedia(constraints, success, error);
				}
			},
			again() {
				this.url = null;
				this.status = 1;
				this.showCenter=true;
			},
			luzhi() {
				if (this.status === 3) {
					//完成提交
					this.submit();
					return;
				}
				this.onCatchPhoto();
				this.mediaRecorder.start();
				this.status = 2;
				setTimeout(() => {
					this.stop();
					this.status = 3;
				}, 3500);
			},
			//拍照
			onCatchPhoto() {
				const canvas = document.createElement("canvas");
				canvas.width = 400;
				canvas.height = 400;
				const context = canvas.getContext("2d");
				const box = document.querySelector(".photo_v");
				const video = box.querySelector("video");
				context.drawImage(video, 0, 0, 400, 400);
				this.faceUrl = canvas.toDataURL("image/png");
				// console.log(this.faceUrl,'faceUrl')
			},
			stop() {
				this.mediaRecorder.stop();
				this.mediaRecorder.ondataavailable = (event) => {
					//this.$message.success("录制完成");
					// console.log(event.data, 'data')
					// 尝试转换为mp4类型
					const blob = event.data.slice(0, event.data.size, "video/mp4");
					this.url = URL.createObjectURL(blob);
					this.videoblob = blob;
					console.log(event.data, 'url')
					// const file = new window.File([blob], "videoss.mp4", {
					//     type: 'video/mp4',
					// });
					// console.log(file, 'file')
				};
			},
		},
		computed: {
			params() {
				return this.paramsFn();
			},
			goodsId() {
				return this.params.goodsId;
			},
		},
		components: {
			PopupPhoto,
		},
		watch: {
			visible(val) {
				if (val) {
					this.takePhTips()//this.openCamera();
				} else {
					this.closeCamera();
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.btnSet {
		width: 440rpx;
		height: 80rpx;
		background: #007aff;
		border-radius: 40rpx;
		color: #ffffff;
		font-size: 28rpx;
		line-height: 80rpx;
	}

	.photoBox {
		width: 100%;

		.photoTop {
			width: 100%;
			height: 74rpx;
			border-radius: 20px 20px 0px 0px;
			background-color: #ffffff;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0rpx 38rpx;

			.centersq {
				color: #333;
				font-size: 30rpx;
				font-weight: 500;
			}
		}

		.photoCenter {
			width: 750rpx;
			height: 75vh;
			position: relative;

			.center_camera {
				width: 100%;
				height: 75vh;
				position: fixed;
				background-color: rgba(0, 0, 0, .8);

				.head_take {
					width: 100%;
					height: 75vh;
					display: flex;
					flex-direction: column;
				}

				.headTake_up {
					width: 100%;
					height: 100rpx;
				}

				.headTake_minddle {
					display: flex;

					.min_img {
						width: 500rpx;
						height: 550rpx;
					}

					.min_left,
					.min_right {
						flex: 1;
						height: 550rpx;
					}
				}

				.headTake_down {
					width: 100%;
					flex: 1;
				}

				.color {
					background-color: #333;
					opacity: 0.5;
				}

				.photo_v {
					display: block;
					margin: 0 auto;
					width: 400px;
					height: 400px;
				}

				.photo_v2 {
					display: block;
					margin: 0 auto;
					width: 400px;
					height: 400px;
				}

				.mask {
					width: 500rpx;
					height: 550rpx;
					position: absolute;
					top: 100rpx;
					left: 0;
					right: 0;
					bottom: 0;
					margin: 0 auto;
					box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.4);
				}
			}

			.custom {
				width: 750rpx;
				height: 75vh;
				position: absolute;
				z-index: 1000;
				top: 0;
				left: 0;
				background-color: rgba(0, 0, 0, .8);

				image {
					display: block;
					margin: 0 auto;
					width: 400px;
					height: 400px;
				}
			}
		}

		.btns {
			display: flex;

			.takePhoto_btn {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				background: #a9a7a9;
				padding: 40rpx 26rpx;

				.middle_btn {
					width: 120rpx;
					height: 120rpx;
					border-radius: 40rpx;
					border: 4rpx solid #ffffff;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.square {
					width: 96rpx;
					height: 96rpx;
					background: #ffffff;
					border-radius: 28rpx;
				}

				.rights {
					font-size: 32rpx;
					font-weight: 500;
					color: #ffffff;
				}
			}

			.btnResult {
				height: 100rpx;
				flex: 1;
				background-color: #07c160;
				text-align: center;
				line-height: 100rpx;
				color: #fff;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}

	.popup_box {
		width: 100%;
		height: 1100rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
		padding: 0rpx 40rpx;

		.photo_head {
			width: 240rpx;
			height: 240rpx;
			margin: 80rpx 0rpx 48rpx;
		}

		.warn {
			width: 100%;
			font-size: 36rpx;
			font-weight: bold;
			color: #222222;
			margin-bottom: 40rpx;
		}

		.words {
			font-size: 28rpx;
			color: #666666;
			line-height: 33rpx;
			margin-bottom: 24rpx;
		}

		.take_photo {
			width: 412rpx;
			height: 84rpx;
			line-height: 84rpx;
			text-align: center;
			background: #01C65A;
			border-radius: 16rpx;
			font-size: 36rpx;
			font-weight: 500;
			color: #FFFFFF;
			margin-top: 100rpx;
		}
	}
</style>