<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>
				<camera v-show="showConfirmBtn" class="camera" device-position="back" flash="off" @initdone="onVideoSuccess"
					style="width:100%; height: 320rpx;"></camera>
			</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);
	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 = '摄像头正在初始化...'
		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>