<template>
  <ElImageViewer
    v-if="visible"
    :url-list="[url]"
    :initial-index="0"
    hide-on-click-modal
    @close="handleClose"
  />
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { ElImageViewer } from 'element-plus'
  import { StorageService } from '@/api/modules'

  interface Props {
    fileKey?: string
  }

  const props = defineProps<Props>()

  const emit = defineEmits<{
    close: []
  }>()

  const visible = ref(false)
  const url = ref('')

  watch(
    () => props.fileKey,
    async (val) => {
      if (val) {
        url.value = ''
        try {
          const res = await StorageService.batchDownloadUrls({
            file_keys: [val]
          })
          if (res.code === 0 && res.data?.urls?.[val]) {
            url.value = res.data.urls[val]
            visible.value = true
          }
        } catch (error) {
          console.error('获取支付凭证失败:', error)
        }
      }
    },
    { immediate: true }
  )

  const handleClose = () => {
    visible.value = false
    url.value = ''
    emit('close')
  }
</script>
