<template>
    <div class="audio-player">
        <!-- 隐藏的 audio 元素 -->
        <audio ref="audioRef" :src="src" preload="auto" @loadedmetadata="onLoadedMetadata" @timeupdate="onTimeUpdate"
            @ended="onEnded" @canplay="onCanPlay"></audio>

        <!-- 播放器主体 -->
        <div class="player-main">
            <!-- 播放/暂停按钮 -->
            <SvgIcon class="btn" v-if="!isPlaying" name="start" :size="32" color="#136cfc" @click="togglePlay" />
            <SvgIcon class="btn" v-if="isPlaying" name="pause" :size="32" color="#d33257" @click="togglePlay" />

            <!-- 当前时间 -->
            <span class="time-text">{{ formatTime(currentTime) }}</span>

            <!-- 自定义进度条 -->
            <div class="progress-wrapper">
                <!-- 缓冲条 -->
                <div class="buffered-bar" :style="{ width: buffered + '%' }"></div>
                <!-- 已播放进度条 -->
                <div class="progress-bar" :style="{ width: progress + '%' }">
                    <div class="progress-thumb" :class="{ active: isDragging }"></div>
                </div>
                <!-- 透明的交互层 -->
                <div class="progress-hit" ref="progressRef" @mousedown="onProgressMouseDown"
                    @mousemove="onProgressHover" @mouseleave="hoverTime = -1"></div>
                <!-- 悬浮时间提示 -->
                <div v-if="hoverTime >= 0 && !isDragging" class="hover-tooltip" :style="{ left: hoverPos + 'px' }">
                    {{ formatTime(hoverTime) }}
                </div>
            </div>

            <!-- 总时长 -->
            <span class="time-text">{{ formatTime(duration) }}</span>

            <!-- 音量控制 -->
            <div class="volume-wrapper">
                <el-button :icon="volumeIcon" text @click="toggleMute" />
                <el-slider v-model="volume" :min="0" :max="100" :show-tooltip="false" size="small" class="volume-slider"
                    @input="onVolumeChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, watch } from 'vue'
import SvgIcon from "@/components/SvgIcon";
import {  Mute, Microphone } from '@element-plus/icons-vue'

const props = defineProps({
    src: {
        type: String,
        required: true
    }
})

const emits = defineEmits(['audioStatus'])

// --- 状态 ---
const audioRef = ref(null)
const progressRef = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const buffered = ref(0)
const volume = ref(80)
const lastVolume = ref(80)
const hoverTime = ref(-1)
const hoverPos = ref(0)
const isDragging = ref(false)

// --- 计算属性 ---
const progress = computed(() => {
    if (!duration.value) return 0
    return (currentTime.value / duration.value) * 100
})

const volumeIcon = computed(() => {
    return volume.value === 0 ? Mute : Microphone
})

// --- audio 事件 ---
const onLoadedMetadata = () => {
    duration.value = audioRef.value.duration
}

const onCanPlay = () => {
    duration.value = audioRef.value.duration
}

const onTimeUpdate = () => {
    if (!isDragging.value) {
        currentTime.value = audioRef.value.currentTime
        updateBuffered()
    }
}

const onEnded = () => {
    isPlaying.value = false
    currentTime.value = 0
}

const updateBuffered = () => {
    const audio = audioRef.value
    if (audio.buffered.length > 0) {
        buffered.value = (audio.buffered.end(audio.buffered.length - 1) / duration.value) * 100
    }
}

// --- 播放控制 ---
const togglePlay = () => {
    if (!audioRef.value && !props.url) return
    if (isPlaying.value) {
        audioRef.value.pause()
    } else {
        audioRef.value.play()
    }
    isPlaying.value = !isPlaying.value
}

// --- 进度条交互 ---
const getTimeFromEvent = (e) => {
    const rect = progressRef.value.getBoundingClientRect()
    const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
    return ratio * duration.value
}

const seekTo = (time) => {
    if (!audioRef.value || !duration.value) return
    audioRef.value.currentTime = Math.max(0, Math.min(time, duration.value))
    currentTime.value = audioRef.value.currentTime
}

const onProgressMouseDown = (e) => {
    isDragging.value = true
    seekTo(getTimeFromEvent(e))

    const onMove = (ev) => {
        seekTo(getTimeFromEvent(ev))
    }

    const onUp = () => {
        isDragging.value = false
        document.removeEventListener('mousemove', onMove)
        document.removeEventListener('mouseup', onUp)
    }

    document.addEventListener('mousemove', onMove)
    document.addEventListener('mouseup', onUp)
}

