import { ref } from 'vue'

/**
 * 处理相机函数
 */
export function useCameraManager() {
	
	const isShowCamera = ref(false) // 摄像头显/隐
	const isShowCameraDelayed = ref(false) // 控制摄像头打开后ui
	const cameraContext = ref(null) // 摄像头方法
	const cameraListener = ref(null) // 摄像头监听对象
	const zoomTimer = ref("") // 变焦定时器

	const startCamera = () => {
		isShowCamera.value = true // 显示摄像头
		cameraContext.value = uni.createCameraContext() // 创建摄像头上下文
		console.log('摄像头实例:', cameraContext.value)
		
		// 延迟显示
		setTimeout(() => {
			if(isShowCamera.value){  //判断摄像头为打开状态时才打开提示弹窗（防止扫码后又弹出提示弹窗）
				isShowCameraDelayed.value = true
			}
		}, 2500)
	}

	// 关闭摄像头
	const stopCamera = () => {
		cameraListener.value?.stop() 
		setIsShowCamera(false)
	}
	
	// 清理摄像头资源
	const cleanupCamera = () => {
		
		stopCamera() // 停止摄像头
		
		if (zoomTimer.value) {
			clearTimeout(zoomTimer.value)
			zoomTimer.value = null
		}
		cameraContext.value = null
	}

	// 控制摄像头显隐
	const setIsShowCamera = (state) => {
		isShowCamera.value = state
		if (state === true) {
			setTimeout(() => {
				isShowCameraDelayed.value = state
			}, 2500)
		} else {
			isShowCameraDelayed.value = state
		}
	}


	return {
		isShowCamera,
		isShowCameraDelayed,
		cameraContext,
		cameraListener,
		startCamera,
		stopCamera,
		setIsShowCamera,
		cleanupCamera,
		zoomTimer
	}
}