<script setup>
import UQRCode from 'uqrcodejs';
import {onMounted, ref, onUnmounted} from 'vue';

const emits = defineEmits(['handleLongPress']);
const {bg, invite, member_url} = defineProps({
    bg: {
        type: String,
        default: null
    },
    invite: {
        type: String,
        default: null
    },
    member_url: {
        type: String,
        default: null
    },
});

const itemList = [
    {text: '置顶', type: 1},
    {text: '取消', type: 0},
]
const CanvasRef = ref();
const QRRef = ref();
let canvas = null;
let timer = null;
const imageSrc = ref(null);
onMounted(() => {
    const _canvas = CanvasRef.value.$el.children[0];
    const ctx = _canvas.getContext("2d");
    canvas = _canvas;
    draw(ctx, _canvas);
    timer = setInterval(() => {
        imageSrc.value = canvas.toDataURL('image/png')
    }, 1000)
});

onUnmounted(() => {
    clearInterval(timer);
})

const draw = (ctx, canvas) => {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.src = bg;
    img.onload = function () {
        ctx.drawImage(img, 0, 0, canvas.width / 3, canvas.height / 3);

        const qr = new UQRCode();
        qr.data = `${member_url}/pages/register/index?invite=${invite}`;
        qr.size = 200;
        qr.margin = 10;
        qr.make()
        const QRRefCanvas = QRRef.value.$el.children[0];
        qr.canvasContext = QRRefCanvas.getContext("2d");
        qr.drawCanvas().then(() => {
            const base64 = QRRefCanvas.toDataURL('image/png');
            const qr_img = new Image();
            qr_img.src = base64;
            qr_img.onload = function () {
                const size = 65;
                const x = 17.5;
                const y = canvas.height / 3 - 88 + 7;
                ctx.drawImage(qr_img, x, y, size, size);
            }
        });
    }
}
</script>

<template>
    <view class="!size-full relative">
        <canvas class="!absolute !size-[200px] opacity-0" ref="QRRef"></canvas>
        <canvas
            class="!size-full"
            ref="CanvasRef"/>
        <image class="!size-full !absolute z-50 left-0 top-0" :src="imageSrc"></image>
    </view>
</template>

<style scoped lang="scss">

</style>
