<template>
  <div class="preview-img-list" v-show="false">
    <img
      class="preview-img-item"
      v-for="item in imageViewerData"
      :src="item.src"
      :key="item.id"
      :id="item.id"
    >
  </div>
</template>
<script>
export default {
  props: {
    images: {
      type: Array,
      required: true,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      imageViewerData: []
    }
  },
  watch: {
    images: 'initImageViewerData'
  },
  methods: {
    initImageViewerData() {
    // console.log('initImageViewerData......')
      this.imageViewerData = []
      let tempData = []
      for (let item of this.images) {
        if (!item.imageSrc) {
          continue
        }
        let obj = { id: item.name, src: item.imageSrc }
        let img = new Image()
        img.src = item.imageSrc
        img.onerror = _ => {
          Object.assign(obj, { w: 120, h: 95, src: 'assets/images/picture404-' + Math.floor(Math.random() * 4) + '.png' })
        }
        if (img.complete) {
          Object.assign(obj, { w: img.width, h: img.height })
        } else {
          img.onload = _ => {
            Object.assign(obj, { w: img.width, h: img.height })
          }
        }
        tempData.push(obj)
      }
      this.imageViewerData = [...tempData]
    },

    openImg(id) {
      if (id) {
        let index = this.imageViewerData.findIndex(item => item.id === id)
        if (index < 0) {
          this.$message({ message: '图片不存在 ！', type: 'error' })
          return
        }
        let img = this.imageViewerData[index]
        if (!img.w || !img.h) {
          this.$message({ message: '获取图片宽高失败，暂无法查看 ！', type: 'error' })
          return
        }
        this.$photoswipe.open(index, this.imageViewerData)
      }
    }
  }
}
</script>
