<script setup lang="ts">
// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error

import UQRCode from 'uqrcodejs'

const props = defineProps<{ text: string, qwidth: number, qrKey: string }>()
const _this = getCurrentInstance()
function createQRCode() {
  const qr = new UQRCode()
  qr.data = props.text
  qr.size = props.qwidth || 100 // 这里是px，和下面的不匹配
  qr.make()
  const canvasContext = uni.createCanvasContext(props.qrKey, _this)
  qr.canvasContext = canvasContext
  qr.drawCanvas()
}
createQRCode()

async function downloadQrcode() {
  try {
    // 1. 先确保二维码已绘制完成（短暂延迟，兼容绘制异步性）
    await new Promise(resolve => setTimeout(resolve, 300))

    // 2. 将Canvas转为临时文件路径（复用原有canvas-id）
    const tempRes: any = await uni.canvasToTempFilePath({
      canvasId: props.qrKey, // 与原有Canvas的canvas-id保持一致
      width: props.qwidth,
      height: props.qwidth,
      destWidth: props.qwidth * 2, // 生成高清图
      destHeight: props.qwidth * 2,
      fileType: 'png',
    }, _this)

    // 3. 分端处理下载/保存逻辑
    const systemInfo = uni.getSystemInfoSync()
    if (systemInfo.platform === 'h5') {
      // H5端：浏览器下载
      const link = document.createElement('a')
      link.href = tempRes.tempFilePath
      link.download = `二维码_${Date.now()}.png`
      link.click()
      uni.showToast({ title: '二维码下载成功' })
    }
    else {
      // 小程序/APP端：保存到相册（处理授权）
      // 检查授权状态
      const settingRes = await uni.getSetting({})
      if (!settingRes.authSetting['scope.writePhotosAlbum']) {
        // 未授权则请求授权
        try {
          await uni.authorize({ scope: 'scope.writePhotosAlbum' })
        }
        catch {
          uni.showToast({ title: '需授权保存相册才能下载', icon: 'none' })
          return
        }
      }

      // 保存到系统相册
      await uni.saveImageToPhotosAlbum({
        filePath: tempRes.tempFilePath,
      })
      uni.showToast({ title: '二维码已保存到相册' })
    }
  }
  catch (err) {
    // const errMsg = (err as any).errMsg
    uni.showToast({ title: `下载失败`, icon: 'none' })
    console.error('二维码下载失败：', err)
  }
}

defineExpose({
  downloadQrcode,
})
</script>

<template>
  <canvas :id="qrKey" :canvas-id="qrKey" :style="{ width: `${props.qwidth}px`, height: `${props.qwidth}px` }" />
</template>

<style scoped>

</style>
