<template>
    <div class="bgmr vh100 p-16 over-y-auto">
        <section class="bg-fff round-14 p-24 detail-card">
            <div class="flex justify-between gap-20">
                <div class="flex-1 minw-0">
                    <div class="flex-items-center">
                        <div class="w-40 h-40 round avatar flex-center mr-12">♙</div>
                        <div class="minw-0">
                            <div class="font-bold color-000 ellipsis">月儿弯弯 / 管理组 / 管理部</div>
                            <div class="fs-12 color-888 mt-2">发布时间: 2025-04-24 14:43:53</div>
                        </div>
                    </div>

                    <div class="mt-24 info-grid">
                        <div class="color-666">音频区</div>
                        <div class="font-bold color-000 flex-items-center gap-8">
                            <span v-if="!isEditAudioCategory">{{ audioCategoryLabel }}</span>
                            <el-cascader
                                v-else
                                v-model="editAudioCategory"
                                :options="audioCategoryOptions"
                                size="small"
                                class="w-220"
                                clearable
                            />
                            <el-button v-if="!isEditAudioCategory" type="primary" link @click="startEditAudioCategory">
                                修改
                            </el-button>
                            <el-button v-else type="primary" link @click="saveAudioCategory">保存</el-button>
                        </div>

                        <div class="color-666">音频标题</div>
                        <div class="font-bold color-000 flex-items-center gap-8">
                            <span v-if="!isEditTitle">{{ audioTitle }}</span>
                            <el-input v-else v-model="editTitle" size="small" class="w-220" @keyup.enter="saveTitle" />
                            <el-button v-if="!isEditTitle" type="primary" link @click="startEditTitle">修改</el-button>
                            <el-button v-else type="primary" link @click="saveTitle">保存</el-button>
                        </div>

                        <div class="color-666">公共标签</div>
                        <div class="flex-items-center flex-wrap gap-8">
                            <el-tag v-for="tag in publicTags" :key="tag" class="border-none tag-soft">{{ tag }}</el-tag>
                            <el-button type="primary" link size="small" @click="addTag('public')">+ 添加公共标签</el-button>
                        </div>

                        <div class="color-666">个人标签</div>
                        <div class="flex-items-center flex-wrap gap-8">
                            <el-tag
                                v-for="tag in personalTags"
                                :key="tag"
                                closable
                                class="border-none tag-main"
                                @close="removePersonalTag(tag)"
                            >
                                {{ tag }}
                            </el-tag>
                            <el-button type="primary" link size="small" @click="addTag('personal')">+ 添加个人标签</el-button>
                        </div>

                        <div class="color-666">音频说明</div>
                        <div class="color-888">{{ audioDesc || '暂无说明' }}</div>
                    </div>
                </div>

                <div class="flex items-start">
                    <el-button type="primary" class="px-24 round-6 font-bold" @click="downloadAudio">下载</el-button>
                    <el-button class="w-40 h-34 round-6 color-main border-main mr-10" @click="shareAudio">⌘</el-button>
                    <el-dropdown trigger="click" @command="handleMore">
                        <el-button class="px-18 round-6 color-main border-main">
                            更多操作
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu class="more-menu">
                                <el-dropdown-item command="push">推送至团队剪辑</el-dropdown-item>
                                <el-dropdown-item command="category">修改所属分类</el-dropdown-item>
                                <el-dropdown-item command="message">发送消息提醒</el-dropdown-item>
                                <el-dropdown-item divided command="delete" class="danger-item">放入回收站</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </section>

        <section class="bg-fff round-14 p-24 mt-16 detail-card">
            <div class="font-bold color-000 fs-18">{{ audioTitle }}</div>
            <div class="flex-items-center mt-24 audio-player">
                <audio
                    ref="audioRef"
                    src="/houlai.mp3"
                    :muted="isMuted"
                    @timeupdate="onTimeUpdate"
                    @ended="onEnded"
                    @loadedmetadata="onLoadedMetadata"
                ></audio>

                <div class="w-44 h-44 round flex-center color-main pointer play-btn" @click="togglePlay">
                    {{ isPlaying ? 'Ⅱ' : '▶' }}
                </div>
                <span class="ml-16 fs-12 color-000 time-text">{{ formatTime(currentTime) }}</span>
                <el-slider
                    v-model="currentTime"
                    class="mx-16"
                    :max="duration"
                    :step="0.1"
                    :show-tooltip="false"
                    @change="onSliderChange"
                    @drag-start="isDragging = true"
                    @drag-end="isDragging = false"
                />
                <span class="fs-12 color-000 time-text">{{ formatTime(duration) }}</span>
                <el-button class="ml-20 border-none color-666" link @click="toggleMuted">
                    {{ isMuted ? '静音' : '◔' }}
                </el-button>
                <el-button class="ml-12 px-16 round-18 font-bold speed-btn" @click="toggleSpeed">{{ playbackRate }}x倍速</el-button>
            </div>
        </section>
    </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';

const audioRef = ref<HTMLAudioElement | null>(null);
const currentTime = ref(0);
const duration = ref(52);
const isDragging = ref(false);
const isPlaying = ref(false);
const isMuted = ref(false);
const playbackRate = ref(1);

