<template>
  <div class="audio-wrapper">
    <span :class="[url ? 'audio-play' : 'audio-play not-url']" @click="playAudio">
      <SvgIcon v-if="audio.paused" :size="audio.paused ? 20 : 14" :icon-class="iconClass" />
      <img
        v-else
        :src="
          themeColor === 'gray'
            ? require('../../../../../assets/voice-play-gray.png')
            : require('../../../../../assets/voice-play-white.png')
        "
        class="voice-play"
      />
    </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,
    },
    themeColor: {
      type: String,
      default: '',
    },
  },
  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() {
      if (!this.url) return;
      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;
    color: #fff;
    cursor: pointer;
    background-color: $main-color;
    border-radius: 50%;

    &.not-url {
      color: #a1a1a1;
      cursor: not-allowed;
    }

    .voice-play {
      width: 20px;
      height: 20px;
    }
  }
}
</style>
