<script setup lang="ts">
import type { SchemeMediaProps }  from '@/request/model/scheme.model';
import type { ImagePreviewProps } from 'vant';


const { media = [] } = defineProps<{ media: SchemeMediaProps[] }>();

const images = computed(() => media?.filter(Boolean));

const preview = ref(false);
const previewProps = shallowRef<Partial<ImagePreviewProps>>();
const current = shallowRef<SchemeMediaProps>();

let Tag = `scheme-media-preview`;

function update(index: number) {
  current.value = images.value[ index ];
  setTimeout(() => {
    const swipe = document.querySelectorAll(`.${ Tag } .van-swipe-item`);
    const video = swipe[ index ]?.querySelector(`video`);
    onPlay(<any> { target: video });
  }, 200);
}

function handle(item: SchemeMediaProps) {
  const closable = !images.value.some(image => image.type === 'video');
  const index = images.value.findIndex(image => image.url === item.url);
  preview.value = true;
  previewProps.value = {
    images: images.value.map(item => item.url), startPosition: index,
    showIndex: images.value.length > 1,
    loop: false, closeable: true,
    closeOnClickImage: closable,
    closeOnClickOverlay: closable,
    className: Tag,
  };
  update(index);
}

function onPlay(event?: Event) {
  const video = event?.target as HTMLVideoElement;
  const pause = (el?: HTMLMediaElement) => {
    el && !el.paused && el !== video && el.pause();
  };

  document.querySelectorAll('video').forEach(pause);
  document.querySelectorAll('audio').forEach(pause);


  if ( video?.paused ) video.play();
}
</script>
<template>
  <div class="flex my-2 -mx-2 overflow-x-auto" v-if="media.length">
    <div class="flex-none mx-2" v-for="item in media" :key="item.title">
      <div v-if="item.url" class="relative h-32 rounded-lg	overflow-hidden" @click="handle(item)">
        <img class="size-full object-scale-down" v-if="item.poster" :src="item.poster" :alt="item.title" />
        <video class="size-full object-scale-down" v-else-if="item.type === 'video'" :src="item.url" preload="metadata"></video>
        <div class="size-full object-scale-down w-64 bg-gray-600" v-else></div>
        <van-icon class="play" v-if="item.type === 'video'" name="play-circle-o" />
      </div>
      <template v-if="item.title">
        <div v-if="item.type === 'text'" class="text-lg text-primary">{{ item.title }}</div>
        <div v-else class="mt-1 text-xs">{{ item.title }}</div>
      </template>
    </div>
    <van-image-preview v-model:show="preview" v-bind="previewProps" @closed="current=void 0" @change="update">
      <template v-slot:index="{index}">
        <span>{{ images[ index ]?.title }}</span>
        <span v-if="previewProps?.showIndex">({{ index + 1 }} / {{ images?.length }})</span>
      </template>
      <template #image="{  src, style, onLoad }">
        <img v-if="current?.type === 'image'" :style="[{ width: '100%' }, style]" :src="src"
             alt="" @load="onLoad"
        />
        <video v-else-if="current?.type === 'video'" :style="[{ width: '100%' }, style]"
               :poster="current?.poster"
               controls controlslist="nodownload" disablepictureinpicture
               playsinline webkit-playsinline @play="onPlay"
        >
          <source :src="src" />
        </video>
      </template>
    </van-image-preview>
  </div>
</template>
<style scoped lang="scss">
.play {
  font-size: 36px;
  position: absolute !important;
  right: 5px;
  bottom: 5px;
}

.overflow-x-auto {
  overflow-y: hidden;
  /* 只允许水平滚动，垂直滚动传递给父元素 */
  touch-action: pan-x pan-y;
  /* 改善移动端滚动体验（iOS Safari） */
  -webkit-overflow-scrolling: touch;
}
</style>
