<template>
  <audio ref="audioPlayer" style="width: 420px; height: 32px" :src="audioSrc" controls @play="onPlay"></audio>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';

const props = defineProps({
  audioSrc: {
    type: String,
    default: ''
  },
  // 单位秒
  startTime: {
    type: [Number, String],
    default: 0
  },
  // 单位秒
  endTime: {
    type: [Number, String],
    default: 0
  },
  content: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['playing-content']);

const audioPlayer = ref(null);
let isPausedAtEndTime = false; // 用于标记是否在endTime暂停

// 判断传入的startTime和endTime是否合法
const isValidTime = (time) => {
  return time !== '' && time !== undefined && !isNaN(time) && time >= 0 && props.endTime != 0;
};

const onPlay = () => {
  // 播放时上抛一个事件给详情信息中传递当前播放文件的内容
  emit('playing-content', props.content);
  // 如果是暂停后从startTime继续播放
  if (isPausedAtEndTime) {
    audioPlayer.value.currentTime = props.startTime;
    isPausedAtEndTime = false;
  }

  // 如果传入的start和end为有效值，则进行时长控制
  if (isValidTime(props.startTime) && isValidTime(props.endTime)) {
    // 设置音频的播放时间从startTime开始
    audioPlayer.value.currentTime = props.startTime;
    audioPlayer.value.addEventListener('timeupdate', handleTimeUpdate);
  } else {
    // 否则播放完整音频
    audioPlayer.value.addEventListener('timeupdate', handleFullPlayback);
  }
};

const handleTimeUpdate = () => {
  if (audioPlayer.value.currentTime >= props.endTime) {
    audioPlayer.value.pause();
    isPausedAtEndTime = true;
  }
};

const handleFullPlayback = () => {
  // 如果播放到音频结束，则移除事件监听
  if (audioPlayer.value.currentTime >= audioPlayer.value.duration) {
    audioPlayer.value.removeEventListener('timeupdate', handleFullPlayback);
  }
};

onMounted(() => {
  // 如果传入的startTime合法，则从startTime开始播放
  if (isValidTime(props.startTime)) {
    audioPlayer.value.currentTime = props.startTime;
  }
});

// 清理事件监听
onUnmounted(() => {
  audioPlayer.value?.removeEventListener('timeupdate', handleTimeUpdate);
  audioPlayer.value?.removeEventListener('timeupdate', handleFullPlayback);
});
</script>
