<script lang="ts" setup>
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import axios from 'axios'

defineOptions({ name: 'ImageViewer' })

const props = defineProps({
  urlList: {
    type: Array as PropType<string[]>,
    default: (): string[] => []
  },
  zIndex: propTypes.number.def(200),
  initialIndex: propTypes.number.def(0),
  infinite: propTypes.bool.def(true),
  hideOnClickModal: propTypes.bool.def(false),
  teleported: propTypes.bool.def(false),
  show: propTypes.bool.def(false),
  headers: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  }
})

const imageUrls = ref<string[]>([])

// 加载图片，如果需要 headers，则通过 axios 获取 blob
const loadImages = async () => {
  if (props.headers && Object.keys(props.headers).length > 0) {
    // 如果有 headers，使用 axios 下载图片
    const promises = props.urlList.map(async (url) => {
      try {
        const response = await axios.get(url, {
          headers: props.headers,
          responseType: 'blob'
        })
        // 创建 blob URL
        return URL.createObjectURL(response.data)
      } catch (error) {
        console.error('图片加载失败:', url, error)
        return url // 失败时返回原 URL
      }
    })
    imageUrls.value = await Promise.all(promises)
  } else {
    // 如果没有 headers，直接使用原 URL
    imageUrls.value = [...props.urlList]
  }
}

const getBindValue = computed(() => {
  const propsData: Recordable = { ...props }
  delete propsData.show
  delete propsData.headers
  return propsData
})

const show = ref(props.show)

const close = () => {
  // 清理 blob URLs
  imageUrls.value.forEach((url) => {
    if (url.startsWith('blob:')) {
      URL.revokeObjectURL(url)
    }
  })
  show.value = false
}

// 初始化加载图片
loadImages()
</script>

<template>
  <ElImageViewer v-if="show" v-bind="{ ...getBindValue, urlList: imageUrls }" @close="close" />
</template>
