<template>
  <!-- <el-image
    lazy
    style="width: 80px; height: 80px"
    :src="localUri && fileId ? localUri : img"
    @click="handlePreview(fileId)"
  /> -->
  <el-image
    lazy
    style="width: 80px; height: 80px"
    :src="localUri && fileId ? localUri : img"
    :fit="fit"
    @click="handlePreview(fileId)"
  />
</template>

<script>
import { fetchFileUrl, throttle, urlToBase64 } from '@/utils'

export default {
  name: 'PreviewImage',
  props: {
    uri: {
      type: String,
      default: ''
    },
    toyCoverUrl: {
      type: String,
      default: null
    },
    fileId: {
      type: String,
      default: ''
    },
    toBase: {
      type: Boolean,
      default: false
    },
    fit: {
      type: String,
      default: 'none'
    }
  },
  data() {
    const handlePreview = throttle(function(fileId) {
      this.onPreview(fileId)
    }, 1000)
    return {
      img: require('@/assets/images/empty/no-picture.svg'),
      localUri: null,
      handlePreview
    }
  },
  watch: {
    uri: {
      handler(val) {
        if (val) {
          const fileExtension = val ? val.split('.')[1] : null
          if (!this.toBase) {
            // urlToBase64(val, fileExtension, base64 => {
            //   this.localUri = base64
            //   console.error("base64:", base64)
            // })
            // 通过修改了转base64时，在onload中图片读取失败时，无法重新赋值导致仍使用旧数据的bug
            urlToBase64(val, fileExtension).then(base64 => {
              this.localUri = base64
            }).catch(err => {
              this.localUri = err
            })
          } else {
            this.localUri = val
          }
        } else {
          this.localUri = null
        }
      },
      immediate: true
    }
  },
  methods: {
    onPreview(fileId) {
      let srcList = []
      if (fileId) {
        fetchFileUrl(fileId, this.toyCoverUrl).then(data => {
          srcList = data && data.length > 0 ? data.map(item => item.url) : []
          let i = 0
          this.$viewerApi({
            images: srcList,
            options: {
              title: [1, (image, imageData) => {
                if (i === srcList.length) i = 0
                i++
                return `第${i}张 / 共${srcList.length}张 ${image.alt}`
              }]
            }
          })
        })
      }
    }
    // handlePreview(fileId) {
    //   if (fileId) throttle(this.onPreview(fileId), 1000)
    // }
  }
}
</script>

<style scoped lang="scss"></style>
