<template>
    <div :class="['message-audio-container', { 'out-message': isSeatSide }]" @click="play">
        <div class="audio-icon-wrapper">
            <img v-if="isPlaying" :src="audioPlayIcon" :class="{ 'rotate-180': !isSeatSide }" class="audio-icon" />
            <img v-else :src="audioIcon" :class="{ 'rotate-180': isSeatSide }" class="audio-icon" />
        </div>
        <span class="audio-duration">{{ audioContent.second || 1 }}"</span>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import audioPlayIcon from '../../../../assets/icons/audioPlay.gif'
import audioIcon from '../../../../assets/icons/msg-audio.svg'
import { amrPlayer } from './AMR'
import toast from '../../../../utils/toast'
import { parseUnknownError } from '../../../../utils/parseUnknownError'

interface MessageAudioContent {
    url: string
    second: number
}

interface Props {
    audioContent: MessageAudioContent
    isSeatSide: boolean
}

const props = defineProps<Props>()
const { t } = useI18n()
const isPlaying = ref(false)

// 订阅播放/停止事件
onMounted(() => {
    amrPlayer.on('play', props.audioContent.url, () => {
        isPlaying.value = true
    })
    amrPlayer.on('stop', props.audioContent.url, () => {
        isPlaying.value = false
    })
})

// 取消订阅
onUnmounted(() => {
    amrPlayer.off('play', props.audioContent.url)
    amrPlayer.off('stop', props.audioContent.url)
})

const play = async () => {
    try {
        await amrPlayer.play(props.audioContent.url)
    } catch (e) {
        toast.error(t('播放失败：{reason}', { reason: parseUnknownError(e) }))
    }

}
</script>

<style scoped>
.message-audio-container {
    display: flex;
    flex: 0 0 auto;
    cursor: pointer;
    overflow: hidden;
    flex-direction: row;
    align-items: center;
}

.message-audio-container.out-message {
    flex-direction: row-reverse;
}

.audio-icon-wrapper {
    position: relative;
}

.audio-icon {
    width: 16px;
    height: 20px;
}

.rotate-180 {
    transform: rotate(180deg);
}

.audio-duration {
    width: 40px;
    margin-left: 10px;
}

.message-audio-container.out-message .audio-duration {
    margin-left: 0;
    margin-right: 10px;
}
</style>