<script setup>
import { ref } from 'vue'
import defaultImg from '@/assets/cover.jpg'
import { QRDownload } from '@/api/information'

const dialogVisible = ref(false)
const imgUrl = ref('')
const nameValue = ref('')
const selectId = ref('')

const open = (id, url, name) => {
  selectId.value = id
  imgUrl.value = url
  nameValue.value = name
  dialogVisible.value = true
}

const download = async () => {
  try {
    await ElMessageBox.confirm('确认下载二维码?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info',
      center: true
    })
    await QRDownload(selectId.value, nameValue.value)
  } catch {
    // 用户取消操作
  }
}

defineExpose({ open })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="场地二维码"
    class="qr-preview-dialog"
    @close="imgUrl = ''"
  >
    <div class="image-container">
      <el-image
        :src="imgUrl || defaultImg"
        :preview-src-list="[imgUrl]"
        fit="contain"
        class="preview-image"
        hide-on-click-modal
      >
        <template #error>
          <div class="image-error">
            <el-icon :size="40"><Picture /></el-icon>
            <span>图片加载失败</span>
          </div>
        </template>
      </el-image>
    </div>

    <template #footer>
      <el-button type="primary" plain :disabled="!imgUrl" @click="download">
        <el-icon><Download /></el-icon>
        <span>下载二维码</span>
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.qr-preview-dialog {
  --dialog-max-width: min(90vw, 800px);
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  padding: 12px;
  border-radius: 8px;
  background: #f8f9fa;
  border: 1px solid #ebeef5;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  object-fit: contain;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  height: 200px;
  gap: 8px;
}

:deep(.el-dialog) {
  border-radius: 10px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(120deg, #e0f2ff 0%, #f0f7ff 100%);
  margin-right: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__title) {
  color: #1c3f6e;
  font-weight: 600;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}
</style>
