<template>
	<uni-popup ref="popupRef" type="dialog" :animation="false" :is-mask-click="false"
		mask-background-color="rgba(0, 0, 0, 0.4);">
		<uni-popup-dialog mode="input" class="phone-camera my-dialog-cc" :title="title" :duration="2000" :before-close="true"
			@close="handleClose" @confirm="handleConfirm">
			<view class="phone-camera-box" style="overflow: hidden;">
				<view v-show="!showConfirmBtn" class="sxt-tip-box" style="text-align: center;">{{textMess}}</view>
				<video v-show="showConfirmBtn" ref="videoRef" style="width:100%; height: 320rpx;" id="videoConfirm"
					:controls="false" :enable-progress-gesture="false"></video>
					
				<!-- 隐藏抓拍绘制图片 -->
				<canvas id="canvasConfirm" style="width: auto; height: 320rpx;visibility: hidden;position: absolute;"></canvas>
				<!-- <canvas id="canvasConfirm" style="width: auto; height: 320rpx;"></canvas> -->
				<!-- 测试抓拍使用 -->
				<!-- <button @click="handleZhua">抓拍</button> -->
			</view>
		</uni-popup-dialog>
	</uni-popup>
</template>

<script setup>
	import {
		ref,
		onUnmounted,
		onMounted,
		nextTick
	} from "vue"
	import {
		useH5Camera
	} from "./useCamera.js"
	
	defineProps({
		title: {
			type: String,
			default: '摄像头确认'
		}
	})
	
	const emits = defineEmits(['success', 'error', 'cancel'])
	
	const popupRef = ref(null)
	const showConfirmBtn = ref(false);
	
	let zhuapaiFun = null;
	let stopCamera = null;
	let errorFunCompleteFn = null;
	const textMess = ref('摄像头正在初始化...')

	function startCamera() {
		// 请求摄像头权限并获取流
		// #ifdef H5
		console.log('navigator', navigator)
		const {
			startH5Camera,
			handlePaiZhao,
			stopH5Camera,
			errorFunComplete
		} = useH5Camera({
			elVideoId: '#videoConfirm',
			elCanvasId: '#canvasConfirm',
			onVideoSuccess,
			onVideoError
		})
		startH5Camera();
		zhuapaiFun = handlePaiZhao;
		stopCamera = stopH5Camera;
		errorFunCompleteFn = errorFunComplete;
		// #endif

		// #ifdef APP-PLUS
		console.log('App端暂时不支持摄像头功能')
		// #endif
	}

	function handleZhua() {
		zhuapaiFun()
	}


	function onVideoSuccess() {
		showConfirmBtn.value = true;
	}

	function onVideoError(e) {
		showConfirmBtn.false = true;
		textMess.value = '摄像头初始化失败!'
		emits('error')
		errorFunCompleteFn && errorFunCompleteFn(e)
	}

	function showDialog() {
		textMess.value = '摄像头正在初始化...'
		popupRef.value.open();
		nextTick(() => {
			startCamera()
		})
	}

	function handleClose() {
		emits('cancel')
		popupRef.value.close();
		stopCamera && stopCamera()
	}

	function handleConfirm() {
		emits('success')
		popupRef.value.close();
		stopCamera && stopCamera()
	}

	defineExpose({
		showDialog
	})

	onUnmounted(() => {
		// 组件销毁时停止摄像头
		stopCamera && stopCamera();
	})
</script>

<style lang="scss">
	.phone-camera-box {
		width: 100%;
	}

	.uni-video-container {
		width: 100%;
	}

	.uni-video-video {
		width: 100%;
	}

  .my-dialog-cc .uni-dialog-button-group .uni-border-left .uni-button-color{
      color: #3fd2a1;
  }
</style>