<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="摄像头确认" :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;">摄像头正在初始化...</view>
				<video v-show="showConfirmBtn" ref="videoRef" style="width:100%; height: 320rpx;" id="videoConfirm"
					:controls="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"
	
	const emits = defineEmits(['success', 'error', 'cancel'])
	
	const popupRef = ref(null)
	const showConfirmBtn = ref(false);
	
	let zhuapaiFun = null;
	let stopCamera = null;

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

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

	function handleZhua() {
		zhuapaiFun()
	}


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

	function onVideoError() {
		showConfirmBtn.false = true;
		emits('error')
	}

	function showDialog() {
		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.uni-border-left {
    .uni-dialog-button-text.uni-button-color {
      color: #3fd2a1;
    }
  }
</style>