<template>
    <el-dialog v-model="visible" :title="dialogProps.title" width="20%" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="qrcode">
            <div class="qrimg-wrap" v-if="dialogProps.rawData.qrcode">
                <img class="qrimg" :src="dialogProps.rawData.qrcode" alt="二维码">
            </div>
            <div v-else class="placeholder"></div>
        </div>
        <template #footer>
            <span class="dialog-footer" v-if="!isDisabled">
                <el-button type="primary" @click="downloadImage(dialogProps.rawData.qrcode)">下载图片</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import type { DialogProps } from '../interface'

const visible = ref(false)
const dialogProps = ref<DialogProps>({
    title: '',
    rawData: {}
})

const isDisabled = computed(() => !dialogProps.value.rawData?.qrcode?.length)

function acceptParams(params: DialogProps) {
    dialogProps.value = params
    visible.value = true
}
/**生成二维码 */
async function generateQrcode() {
    const data = {
        page: "pages/index/index",
        scene: dialogProps.value.rawData.id,
        width: "250"
    }
    const qrcode = await dialogProps.value.api!(data)
    Object.assign(dialogProps.value.rawData, {
        qrcode
    })
}
/**下载图片 */
const downloadImage = (imageSrc: string) => {
    const image = new Image()
    image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context?.drawImage(image, 0, 0, image.width, image.height)
        const url = canvas.toDataURL(`image/jpeg`)
        const a = document.createElement('a')
        a.href = url
        a.download = '二维码'
        a.click()
    }
    image.src = imageSrc
}

watch(() => unref(visible), (newVal) => {
    if (newVal) {
        generateQrcode()
    }
})

defineExpose({
    acceptParams
})

</script>
<style lang="scss" scoped>
.qrcode {
    display: flex;
    justify-content: center;
    align-items: center;

    .qrimg-wrap {
        max-width: 280px;
        max-height: 280px;

        .qrimg {
            width: 100%;
            height: 100%;
            display: block;
        }
    }

    .placeholder {
        width: 100%;
        height: 280px;
        background-image: url('@/assets/images/cli-loading.gif');
        background-repeat: no-repeat;
        background-position: center;
    }
}
</style>