<template>
  <div class="svgaplayer-comp">
    <el-popover
      v-model="visible"
      trigger="hover"
    >
      <div v-if="urlType === 'svga'" ref="svgaplayer" v-loading="loading" class="svgaplayer" :style="{'width':width,'height':height }" />
      <img v-else :style="{'width':width,'height':height }" :src="url" alt="">
      <el-button slot="reference" type="text" :disabled="!url">
        <i class="el-icon-video-camera-solid" :style="{'font-size': iconSize }" />
      </el-button>
    </el-popover>
  </div>
</template>
<script>
import SVGA from 'svgaplayerweb'

export default {
  props: {
    url: {
      type: String,
      require: true,
      default: ''
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    iconSize: {
      type: String,
      default: '16px'
    }
  },
  data() {
    return {
      loading: true,
      visible: false,
      urlType: ''
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal === true) {
          this.renderSvga()
        }
      },
      immediate: true
    }
  },
  methods: {
    renderSvga() {
      const that = this
      if (!that.visible) {
        return
      }
      that.loading = true
      const urlType = this.url.split('.')
      that.urlType = urlType[urlType.length - 1]
      if (that.urlType !== 'svga') {
        return
      }
      that.$nextTick(() => {
        const player = new SVGA.Player(that.$refs.svgaplayer)
        const parser = new SVGA.Parser(that.$refs.svgaplayer)
        parser.load(that.url, function(videoItem) {
          that.loading = false
          player.setVideoItem(videoItem)
          player.startAnimation()
        })
      })
    }
  }
}
</script>
<style scoped>
 .svgaplayer {
    margin:  auto;
 }
</style>
