import {Html5Qrcode, Html5QrcodeScanner, Html5QrcodeScanType, Html5QrcodeSupportedFormats} from "html5-qrcode";

export const useScanCode = (elementId) => {
    const router = useRouter()

    let scanInstance = null; // 扫码实例
    let results = ref(null); // 扫码结果

    const initScanInstance = () => {
        if(!elementId) throw error('请传入放置扫码功能的元素ID')
        if (!scanInstance) {
            // reader放置扫码功能的元素ID
            scanInstance = new Html5Qrcode(elementId, {
                formatsToSupport: [
                    Html5QrcodeSupportedFormats.QR_CODE,
                ],
            })
        }
    }
    const openQrcode = async () => {
        Html5Qrcode.getCameras()
            .then(devices => {
                if (devices && devices.length) {// 当前环境下能识别出摄像头，并且摄像头的数据可能不止一个
                    initScanInstance()

                    // isShow.value = true
                    scanInstance.start(
                        {facingMode: "environment"},
                        {
                            focusMode: 'continuous',
                            fps: 1, // 可选，每n秒帧扫描一次
                            qrbox: { // 扫描的UI框
                                width: 250,
                                height: 250
                            },
                            videoConstraints: {
                                // width: 375,
                                // height: (window.visualViewport.height - 50),
                                aspectRatio: window.visualViewport.height / window.visualViewport.width,
                                facingMode: "environment",
                            }
                        },
                        (decodedText, decodedResult) => {
                            showToast('识别成功')
                            // 扫描结果
                            results.value = {
                                decodedText,
                                decodedResult
                            }
                            // scanInstance.stop()
                        },
                        (errorMessage, error) => {
                            closeQrcode(errorMessage)
                        }
                    )
                }
            })
            .catch((err) => {
                // 错误信息处理仅供参考，具体情况看输出！！！
                let errorStr = ''
                if (typeof err === "string") {
                    errorStr = err
                } else {
                    if (err.name === "NotAllowedError")
                        errorStr = "您需要授予相机访问权限"
                    if (err.name === "NotFoundError") {
                        errorStr = "未检测到摄像头"
                    }
                    if (err.name === "NotSupportedError")
                        errorStr = "摄像头访问只支持在安全的上下文中，如https或localhost"
                    if (err.name === "NotReadableError") errorStr = "摄像头被占用"
                    if (err.name === "OverconstrainedError")
                        errorStr = "安装摄像头不合适"
                    if (err.name === "StreamApiNotSupportedError")
                        errorStr = "此浏览器不支持流API"
                }
                showToast(errorStr)
                closeQrcode()
            })
    }

    const closeQrcode = () => {
        // if (scanInstance) scanInstance.stop()
        console.log(router, 'router')
        router.back()
    }


    onMounted(() => {
        initScanInstance()
        openQrcode()
    })
    onUnmounted(() => {
        if (scanInstance) scanInstance.stop()
    })

    return {
        results,
        closeQrcode
    }
}