const audioTitle = ref('现在洁牙');
const editTitle = ref(audioTitle.value);
const isEditTitle = ref(false);
const audioCategory = ref(['beauty', 'medical']);
const editAudioCategory = ref<string[]>([]);
const isEditAudioCategory = ref(false);
const audioDesc = ref('');
const publicTags = ref(['场景', '合作达人']);
const personalTags = ref(['有个人标签']);
const audioCategoryOptions = [
    {
        label: '美容美体',
        value: 'beauty',
        children: [
            { label: '医疗机构', value: 'medical' },
            { label: '皮肤管理', value: 'skin' },
            { label: '口腔护理', value: 'dental' },
        ],
    },
    {
        label: '生活服务',
        value: 'life',
        children: [
            { label: '探店口播', value: 'shop' },
            { label: '本地推广', value: 'local' },
        ],
    },
];

const togglePlay = async () => {
    if (!audioRef.value) return;

    if (isPlaying.value) {
        audioRef.value.pause();
        isPlaying.value = false;
        return;
    }

    try {
        audioRef.value.playbackRate = playbackRate.value;
        await audioRef.value.play();
        isPlaying.value = true;
    } catch (err) {
        isPlaying.value = false;
    }
};

const onSliderChange = (val: number) => {
    if (audioRef.value) {
        audioRef.value.currentTime = val;
    }
};

const onLoadedMetadata = () => {
    if (audioRef.value) {
        duration.value = audioRef.value.duration;
    }
};

const onTimeUpdate = () => {
    if (!audioRef.value || isDragging.value) return;
    currentTime.value = audioRef.value.currentTime;
};

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

const formatTime = (time: number) => {
    if (!time || isNaN(time)) return '00:00';
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const toggleMuted = () => {
    isMuted.value = !isMuted.value;
};

const toggleSpeed = () => {
    playbackRate.value = playbackRate.value === 1 ? 1.5 : playbackRate.value === 1.5 ? 2 : 1;
    if (audioRef.value) {
        audioRef.value.playbackRate = playbackRate.value;
    }
};

const startEditTitle = () => {
    editTitle.value = audioTitle.value;
    isEditTitle.value = true;
};

const saveTitle = () => {
    audioTitle.value = editTitle.value;
    isEditTitle.value = false;
    ElMessage.success('标题已修改');
};

const findCategoryLabel = (value: string[], options: typeof audioCategoryOptions) => {
    const first = options.find((item) => item.value === value[0]);
    const second = first?.children.find((item) => item.value === value[1]);
    return first && second ? `${first.label} / ${second.label}` : '';
};

const audioCategoryLabel = computed(() => findCategoryLabel(audioCategory.value, audioCategoryOptions));

const startEditAudioCategory = () => {
    editAudioCategory.value = [...audioCategory.value];
    isEditAudioCategory.value = true;
};

const saveAudioCategory = () => {
    if (editAudioCategory.value.length < 2) {
        ElMessage.warning('请选择二级分类');
        return;
    }
    audioCategory.value = [...editAudioCategory.value];
    isEditAudioCategory.value = false;
    ElMessage.success('音频区已修改');
};

const removePersonalTag = (tag: string) => {
    personalTags.value = personalTags.value.filter((item) => item !== tag);
};

const addTag = (type: 'public' | 'personal') => {
    const tag = type === 'public' ? '新公共标签' : '个人收藏';
    const list = type === 'public' ? publicTags.value : personalTags.value;
    if (!list.includes(tag)) {
        list.push(tag);
    }
};

const downloadAudio = () => ElMessage.success('开始下载音频');
const shareAudio = () => ElMessage.success('分享链接已生成');
const handleEdit = (name: string) => ElMessage.success(`${name}编辑功能已触发`);
const handleMore = (command: string) => ElMessage.success(`已选择：${command}`);
</script>

<style scoped lang="scss">
.detail-card {
    max-width: 976px;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid #e6ebf3;
}

.avatar {
    background-color: #edf2f8;
    color: #7890ad;
}

.info-grid {
    display: grid;
    grid-template-columns: 74px 1fr;
    row-gap: 20px;
}

.tag-soft {
    background-color: #f2f6ff;
    color: #21324f;
}

.tag-main {
    background-color: rgba(var(--main-color), .08);
    color: rgba(var(--main-color), 1);
}

.border-main {
    border: 1px solid rgba(var(--main-color), .35);
}

.play-btn {
    border: 2px solid rgba(var(--main-color), 1);
    flex-shrink: 0;
}

.audio-player {
    :deep(.el-slider) {
        flex: 1;
    }

    :deep(.el-slider__button) {
        width: 14px;
        height: 14px;
        border: none;
        background-color: rgb(var(--main-color));
    }

    :deep(.el-slider__bar) {
        background-color: rgb(var(--main-color));
    }

    :deep(.el-slider__runway) {
        height: 5px;
        background-color: #e6ebf2;
    }
}

.time-text {
    font-family: Consolas, monospace;
}

.speed-btn {
    border: 1px solid #e5eaf2;
    background-color: #fff;
}

:deep(.more-menu) {
    min-width: 158px;
}

:deep(.danger-item) {
    color: #f03b55;
}
</style>
