<template>
  <div class="audio-wrapper">
    <span class="audio-play" @click="playAudio">
      <SvgIcon :size="audio.paused ? 20 : 14" :icon-class="iconClass" />
    </span>
    <audio ref="audio" :src="url" preload="metadata"></audio>
  </div>
</template>

<script>
import { GetFileURLMap } from '@/api/app';

export default {
  name: 'AudioPlay',
  props: {
    fileId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      url: '',
      audio: {
        paused: true
      }
    };
  },
  computed: {
    iconClass() {
      return this.audio.paused ? 'audio' : 'audio-stop';
    }
  },
  watch: {
    fileId: {
      handler(val) {
        if (!val) return;
        GetFileURLMap({ file_id_list: [val] }).then(({ url_map }) => {
          this.url = url_map[val];
        });
      },
      immediate: true
    }
  },
  mounted() {
    this.$refs.audio.addEventListener('ended', () => {
      this.audio.paused = true;
    });
    this.$refs.audio.addEventListener('pause', () => {
      this.audio.paused = true;
    });
    this.$refs.audio.addEventListener('play', () => {
      this.audio.paused = false;
    });
  },
  methods: {
    playAudio() {
      const audio = this.$refs.audio;
      audio.paused ? audio.play() : audio.pause();
    }
  }
};
</script>

<style lang="scss" scoped>
.audio-wrapper {
  .audio-play {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    cursor: pointer;
    background-color: $main-color;
    border-radius: 50%;
  }
}
</style>