const onProgressHover = (e) => {
    if (isDragging.value) return
    const rect = progressRef.value.getBoundingClientRect()
    const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
    hoverTime.value = ratio * duration.value
    hoverPos.value = e.clientX - rect.left
}

// --- 音量控制 ---
const onVolumeChange = (val) => {
    if (!audioRef.value) return
    audioRef.value.volume = val / 100
}

const toggleMute = () => {
    if (volume.value > 0) {
        lastVolume.value = volume.value
        volume.value = 0
    } else {
        volume.value = lastVolume.value
    }
    audioRef.value.volume = volume.value / 100
}

// --- 初始化音量 ---
const initVolume = () => {
    if (audioRef.value) {
        audioRef.value.volume = volume.value / 100
    }
}

// --- 工具函数 ---
const formatTime = (seconds) => {
    if (!seconds || isNaN(seconds)) return '00:00'
    const m = Math.floor(seconds / 60)
    const s = Math.floor(seconds % 60)
    return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}

// 监听 audio 元素加载完成后设置音量
const observer = setInterval(() => {
    if (audioRef.value) {
        initVolume()
        clearInterval(observer)
    }
}, 100)

watch(() => isPlaying.value,
    () => {
        emits('audioStatus', isPlaying.value)
    }
)

onBeforeUnmount(() => {
    clearInterval(observer)
})
</script>

<style lang="scss" scoped>
.audio-player {
    width: 100%;
    border-radius: 12px;
    padding: 12px 28px;
    border: 1px solid #afafaf;

    .player-main {
        display: flex;
        align-items: center;
        gap: 14px;

        /* 时间文字 */
        .time-text {
            flex-shrink: 0;
            font-size: 13px;
            color: #94a3b8;
            font-variant-numeric: tabular-nums;
            width: 42px;
            text-align: center;
            font-family: 'DM Mono', 'Courier New', monospace;
        }

        /* 进度条容器 */
        .progress-wrapper {
            position: relative;
            flex: 1;
            height: 6px;
            background: #e5e5e5;
            border-radius: 3px;
            cursor: pointer;
            overflow: visible;

            .buffered-bar {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 3px;
                transition: width 0.3s ease;
            }

            .progress-bar {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                background: linear-gradient(90deg, #3b82f6, #60a5fa);
                border-radius: 3px;
                transition: width 0.05s linear;

                .progress-thumb {
                    position: absolute;
                    right: -7px;
                    top: 50%;
                    transform: translateY(-50%) scale(0);
                    width: 14px;
                    height: 14px;
                    background: #fff;
                    border-radius: 50%;
                    box-shadow: 0 0 8px rgba(59, 130, 246, 0.6);
                    transition: transform 0.15s ease;
                }
            }

            /* 透明交互层 */
            .progress-hit {
                position: absolute;
                top: -8px;
                left: 0;
                right: 0;
                bottom: -8px;
                z-index: 2;
            }

            /* hover 时间提示 */
            .hover-tooltip {
                position: absolute;
                top: -32px;
                transform: translateX(-50%);
                background: rgba(0, 0, 0, 0.85);
                color: #e2e8f0;
                font-size: 12px;
                padding: 3px 8px;
                border-radius: 4px;
                pointer-events: none;
                white-space: nowrap;
                font-variant-numeric: tabular-nums;
            }
        }
    }
}

/* hover 时显示圆点 */
.progress-wrapper:hover .progress-thumb,
.progress-thumb.active {
    transform: translateY(-50%) scale(1);
}

/* 音量区域 */
.volume-wrapper {
    display: flex;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
    margin-left: 4px;
}

.volume-wrapper .el-button {
    color: #94a3b8 !important;
}

.volume-slider {
    width: 80px;
}

:deep(.volume-slider .el-slider__runway) {
    height: 4px;
    background: rgba(255, 255, 255, 0.1);
}

:deep(.volume-slider .el-slider__bar) {
    height: 4px;
    background: #3b82f6;
}

:deep(.volume-slider .el-slider__button-wrapper) {
    top: -16px;
}

:deep(.volume-slider .el-slider__button) {
    width: 12px;
    height: 12px;
    border: 2px solid #3b82f6;
    background: #fff;
}

/* 进度条 hover 加粗效果 */
.progress-wrapper:hover {
    height: 8px;
}
</style>