<template>
    <div class="app-qrcode-scan">
        <div @click="scan">
            <slot>
                <Button type="primary">扫一扫</Button>
            </slot>
        </div>
        <div id="camera" class="app-qrcode-scan__camera"></div>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, shallowRef } from 'vue'
import { Button, Toast } from 'vant'
import { Html5Qrcode } from 'html5-qrcode'
import plus from '@/utils/h5plus'

const emit = defineEmits(['success'])
const html5QrCode = shallowRef<Html5Qrcode>()
const showCamera = shallowRef(false)

const scan = () => {
    plus.onPlusReady((plus) => {
        const barcode = plus.barcode.create('barcode', [plus.barcode.QR], {
            background: '#fff',
            frameColor: '#07c160',
            scanbarColor: '#07c160',
            top: '100px',
            left: '0px',
            width: '100%',
            height: '580px',
            position: 'static'
        });
        barcode.onmarked = (type: any, result: any) => {
            console.log('扫码成功', type, result)
            emit('success', result)
            barcode.close()
        }
        barcode.onerror = (err: any) => {
            console.log('扫码失败', err)
            Toast.fail('扫码失败')
        }
        plus.webview.currentWebview().append(barcode);//必要的
    })
}

const onScan = () => {
    Html5Qrcode.getCameras().then(devices => {
        if (devices && devices.length) {
            html5QrCode.value?.start(
                {
                    facingMode: 'environment'
                },
                {
                    fps: 10,
                    qrbox: { width: 250, height: 250 }
                },
                (decodedText) => {
                    emit('success', decodedText)
                },
                (err) => {
                    console.log('html5QrCode', err)
                }).catch(() => {
                    Toast.fail('获取设备信息失败')
                })
        }
    }).catch(() => {
        Toast.fail('您需要授予相机访问权限')
    })
}

onMounted(() => {
    html5QrCode.value = new Html5Qrcode('camera')
})
</script>

<style lang="less" scoped>
@import './index.less';
</style>