<template>
  <el-dialog
    v-model="dialogVisible"
    title="资产二维码"
    width="400px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="asset" class="qrcode-container">
      <div class="qrcode-image">
        <img v-if="qrcodeUrl" :src="qrcodeUrl" alt="资产二维码" />
        <el-skeleton v-else :loading="true" animated />
      </div>
      <div class="asset-info">
        <p class="asset-code">{{ asset.assetCode }}</p>
        <p class="asset-name">{{ asset.assetName }}</p>
      </div>
      <div class="actions">
        <el-button type="primary" @click="handleDownload">
          下载二维码
        </el-button>
        <el-button @click="handlePrint">
          打印
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import QRCode from 'qrcode'

interface Props {
  modelValue: boolean
  asset: any
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const qrcodeUrl = computed(() => {
  if (!props.asset) return ''
  // 生成二维码URL
  return `${window.location.origin}/scan/${props.asset.assetCode}`
})

// 下载二维码
const handleDownload = async () => {
  if (!props.asset) return

  try {
    const canvas = document.createElement('canvas')
    await QRCode.toCanvas(canvas, props.asset.assetCode, {
      width: 300,
      margin: 2
    })

    const url = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.href = url
    link.download = `${props.asset.assetCode}.png`
    link.click()

    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 打印
const handlePrint = () => {
  ElMessage.info('打印功能开发中')
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}
</script>

<style scoped lang="scss">
.qrcode-container {
  text-align: center;
  padding: 20px 0;

  .qrcode-image {
    display: inline-block;
    padding: 20px;
    background: white;
    border-radius: $border-radius-large;
    box-shadow: $box-shadow-base;
    margin-bottom: 20px;

    img {
      width: 200px;
      height: 200px;
      display: block;
    }
  }

  .asset-info {
    margin-bottom: 20px;

    .asset-code {
      font-size: 18px;
      font-weight: 600;
      color: $text-primary;
      margin: 0 0 5px;
    }

    .asset-name {
      font-size: 14px;
      color: $text-secondary;
      margin: 0;
    }
  }

  .actions {
    display: flex;
    justify-content: center;
    gap: 10px;
  }
}
</style>
