<template>
  <div v-show="modelValue">
    <template v-if="type == 'image'">
      <el-image-viewer
        v-if="previewLists.length"
        :url-list="previewLists"
        :initial-index="props.index"
        hide-on-click-modal
        @close="handleClose"
      />
    </template>
    <template v-else-if="type == 'video'">
      <popup customClass="pb-6" v-model="showDialog" :width="width" title="视频预览" :show-footer="false">
        <video class="size-full" controls v-if="previewLists.length" autoplay>
          <source :src="previewLists[0]" type="video/mp4" />
        </video>
      </popup>
    </template>
  </div>
</template>

<script setup lang="ts">
// 定义组件属性
const props = withDefaults(
  defineProps<{
    modelValue: boolean
    url: string | string[]
    index?: number
    type?: string
    width?: string
  }>(),
  {
    modelValue: false,
    url: '',
    index: 0,
    type: 'image',
    width: '700px'
  }
)
// 定义组件事件
const emit = defineEmits<{
  (event: 'update:modelValue', value: boolean): void
}>()
// 对话框可见性
const showDialog = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
// 预览列表
const previewLists = ref<any[]>([])
// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      previewLists.value = Array.isArray(props.url) ? props.url : [props.url]
    } else {
      previewLists.value = []
    }
  }
)
</script>
