<template>
		<view v-show="!showConfirmBtn" class="sxt-tip-box">{{textMess}}</view>
		<camera v-show="showConfirmBtn" class="zp-camera" device-position="front" flash="off" @initdone="onVideoSuccess"></camera>
</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);
	const cameraContext = ref(null);

	let zhuapaiFun = null;
	let stopCamera = null;
	let errorFunCompleteFn = null;
	const textMess = ref('摄像头正在初始化...')

	function startCamera() {
		// 请求摄像头权限并获取流
		cameraContext.value = uni.createCameraContext();
	}

	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 = '摄像头正在初始化...'
		setTimeout(() => {
			showConfirmBtn.value = true;
			nextTick(() => {
				startCamera()
			})
		},1000)
	}

	function handleClose() {
		emits('cancel')
		stopCamera && stopCamera()
	}

	function handleConfirm() {
		emits('success')
		stopCamera && stopCamera()
	}

	defineExpose({
		showDialog
	})

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