<template>
  <Dialog title="设备二维码" v-model="dialogVisible" top="5vh">
    <div class="qr_img_box" v-loading="loading">
      <img v-if="qrUrl" :src="qrUrl" class="qr_image" /> <div v-else>生成失败</div></div
    >
    <div class="btn_box" v-if="qrUrl">
      <el-button type="primary" @click="downloadBase64Image(qrUrl, qrFileName)"
        >下载二维码</el-button
      >
    </div>
    <!-- <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template> -->
  </Dialog>
</template>
<script setup>
import { InfoApi } from '@/api/device/info'
const dialogVisible = ref(false) // 弹窗的是否展示
const qrUrl = ref()
const qrFileName = ref('设备')
const loading = ref(true)

/** 打开弹窗 */
const open = async (id, fileName) => {
  dialogVisible.value = true
  qrFileName.value = fileName
  try {
    let obj = {
      deviceId: id
    }
    const res = await InfoApi.getDeviceInfoQr(obj)
    // console.log(res)
    qrUrl.value = res.qr
  } finally {
    loading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const downloadBase64Image = (base64Url, fileName) => {
  // 分离Base64数据部分（去掉前缀）
  const base64Data = base64Url.replace(/^data:image\/\w+;base64,/, '')

  // 解码Base64字符串
  const byteCharacters = atob(base64Data)
  const byteNumbers = new Array(byteCharacters.length)

  // 转换为字节数组
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  const byteArray = new Uint8Array(byteNumbers)
  // 创建Blob对象（根据实际图片类型调整MIME类型）
  const blob = new Blob([byteArray], { type: 'image/png' })
  // 生成下载URL
  const url = URL.createObjectURL(blob)
  // 创建下载链接
  const a = document.createElement('a')
  a.href = url
  a.download = fileName || 'downloaded_image.png' // 默认文件名
  // 触发下载
  document.body.appendChild(a)
  a.click()

  // 清理
  setTimeout(() => {
    document.body.removeChild(a)
    URL.revokeObjectURL(url) // 释放内存
  }, 100)
}

// 使用示例
//const base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z/C/HgAGgwJ/lK3Q6wAAAABJRU5ErkJggg==';
// downloadBase64Image(qrUrl.value, 'my_custom_image.png')
</script>
<style scoped lang="less">
.qr_img_box {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  .qr_image {
  }
}
.btn_box {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
