<template>
  <!-- 预览图片 -->
  <teleport v-if="baseData.showImageViewer" to="body">
    <div v-myPreventEvent>
      <el-image-viewer hideOnClickModal :zIndex="999999" :initialIndex="baseData.initialIndex" :urlList="baseData.urlList" @close="hide()"></el-image-viewer>
    </div>
  </teleport>
</template>

<script setup lang="ts">
  import { ElImageViewer } from 'element-plus';
  import type { PropType } from 'vue';

  const props = defineProps({
    /** 图片路径数组 */
    images: { type: Array as PropType<string[]>, default: () => [] },
  });

  const baseData = reactive({
    showImageViewer: false,
    urlList: props.images,
    initialIndex: 0,
  });

  /**
   * 显示
   */
  function show(images: string[], initialIndex: number) {
    baseData.urlList = images;
    baseData.initialIndex = initialIndex;
    baseData.showImageViewer = true;
  }

  /**
   * 隐藏
   */
  function hide() {
    baseData.showImageViewer = false;
  }

  /** 用于阻止冒泡事件 */
  function preventEventFun(event: Event) {
    event.stopPropagation && event.stopPropagation();
    event.preventDefault && event.preventDefault();
    if (event.type === 'keyup') {
      baseData.showImageViewer = false;
    }
  }

  /** 自定义指令 用于阻止弹窗被关闭(bubble-base-bubble点击外部关闭导致跟着一起销毁了 ) */
  const vMyPreventEvent = {
    mounted(el: HTMLElement) {
      el.addEventListener('mousedown', preventEventFun, false);
      el.addEventListener('keyup', preventEventFun, false);
      el.addEventListener('keydown', preventEventFun, false);
      el.addEventListener('click', preventEventFun, false);
    },
    unmounted(el: HTMLElement) {
      el.removeEventListener('mousedown', preventEventFun);
      el.removeEventListener('keyup', preventEventFun);
      el.removeEventListener('keydown', preventEventFun);
      el.removeEventListener('click', preventEventFun);
    },
  };
  defineExpose({ hide, show });
</script>
