<template>
  <div class="wrap environment-photo-wrap">
    <div v-if="loaded && photoList.length === 0" class="empty-tip">暂无环境照片</div>
    <div v-for="(item, index) in photoList" :key="index" class="photo-item">
      <div class="media-wrap">
        <video
          v-if="item.tag && item.tag.includes('video')"
          :src="item.imageUrl"
          controls
          playsinline
          class="media"
        />
        <img
          v-else-if="item.tag && item.tag.includes('img')"
          :src="item.imageUrl"
          class="media"
          @click="previewImage(index)"
        />
      </div>
      <p v-if="item.title" class="photo-name">{{ item.title }}</p>
    </div>
  </div>
</template>

<script>
import { Toast, ImagePreview } from 'vant'
import { getBeforeDispatchImage } from '@/api/environmentPhoto'

export default {
  name: 'EnvironmentPhotoList',
  data() {
    return {
      photoList: [],
      loaded: false
    }
  },
  async mounted() {
    await this.fetchPhotos()
  },
  methods: {
    async fetchPhotos() {
      const userOrderId = this.$route.query.userOrderId
      if (!userOrderId) {
        Toast('缺少必要参数')
        this.loaded = true
        return
      }
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const res = await getBeforeDispatchImage({ userOrderId: Number(userOrderId) })
        this.photoList = Array.isArray(res.data) ? res.data : []
      } finally {
        Toast.clear()
        this.loaded = true
      }
    },
    previewImage(index) {
      const urls = this.photoList
        .filter(item => item.tag && item.tag.includes('img'))
        .map(item => item.imageUrl)
      ImagePreview({ images: urls, startPosition: index })
    }
  }
}
</script>

<style scoped>.wrap {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #F4F5F7;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.environment-photo-wrap {
  padding: 12px;
}
.empty-tip {
  text-align: center;
  color: #999;
  margin-top: 60px;
  font-size: 14px;
}
.photo-item {
  background: #fff;
  border-radius: 6px;
  margin-bottom: 12px;
  overflow: hidden;
}
.media-wrap {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}
.photo-item img,
.photo-item video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}
.photo-name {
  font-size: 13px;
  color: #333;
  padding: 8px 10px;
  margin: 0;
}
</style>
