文章详情

返回首页

云音乐CF终极版本

分享文章 作者: Ws01 创建时间: 2025-11-24 📝 字数: 130,186 字 👁️ 阅读: 12 次

原始 Markdown

export default {
    async fetch(request, env, ctx) {
        // 设置CORS头
        const corsHeaders = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
        };

        // 处理预检请求
        if (request.method === 'OPTIONS') {
            return new Response(null, { headers: corsHeaders });
        }

        const url = new URL(request.url);

        // 登录逻辑
        if (url.pathname === '/login' && request.method === 'POST') {
            const formData = await request.formData();
            const password = formData.get('password');
            const adminPassword = env.ADMIN_PASSWORD || 'admin123'; // 默认密码,可通过环境变量设置
            if (password === adminPassword) {
                // 登录成功,设置 Cookie, 默认24小时等于86400秒,自用30天等于2592000秒
                console.log('登录成功,设置Cookie');
                return new Response('', {
                    status: 302,
                    headers: {
                        'Set-Cookie': `auth=1; Path=/; HttpOnly; SameSite=Lax; Max-Age=864000`,
                        'Location': '/'
                    }
                });
            } else {
                return new Response(renderLoginPage('密码错误,请重试!'), {
                    headers: { 'Content-Type': 'text/html;charset=utf-8' }
                });
            }
        }

        // 退出逻辑
        if (url.pathname === '/logout') {
            return new Response('', {
                status: 302,
                headers: {
                    'Set-Cookie': `auth=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`,
                    'Location': '/'
                }
            });
        }

        // 检查是否已登录
        const cookie = request.headers.get('Cookie') || '';
        console.log('检查Cookie:', cookie);
        if (!cookie.includes('auth=1')) {
            console.log('未找到有效Cookie,重定向到登录页面');
            return new Response(renderLoginPage(), {
                headers: { 'Content-Type': 'text/html;charset=utf-8' }
            });
        }
        console.log('Cookie验证通过,允许访问');

        const html = `<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ws01 Music - 个人音乐库</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>♬</text></svg>">
    <style>
        :root {
            --font-main: 'Noto Sans SC', 'Segoe UI', Arial, sans-serif;
            --accent-color: #0F52BA;
            --accent-color-hover: #00318C;
            --danger-color: #D32F2F;
            --download-color: #27ae60;

            --bg-color-dark: #191A1C;
            --sidebar-bg: rgba(17, 18, 19, 0.75);
            --main-bg: rgba(25, 26, 28, 0.6);
            --player-bg: rgba(17, 18, 19, 0.75);

            --text-color-primary: #F5F5F5;
            --text-color-secondary: #A0A0A0;

            --component-bg: rgba(44, 45, 47, 0.7);
            --hover-bg: rgba(58, 59, 61, 0.8);
            --border-color: rgba(80, 80, 80, 0.5);
        }

        .light-mode {
            --accent-color: #0F52BA;
            --accent-color-hover: #0039A6;
            --download-color: #2ecc71;
            --danger-color: #c0392b;

            --bg-color-dark: #F4F6F8;
            --sidebar-bg: rgba(255, 255, 255, 0.7);
            --main-bg: rgba(244, 246, 248, 0.65);
            --player-bg: rgba(255, 255, 255, 0.7);

            --text-color-primary: #121212;
            --text-color-secondary: #6B7280;

            --component-bg: rgba(255, 255, 255, 0.6);
            --hover-bg: rgba(234, 236, 239, 0.7);
            --border-color: rgba(200, 200, 200, 0.6);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--hover-bg);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--accent-color);
        }

        body {
            font-family: var(--font-main);
            color: var(--text-color-primary);
            background-color: var(--bg-color-dark);
            overflow: hidden;
            transition: background-color 0.3s;
        }

        @keyframes gradient-animation {
            0% {
                background-position: 0% 50%;
            }

            50% {
                background-position: 100% 50%;
            }

            100% {
                background-position: 0% 50%;
            }
        }

        .app-container {
            display: grid;
            grid-template-columns: 240px 1fr;
            grid-template-rows: 1fr auto;
            grid-template-areas: "sidebar main" "player player";
            height: 100vh;
            width: 100vw;
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradient-animation 15s ease infinite;
        }

        .sidebar {
            grid-area: sidebar;
            background-color: var(--sidebar-bg);
            padding: 24px;
            display: flex;
            flex-direction: column;
            border-right: 1px solid var(--border-color);
            box-shadow: 2px 0 15px rgba(0, 0, 0, 0.2);
            transition: background-color 0.3s, border-color 0.3s;
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
        }

        .sidebar h1 {
            color: var(--text-color-primary);
            margin-bottom: 32px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .sidebar nav ul {
            list-style: none;
        }

        .sidebar nav a {
            color: var(--text-color-secondary);
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .sidebar nav a:hover {
            color: var(--text-color-primary);
            background-color: var(--hover-bg);
        }

        .sidebar nav a.active {
            color: var(--accent-color);
            font-weight: 700;
            background-color: var(--hover-bg);
        }

        .main-content {
            grid-area: main;
            overflow-y: auto;
            padding: 24px 32px;
            background-color: var(--main-bg);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }

        .search-area {
            position: relative;
            margin-bottom: 24px;
        }

        .search-area i.fa-search {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-color-secondary);
        }

        .search-area input {
            background-color: var(--component-bg);
            border: 1px solid var(--border-color);
            color: var(--text-color-primary);
            width: 100%;
            padding: 12px 20px 12px 50px;
            font-size: 1em;
            border-radius: 50px;
            outline: none;
            transition: all 0.3s;
        }

        .search-area input:focus {
            border-color: var(--accent-color);
            box-shadow: 0 0 10px rgba(15, 82, 186, 0.2);
        }

        .song-list-header,
        .song-item {
            display: grid;
            grid-template-columns: 40px 3fr 2fr 2fr 40px 40px;
            align-items: center;
            padding: 10px 15px;
            gap: 15px;
        }

        #stats-top-tracks .song-item,
        #stats-top-artists .song-item {
            grid-template-columns: 40px 3fr 2fr 1fr 40px;
        }

        .song-list-header {
            color: var(--text-color-secondary);
            font-size: 0.8em;
            border-bottom: 1px solid var(--border-color);
            background-color: var(--component-bg);
            border-radius: 8px 8px 0 0;
            margin-top: 10px;
        }

        .song-item {
            border-radius: 8px;
            transition: background-color 0.2s;
            cursor: pointer;
            font-size: 0.9em;
            border-bottom: 1px solid var(--border-color);
        }

        .song-list>.song-item:last-child {
            border-bottom: none;
        }

        .song-item:hover {
            background-color: var(--hover-bg);
        }

        .song-item.current {
            background-color: var(--hover-bg);
        }

        .song-item.current .song-title>span:first-child {
            color: var(--accent-color);
        }

        .song-item .song-title {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .song-item .song-title .error-msg {
            font-size: 0.8em;
            color: var(--danger-color);
            margin-top: 4px;
        }

        .action-btn {
            color: var(--text-color-secondary);
            cursor: pointer;
            transition: color 0.2s, transform 0.2s;
            text-align: center;
        }

        .action-btn:hover {
            transform: scale(1.2);
        }

        .fav-btn.favourited {
            color: var(--danger-color);
        }

        .download-btn:hover {
            color: var(--download-color);
        }

        .delete-btn:hover {
            color: var(--danger-color);
        }

        .now-playing-bar {
            grid-area: player;
            background-color: var(--player-bg);
            border-top: 1px solid var(--border-color);
            padding: 15px 30px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            align-items: center;
            gap: 20px;
            box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
        }

        .song-info-bar {
            display: flex;
            align-items: center;
            gap: 15px;
            min-width: 0;
        }

        .song-info-bar img {
            width: 56px;
            height: 56px;
            border-radius: 8px;
            object-fit: cover;
            background-color: var(--hover-bg);
        }

        .song-info-bar .fav-btn {
            font-size: 1.2em;
        }

        .song-info-bar div {
            overflow: hidden;
        }

        .song-info-bar div h3,
        .song-info-bar div p {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .player-controls {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .control-buttons {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 24px;
            margin-bottom: 12px;
        }

        #playPauseBtn {
            background-color: var(--text-color-primary);
            color: var(--player-bg);
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5em;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            cursor: pointer;
            border: none;
        }

        .light-mode #playPauseBtn {
            color: #FFFFFF;
            background-color: #121212;
        }

        #playPauseBtn:hover {
            transform: scale(1.1);
        }

        .control-btn {
            background: none;
            border: none;
            color: var(--text-color-secondary);
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.2s;
        }

        .control-btn:hover {
            color: var(--text-color-primary);
            transform: scale(1.15);
        }

        .control-btn.active {
            color: var(--accent-color);
        }

        .progress-area {
            display: flex;
            align-items: center;
            gap: 10px;
            width: 100%;
            max-width: 500px;
        }

        .progress-bar {
            flex-grow: 1;
            height: 6px;
            background-color: var(--hover-bg);
            border-radius: 3px;
            cursor: pointer;
        }

        .progress {
            height: 100%;
            width: 0%;
            background-color: var(--accent-color);
            border-radius: 3px;
        }

        .time-display span {
            font-size: 0.75em;
            color: var(--text-color-secondary);
        }

        .extra-controls {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 15px;
        }

        .volume-area {
            display: flex;
            align-items: center;
            gap: 8px;
            width: 120px;
        }

        input[type="range"] {
            -webkit-appearance: none;
            appearance: none;
            width: 100%;
            height: 6px;
            background-color: var(--hover-bg);
            border-radius: 3px;
            outline: none;
            cursor: pointer;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 16px;
            height: 16px;
            background-color: var(--text-color-primary);
            border-radius: 50%;
            transition: background-color 0.3s;
        }

        input[type="range"]:hover::-webkit-slider-thumb {
            background-color: var(--accent-color);
        }

        .sidebar .theme-switcher {
            margin-top: auto;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 12px;
            border-radius: 8px;
            background-color: var(--component-bg);
            color: var(--text-color-secondary);
            font-weight: 500;
            transition: all 0.3s;
        }

        .sidebar .theme-switcher:hover {
            color: var(--text-color-primary);
            background-color: var(--hover-bg);
        }


        .view {
            display: none;
        }

        .view.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .list-section h2,
        .view>h2 {
            margin-bottom: 20px;
            font-size: 1.8rem;
            color: var(--text-color-primary);
            border-bottom: 2px solid var(--accent-color);
            padding-bottom: 10px;
        }

        /* 数据管理界面样式 */
        .data-management-controls {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .data-control-group {
            margin-bottom: 24px;
            padding: 16px;
            background: var(--bg-color);
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }

        .data-control-group:last-child {
            margin-bottom: 0;
        }

        .data-control-group h3 {
            margin: 0 0 12px 0;
            font-size: 1.2rem;
            color: var(--text-color-primary);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .data-control-group h3::before {
            content: '';
            width: 4px;
            height: 20px;
            background: var(--accent-color);
            border-radius: 2px;
        }

        .data-control-group .control-buttons {
            display: flex;
            gap: 12px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }

        .data-control-group .control-btn {
            background: var(--accent-color);
            color: white;
            border: none;
            padding: 10px 16px;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .data-control-group .control-btn:hover {
            background: var(--accent-color-hover);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }

        .data-control-group .control-btn:active {
            transform: translateY(0);
        }

        .data-info {
            margin: 0;
            font-size: 0.9rem;
            color: var(--text-color-secondary);
            font-weight: 500;
        }

        .data-info span {
            color: var(--accent-color);
            font-weight: 600;
        }

        /* 清空按钮样式 */
        .control-btn.clear-btn {
            background: #e74c3c;
            color: white;
        }

        .control-btn.clear-btn:hover {
            background: #c0392b;
            transform: translateY(-1px);
        }

        .control-btn.clear-btn:active {
            transform: translateY(0);
        }

        /* 移动端数据管理适配 */
        @media (max-width: 768px) {
            .data-management-controls {
                padding: 16px;
            }

            .data-control-group {
                padding: 12px;
            }

            .data-control-group .control-buttons {
                gap: 8px;
            }

            .data-control-group .control-btn {
                padding: 8px 12px;
                font-size: 0.85rem;
            }
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background-color: var(--component-bg);
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .stat-card h3 {
            color: var(--text-color-secondary);
            font-size: 0.9rem;
            margin-bottom: 8px;
        }

        .stat-card p {
            font-size: 2rem;
            font-weight: bold;
        }

        .pagination-controls {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px 0;
            gap: 8px;
            user-select: none;
        }

        .page-btn {
            background-color: var(--component-bg);
            border: 1px solid var(--border-color);
            color: var(--text-color-secondary);
            padding: 8px 14px;
            min-width: 40px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .page-btn:hover {
            background-color: var(--hover-bg);
            color: var(--text-color-primary);
            border-color: var(--accent-color);
        }

        .page-btn.active {
            background-color: var(--accent-color);
            color: #FFFFFF;
            border-color: var(--accent-color);
            font-weight: 700;
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .action-button {
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 20px;
            border: none;
            background: var(--accent-color);
            color: white;
            font-weight: bold;
            cursor: pointer;
            min-width: 120px;
        }

        /* 移动端响应式设计 */
        @media (max-width: 768px) {
            .app-container {
                grid-template-columns: 1fr;
                grid-template-rows: 1fr auto auto;
                grid-template-areas: "main" "player" "sidebar";
            }

            .sidebar {
                grid-area: sidebar;
                position: fixed;
                top: 0;
                left: -280px;
                width: 280px;
                height: 100vh;
                z-index: 1000;
                transition: left 0.3s ease;
                background-color: var(--sidebar-bg);
                backdrop-filter: blur(20px);
                -webkit-backdrop-filter: blur(20px);
                box-shadow: 2px 0 15px rgba(0, 0, 0, 0.3);
            }

            .sidebar.open {
                left: 0;
            }

            .sidebar .theme-switcher {
                position: absolute;
                bottom: 20px;
                left: 24px;
                right: 24px;
            }

            .sidebar h1 {
                margin-bottom: 20px;
                font-size: 1.5rem;
            }

            .sidebar nav a {
                padding: 16px;
                font-size: 1rem;
            }

            /* 移动端主内容区域 */
            .main-content {
                grid-area: main;
                padding: 16px 20px;
            }

            /* 移动端播放控制栏 */
            .now-playing-bar {
                grid-area: player;
                padding: 20px;
                flex-direction: column;
                gap: 20px;
            }

            .song-info-bar {
                width: 100%;
                gap: 15px;
                justify-content: center;
            }

            .song-info-bar img {
                width: 50px;
                height: 60px;
            }

            /* 在移动端隐藏歌曲信息和收藏按钮,只保留封面 */
            @media (max-width: 768px) {
                .song-info-bar div,
                .song-info-bar .fav-btn {
                    display: none;
                }

                .song-info-bar img {
                    margin: 0 auto;
                }
            }

            .player-controls {
                width: 100%;
            }

            .control-buttons {
                gap: 20px;
            }

            .progress-area {
                max-width: none;
                width: 100%;
            }

            .extra-controls {
                justify-content: center;
                width: 100%;
            }

            .volume-area {
                width: 80px;
            }

            /* 移动端歌曲列表 */
            .song-list-header,
            .song-item {
                grid-template-columns: 30px 1fr 30px 30px;
                padding: 12px 8px;
                gap: 8px;
            }

            .song-list-header span:nth-child(2),
            .song-list-header span:nth-child(3),
            .song-list-header span:nth-child(4) {
                display: none;
            }

            .song-item .song-title {
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                max-width: 100%;
            }

            .song-item span:nth-child(3),
            .song-item span:nth-child(4) {
                display: none;
            }

            .song-item .song-index {
                font-size: 0.8rem;
            }

            .action-btn {
                font-size: 1rem;
                min-width: 44px;
                min-height: 44px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            /* 移动端搜索框 */
            .search-area input {
                padding: 14px 20px 14px 50px;
                font-size: 1rem;
            }

            .search-area i.fa-search {
                left: 18px;
                font-size: 1.1rem;
            }

            /* 移动端按钮优化 */
            .action-button {
                padding: 14px 20px;
                font-size: 1rem;
                min-width: 100%;
                margin-bottom: 16px;
            }

            /* 移动端分页 */
            .pagination-controls {
                padding: 16px 0;
            }

            .page-btn {
                padding: 10px 16px;
                min-width: 44px;
                font-size: 1rem;
            }

            /* 移动端统计卡片 */
            .stats-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .stat-card {
                padding: 16px;
            }

            .stat-card h3 {
                font-size: 0.85rem;
            }

            .stat-card p {
                font-size: 1.8rem;
            }

            /* 移动端列表标题 */
            .list-section h2,
            .view > h2 {
                font-size: 1.5rem;
                margin-bottom: 16px;
            }
        }

        /* 移动端统计列表特殊适配 */
        @media (max-width: 768px) {
            #stats-top-tracks .song-item {
                grid-template-columns: 30px 1fr 1fr 1fr 30px !important;
                padding: 12px 8px;
                gap: 8px;
            }

            #stats-top-tracks .song-list-header {
                grid-template-columns: 30px 1fr 1fr 1fr 30px !important;
            }

            #stats-top-tracks .song-item span:nth-child(3),
            #stats-top-tracks .song-item span:nth-child(4) {
                display: block !important;
                font-size: 0.8rem;
                color: var(--text-color-secondary);
            }

            #stats-top-tracks .song-item .song-title {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            /* 最常听的歌手在移动端使用3列布局 */
            #stats-top-artists .song-item {
                grid-template-columns: 30px 1fr 1fr !important;
                padding: 12px 8px;
                gap: 8px;
            }

            #stats-top-artists .song-list-header {
                grid-template-columns: 30px 1fr 1fr !important;
            }

            #stats-top-artists .song-item span:nth-child(3) {
                display: block !important;
                font-size: 0.8rem;
                color: var(--text-color-secondary);
                text-align: right;
            }

            #stats-top-artists .song-item .song-title {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

        /* 超小屏幕统计适配 */
        @media (max-width: 480px) {
            #stats-top-tracks .song-item {
                grid-template-columns: 25px 1fr 1fr 25px !important;
                font-size: 0.8rem;
            }

            #stats-top-tracks .song-list-header {
                grid-template-columns: 25px 1fr 1fr 25px !important;
                font-size: 0.7rem;
            }

            #stats-top-tracks .song-item span:nth-child(4) {
                display: none !important;
            }

            #stats-top-tracks .song-item span:nth-child(3) {
                text-align: right;
            }

            /* 最常听的歌手在超小屏幕下使用3列布局 */
            #stats-top-artists .song-item {
                grid-template-columns: 25px 1fr 1fr !important;
                font-size: 0.8rem;
            }

            #stats-top-artists .song-list-header {
                grid-template-columns: 25px 1fr 1fr !important;
                font-size: 0.7rem;
            }

            #stats-top-artists .song-item span:nth-child(3) {
                text-align: right;
            }
        }

        /* 超小屏幕适配 */
        @media (max-width: 480px) {
            .sidebar {
                width: 100%;
                left: -100%;
            }

            .sidebar.open {
                left: 0;
            }

            .main-content {
                padding: 12px 16px;
            }

            .now-playing-bar {
                padding: 16px;
            }

            .control-buttons {
                gap: 16px;
            }

            #playPauseBtn {
                width: 50px;
                height: 50px;
                font-size: 1.2em;
            }

            .control-btn {
                font-size: 1.2em;
            }

            .song-info-bar img {
                width: 40px;
                height: 50px;
            }

            .volume-area {
                width: 60px;
            }
        }

        /* 遮罩层 */
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        .sidebar-overlay.show {
            display: block;
        }

        /* 移动端菜单按钮 */
        .mobile-menu-btn {
            display: none;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1001;
            background-color: var(--component-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 12px;
            cursor: pointer;
            color: var(--text-color-primary);
            font-size: 1.2rem;
            transition: all 0.2s;
        }

        .mobile-menu-btn:hover {
            background-color: var(--hover-bg);
        }

        @media (max-width: 768px) {
            .mobile-menu-btn {
                display: block;
            }
        }

        /* 歌曲选项菜单样式 */
        .song-options-menu {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2000;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        /* 下载完成对话框样式 */
        .download-dialog {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 3000;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
            -webkit-backdrop-filter: blur(4px);
        }

        .download-dialog-content {
            background-color: var(--component-bg);
            border-radius: 12px;
            padding: 25px;
            margin: 20px;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: dialogSlideIn 0.3s ease;
            text-align: center;
        }

        @keyframes dialogSlideIn {
            from {
                opacity: 0;
                transform: scale(0.8) translateY(20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .download-dialog-icon {
            font-size: 48px;
            color: var(--download-color);
            margin-bottom: 15px;
        }

        .download-dialog-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-color-primary);
            margin-bottom: 10px;
        }

        .download-dialog-message {
            color: var(--text-color-secondary);
            margin-bottom: 20px;
            line-height: 1.5;
        }

        .download-dialog-buttons {
            display: flex;
            gap: 12px;
            justify-content: center;
        }

        .download-dialog-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
            min-width: 100px;
        }

        .download-dialog-btn.primary {
            background-color: var(--accent-color);
            color: white;
        }

        .download-dialog-btn.primary:hover {
            background-color: var(--accent-color-hover);
            transform: translateY(-1px);
        }

        .download-dialog-btn.secondary {
            background-color: var(--hover-bg);
            color: var(--text-color-primary);
            border: 1px solid var(--border-color);
        }

        .download-dialog-btn.secondary:hover {
            background-color: var(--component-bg);
            transform: translateY(-1px);
        }

        .song-options-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
            -webkit-backdrop-filter: blur(4px);
        }

        .song-options-content {
            position: relative;
            background-color: var(--component-bg);
            border-radius: 12px;
            padding: 20px;
            margin: 20px;
            width: 100%;
            max-width: 300px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: menuSlideIn 0.3s ease;
        }

        @keyframes menuSlideIn {
            from {
                opacity: 0;
                transform: scale(0.8) translateY(20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .option-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            width: 100%;
            padding: 16px 20px;
            background: none;
            border: none;
            color: var(--text-color-primary);
            font-size: 1rem;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.2s;
            margin-bottom: 8px;
        }

        .option-btn:last-child {
            margin-bottom: 0;
        }

        .option-btn:hover {
            background-color: var(--hover-bg);
            transform: translateY(-1px);
        }

        .option-btn:active {
            transform: translateY(0);
        }

        /* 歌单导入相关样式 */
        .playlist-import {
            background-color: var(--component-bg);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid var(--border-color);
        }

        .section-title {
            color: var(--text-color-primary);
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .import-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .import-input {
            flex: 1;
            padding: 12px 15px;
            background: var(--hover-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            color: var(--text-color-primary);
            outline: none;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .import-input:focus {
            border-color: var(--accent-color);
            box-shadow: 0 0 0 2px rgba(15, 82, 186, 0.2);
        }

        .import-input::placeholder {
            color: var(--text-color-secondary);
        }

        .import-btn {
            padding: 12px 20px;
            background: var(--accent-color);
            border: none;
            border-radius: 8px;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
        }

        .import-btn:hover {
            background: var(--accent-color-hover);
            transform: translateY(-1px);
        }

        .saved-playlists {
            margin-top: 20px;
        }

        .playlist-item {
            padding: 12px 15px;
            background: var(--hover-bg);
            border-radius: 8px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid var(--border-color);
        }

        .playlist-item:hover {
            background: var(--component-bg);
            transform: translateY(-1px);
        }

        .playlist-item .playlist-info {
            flex: 1;
            min-width: 0;
            margin-right: 10px;
        }

        .playlist-item .playlist-name {
            font-weight: 500;
            color: var(--text-color-primary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 4px;
        }

        .playlist-item .playlist-count {
            font-size: 13px;
            color: var(--text-color-secondary);
        }

        .playlist-actions {
            display: flex;
            gap: 8px;
        }

        .playlist-action-btn {
            background: none;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: var(--text-color-secondary);
            cursor: pointer;
            padding: 6px 10px;
            transition: all 0.2s ease;
            font-size: 12px;
        }

        .playlist-action-btn:hover {
            background: var(--accent-color);
            color: white;
            border-color: var(--accent-color);
        }

        .playlist-action-btn.delete {
            color: var(--danger-color);
            border-color: var(--danger-color);
        }

        .playlist-action-btn.delete:hover {
            background: var(--danger-color);
            color: white;
        }

        .empty-state {
            text-align: center;
            color: var(--text-color-secondary);
            padding: 20px;
            font-style: italic;
        }

        /* 移动端歌单导入样式适配 */
        @media (max-width: 768px) {
            .playlist-import {
                padding: 15px;
                margin-bottom: 15px;
            }

            .import-form {
                flex-direction: column;
                gap: 10px;
            }

            .import-btn {
                justify-content: center;
            }

            .playlist-item {
                padding: 10px 12px;
            }

            .playlist-item .playlist-name {
                font-size: 14px;
            }

            .playlist-item .playlist-count {
                font-size: 12px;
            }

            .playlist-actions {
                gap: 6px;
            }

            .playlist-action-btn {
                padding: 4px 8px;
                font-size: 11px;
            }
        }
    </style>
</head>

<body class="dark-mode">

    <audio id="audioPlayer"></audio>

    <div class="app-container">
        <!-- 移动端菜单按钮 -->
        <button class="mobile-menu-btn" id="mobileMenuBtn">
            <i class="fas fa-bars"></i>
        </button>

        <!-- 侧边栏遮罩层 -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>

        <aside class="sidebar" id="sidebar">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px;">
                <h1 style="margin: 0;"><i class="fas fa-headphones-alt"></i> Music</h1>
                <a href="/logout" style="color: var(--text-color-secondary); text-decoration: none; padding: 8px; border-radius: 6px; transition: all 0.2s;" onmouseover="this.style.backgroundColor='var(--hover-bg)'; this.style.color='var(--text-color-primary)'" onmouseout="this.style.backgroundColor='transparent'; this.style.color='var(--text-color-secondary)'" title="退出登录">
                    <i class="fas fa-sign-out-alt"></i>
                </a>
            </div>
            <nav>
                <ul>
                    <li><a href="#" class="nav-link active" data-view="discover-view"><i
                                class="fas fa-compass"></i>发现音乐</a></li>
                    <!-- [] 本地音乐库的导航链接 -->
                    <li><a href="#" class="nav-link" data-view="local-view"><i class="fas fa-hdd"></i>我的本地</a></li>
                    <li><a href="#" class="nav-link" data-view="favourites-view"><i class="fas fa-heart"></i>我的收藏</a>
                    </li>
                    <li><a href="#" class="nav-link" data-view="history-view"><i class="fas fa-history"></i>播放历史</a>
                    </li>
                    <li><a href="#" class="nav-link" data-view="stats-view"><i class="fas fa-chart-pie"></i>听歌统计</a>
                    </li>
                    <li><a href="#" class="nav-link" data-view="data-management-view"><i class="fas fa-database"></i>数据管理</a>
                    </li>
                </ul>
            </nav>
            <div class="login-status" id="loginStatus" style="margin-top: 20px; padding: 12px; background: var(--card-bg); border-radius: 8px; font-size: 0.85rem; color: var(--text-color-secondary); text-align: center;">
                <i class="fas fa-user-check"></i> <span id="loginStatusText">已登录</span>
            </div>
            <div class="theme-switcher" id="themeToggle"><i class="fas fa-sun"></i> <span>切换模式</span></div>
        </aside>

        <main class="main-content">
            <div id="discover-view" class="view active">
                <div class="search-area">
                    <i class="fas fa-search"></i>
                    <input type="search" id="searchInput" placeholder="搜索歌曲、歌手...">
                </div>
                <button id="loadOnlineBtn" class="action-button">
                    <i class="fas fa-satellite-dish"></i> 探索雷达
                </button>
                
                <!-- 歌单导入区域 -->
                <div class="playlist-import">
                    <h2 class="section-title">
                        <i class="fas fa-folder-plus"></i>
                        导入网易云歌单
                    </h2>
                    <div class="import-form">
                        <input type="text" class="import-input" id="playlistIdInput" placeholder="粘贴歌单ID或链接"/>
                        <button class="import-btn" onclick="importPlaylist()">
                            <i class="fas fa-download"></i>
                            <span>导入</span>
                        </button>
                    </div>
                    <div class="saved-playlists" id="savedPlaylists">
                        <!-- 保存的歌单将在这里显示 -->
                    </div>
                </div>
                
                <div id="song-list-container" class="song-list"></div>
                <div id="pagination-discover" class="pagination-controls"></div>
            </div>

            <!-- [] 本地音乐库的视图 -->
            <div id="local-view" class="view">
                <h2><i class="fas fa-hdd"></i> 我的本地音乐</h2>
                <button id="addLocalFilesBtn" class="action-button">
                    <i class="fas fa-folder-plus"></i> 添加本地音乐
                </button>
                <input type="file" id="localFileInput" multiple accept="audio/*" style="display: none;">
                <div id="local-list-container" class="song-list"></div>
                <div id="pagination-local" class="pagination-controls"></div>
            </div>

            <div id="favourites-view" class="view">
                <h2><i class="fas fa-heart"></i> 我的收藏</h2>
                <div id="favourites-list-container" class="song-list"></div>
                <div id="pagination-favourites" class="pagination-controls"></div>
            </div>
            <div id="history-view" class="view">
                <h2><i class="fas fa-history"></i> 播放历史</h2>
                <div id="history-list-container" class="song-list"></div>
                <div id="pagination-history" class="pagination-controls"></div>
            </div>
            <div id="stats-view" class="view">
                <h2><i class="fas fa-chart-pie"></i> 听歌统计</h2>
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3>总播放量</h3>
                        <p id="stats-total-plays">0</p>
                    </div>
                    <div class="stat-card">
                        <h3>不同歌曲</h3>
                        <p id="stats-unique-tracks">0</p>
                    </div>
                </div>
                
                <div class="list-section">
                    <h2>播放最多的歌曲</h2>
                    <div id="stats-top-tracks" class="song-list"></div>
                </div>
                <div class="list-section" style="margin-top: 30px;">
                    <h2>最常听的歌手</h2>
                    <div id="stats-top-artists" class="song-list"></div>
                </div>
            </div>
            
            <div id="data-management-view" class="view">
                <h2><i class="fas fa-database"></i> 数据管理</h2>
                <div class="data-management-controls">
                    <div class="data-control-group">
                        <h3>我的收藏</h3>
                        <div class="control-buttons">
                            <button class="control-btn" id="exportFavouritesBtn" title="导出收藏数据">
                                <i class="fas fa-download"></i> 导出
                            </button>
                            <button class="control-btn" id="importFavouritesBtn" title="导入收藏数据">
                                <i class="fas fa-upload"></i> 导入
                            </button>
                            <button class="control-btn clear-btn" id="clearFavouritesBtn" title="清空收藏数据">
                                <i class="fas fa-trash"></i> 清空
                            </button>
                            <input type="file" id="favouritesFileInput" accept=".json" style="display: none;">
                        </div>
                        <p class="data-info">收藏数量: <span id="favourites-count">0</span></p>
                    </div>
                    
                    <div class="data-control-group">
                        <h3>播放历史</h3>
                        <div class="control-buttons">
                            <button class="control-btn" id="exportHistoryBtn" title="导出播放历史">
                                <i class="fas fa-download"></i> 导出
                            </button>
                            <button class="control-btn" id="importHistoryBtn" title="导入播放历史">
                                <i class="fas fa-upload"></i> 导入
                            </button>
                            <button class="control-btn clear-btn" id="clearHistoryBtn" title="清空播放历史">
                                <i class="fas fa-trash"></i> 清空
                            </button>
                            <input type="file" id="historyFileInput" accept=".json" style="display: none;">
                        </div>
                        <p class="data-info">历史记录: <span id="history-count">0</span></p>
                    </div>
                    
                    <div class="data-control-group">
                        <h3>全部数据</h3>
                        <div class="control-buttons">
                            <button class="control-btn" id="exportAllDataBtn" title="导出所有数据">
                                <i class="fas fa-download"></i> 导出
                            </button>
                            <button class="control-btn" id="importAllDataBtn" title="导入所有数据">
                                <i class="fas fa-upload"></i> 导入
                            </button>
                            <button class="control-btn clear-btn" id="clearAllDataBtn" title="清空所有数据">
                                <i class="fas fa-trash"></i> 清空
                            </button>
                            <input type="file" id="allDataFileInput" accept=".json" style="display: none;">
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="now-playing-bar">
            <div class="song-info-bar">
                <img id="bar-album-art" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=">
                <div>
                    <h3 id="bar-song-title">--</h3>
                    <p id="bar-song-artist">--</p>
                </div>
                <i class="action-btn fav-btn far fa-heart" id="bar-fav-btn" title="添加到我的收藏"></i>
            </div>
            <div class="player-controls">
                <div class="control-buttons">
                    <button class="control-btn" id="shuffleBtn" title="随机"><i class="fas fa-random"></i></button>
                    <button class="control-btn" id="prevBtn" title="上一曲"><i class="fas fa-backward-step"></i></button>
                    <button id="playPauseBtn" title="播放"><i class="fas fa-play"></i></button>
                    <button class="control-btn" id="nextBtn" title="下一曲"><i class="fas fa-forward-step"></i></button>
                    <button class="control-btn" id="repeatBtn" title="循环"><i class="fas fa-redo"></i></button>
                </div>
                <div class="progress-area">
                    <span class="time-display" id="currentTime">0:00</span>
                    <div class="progress-bar" id="progressBar">
                        <div class="progress" id="progress"></div>
                    </div>
                    <span class="time-display" id="totalDuration">0:00</span>
                </div>
            </div>
            <div class="extra-controls">
                <div class="volume-area"><i class="fas fa-volume-down"></i><input type="range" id="volumeSlider" min="0"
                        max="1" step="0.01" value="0.8"></div>
            </div>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // [] IndexedDB 帮助对象
            const idbHelper = {
                db: null,
                init() {
                    return new Promise((resolve, reject) => {
                        const request = indexedDB.open("musicDB", 1);
                        request.onupgradeneeded = (event) => {
                            this.db = event.target.result;
                            if (!this.db.objectStoreNames.contains('songs')) {
                                this.db.createObjectStore('songs', { keyPath: 'id' });
                            }
                        };
                        request.onsuccess = (event) => {
                            this.db = event.target.result;
                            resolve(this.db);
                        };
                        request.onerror = (event) => reject("IndexedDB error: " + event.target.errorCode);
                    });
                },
                addSong(song) {
                    return new Promise((resolve, reject) => {
                        const transaction = this.db.transaction(['songs'], 'readwrite');
                        const store = transaction.objectStore('songs');
                        const request = store.put(song);
                        request.onsuccess = () => resolve();
                        request.onerror = (event) => reject(event.target.error);
                    });
                },
                getSongs() {
                    return new Promise((resolve, reject) => {
                        const transaction = this.db.transaction(['songs'], 'readonly');
                        const store = transaction.objectStore('songs');
                        const request = store.getAll();
                        request.onsuccess = () => resolve(request.result);
                        request.onerror = (event) => reject(event.target.error);
                    });
                },
                deleteSong(id) {
                    return new Promise((resolve, reject) => {
                        const transaction = this.db.transaction(['songs'], 'readwrite');
                        const store = transaction.objectStore('songs');
                        const request = store.delete(id);
                        request.onsuccess = () => resolve();
                        request.onerror = (event) => reject(event.target.error);
                    });
                },
            };

            const dom = {
                audioPlayer: document.getElementById('audioPlayer'),
                themeToggle: document.getElementById('themeToggle'),
                mainContent: document.querySelector('.main-content'),
                songListContainer: document.getElementById('song-list-container'),
                favouritesListContainer: document.getElementById('favourites-list-container'),
                historyListContainer: document.getElementById('history-list-container'),
                localListContainer: document.getElementById('local-list-container'), // 
                paginationDiscover: document.getElementById('pagination-discover'),
                paginationFavourites: document.getElementById('pagination-favourites'),
                paginationHistory: document.getElementById('pagination-history'),
                paginationLocal: document.getElementById('pagination-local'), // 
                searchInput: document.getElementById('searchInput'),
                loadOnlineBtn: document.getElementById('loadOnlineBtn'),
                addLocalFilesBtn: document.getElementById('addLocalFilesBtn'), 
                localFileInput: document.getElementById('localFileInput'), //
                mobileMenuBtn: document.getElementById('mobileMenuBtn'),
                sidebarOverlay: document.getElementById('sidebarOverlay'),
                sidebar: document.getElementById('sidebar'),
                barAlbumArt: document.getElementById('bar-album-art'),
                barSongTitle: document.getElementById('bar-song-title'),
                barSongArtist: document.getElementById('bar-song-artist'),
                barFavBtn: document.getElementById('bar-fav-btn'),
                playPauseBtn: document.getElementById('playPauseBtn'),
                prevBtn: document.getElementById('prevBtn'),
                nextBtn: document.getElementById('nextBtn'),
                shuffleBtn: document.getElementById('shuffleBtn'),
                repeatBtn: document.getElementById('repeatBtn'),
                currentTime: document.getElementById('currentTime'),
                totalDuration: document.getElementById('totalDuration'),
                progressBar: document.getElementById('progressBar'),
                progress: document.getElementById('progress'),
                volumeSlider: document.getElementById('volumeSlider'),
                statsTotalPlays: document.getElementById('stats-total-plays'),
                statsUniqueTracks: document.getElementById('stats-unique-tracks'),
                statsTopTracks: document.getElementById('stats-top-tracks'),
                statsTopArtists: document.getElementById('stats-top-artists'),
                // 数据管理相关DOM元素
                exportFavouritesBtn: document.getElementById('exportFavouritesBtn'),
                importFavouritesBtn: document.getElementById('importFavouritesBtn'),
                favouritesFileInput: document.getElementById('favouritesFileInput'),
                exportHistoryBtn: document.getElementById('exportHistoryBtn'),
                importHistoryBtn: document.getElementById('importHistoryBtn'),
                historyFileInput: document.getElementById('historyFileInput'),
                exportAllDataBtn: document.getElementById('exportAllDataBtn'),
                importAllDataBtn: document.getElementById('importAllDataBtn'),
                allDataFileInput: document.getElementById('allDataFileInput'),
                favouritesCount: document.getElementById('favourites-count'),
                historyCount: document.getElementById('history-count'),
                // 清空按钮相关DOM元素
                clearFavouritesBtn: document.getElementById('clearFavouritesBtn'),
                clearHistoryBtn: document.getElementById('clearHistoryBtn'),
                clearAllDataBtn: document.getElementById('clearAllDataBtn'),
                // 登录状态相关DOM元素
                loginStatus: document.getElementById('loginStatus'),
                loginStatusText: document.getElementById('loginStatusText'),
            };

            const API = {
                getList: async (keyword) => {
                    const url = \`https://music-api.gdstudio.xyz/api.php?types=search&source=netease,kuwo&name=\${encodeURIComponent(keyword)}&count=100\`;
                    const response = await fetch(url);
                    if (!response.ok) throw new Error('API request failed');
                    const data = await response.json();
                    if (!Array.isArray(data)) throw new Error('Invalid API response');
                    return data.map(song => ({
                        id: \`\${song.source}_\${song.id}\`, name: song.name,
                        artists: [{ name: song.artist.join(' / ') }], album: song.album || '未知专辑',
                        source: song.source, lyric_id: song.lyric_id,
                        pic: \`https://picsum.photos/400/400?random=\${encodeURIComponent(song.name)}\`
                    }));
                },
                getSongUrl: (song) => \`https://music-api.gdstudio.xyz/api.php?types=url&id=\${song.id.split('_')[1]}&source=\${song.source}&br=320000\`
            };

            const state = {
                discoverPlaylist: [], localPlaylist: [], currentPlaylist: [], currentTrackIndex: -1,
                isPlaying: false, isShuffle: false, repeatMode: 'none',
                history: [], favourites: [], itemsPerPage: 20,
                pagination: { discover: 1, favourites: 1, history: 1, local: 1 },
                keywords: ['热门', '华语', '流行', '摇滚', '民谣', '电子', '说唱', '经典老歌', '刀郞', '张学友', '刘德华', '宋祖英', '王二妮', 'Beyond', '纯音乐', 'DJ', 'ACG'],
                lastKeyword: null, currentBlobUrl: null,
                savedPlaylists: [], currentPlaylistId: null, // 歌单相关状态
            };

            async function init() {
                try {
                    await idbHelper.init();
                    loadStateFromLocalStorage();
                    setupEventListeners();
                    await loadLocalSongs(); // 先加载本地歌曲
                    renderAllViews();
                    displaySavedPlaylists(); // 显示保存的歌单
                    showView('discover-view');
                    fetchOnlineMusic();
                    initTouchFeatures(); // 初始化触摸功能
                    initLoginStatus(); // 初始化登录状态显示
                } catch (error) {
                    console.error("初始化失败:", error);
                    alert("无法初始化数据库,本地功能将不可用。");
                }
            }

            // 清空收藏数据
            function clearFavourites() {
                console.log('clearFavourites 函数被调用');
                if (confirm('确定要清空所有收藏数据吗?此操作不可恢复!')) {
                    console.log('用户确认清空收藏数据');
                    state.favourites = [];
                    saveStateToLocalStorage();
                    renderFavourites();
                    updateAndRenderStats();
                    alert('收藏数据已清空');
                } else {
                    console.log('用户取消清空收藏数据');
                }
            }

            // 清空播放历史
            function clearHistory() {
                console.log('clearHistory 函数被调用');
                if (confirm('确定要清空所有播放历史吗?此操作不可恢复!')) {
                    console.log('用户确认清空播放历史');
                    state.history = [];
                    saveStateToLocalStorage();
                    renderHistory();
                    updateAndRenderStats();
                    alert('播放历史已清空');
                } else {
                    console.log('用户取消清空播放历史');
                }
            }

            // 清空所有数据
            function clearAllData() {
                console.log('clearAllData 函数被调用');
                if (confirm('确定要清空所有数据吗?包括收藏、播放历史、歌单等,此操作不可恢复!')) {
                    console.log('用户确认清空所有数据');
                    state.favourites = [];
                    state.history = [];
                    state.savedPlaylists = [];
                    saveStateToLocalStorage();
                    renderFavourites();
                    renderHistory();
                    updateAndRenderStats();
                    // 清空歌单显示
                    const savedPlaylists = document.getElementById('savedPlaylists');
                    if (savedPlaylists) {
                        savedPlaylists.innerHTML = '';
                    }
                    alert('所有数据已清空');
                } else {
                    console.log('用户取消清空所有数据');
                }
            }

            function setupEventListeners() {
                document.querySelectorAll('.nav-link').forEach(link => link.addEventListener('click', e => { e.preventDefault(); showView(e.currentTarget.dataset.view); }));
                dom.themeToggle.addEventListener('click', () => {
                    const isLight = document.body.classList.toggle('light-mode');
                    document.body.classList.toggle('dark-mode', !isLight);
                    localStorage.setItem('theme', isLight ? 'light' : 'dark');
                });
                dom.searchInput.addEventListener('keypress', e => { if (e.key === 'Enter' && e.target.value.trim()) fetchAndDisplaySearchResults(e.target.value.trim()); });
                dom.loadOnlineBtn.addEventListener('click', () => fetchOnlineMusic());
                dom.addLocalFilesBtn.addEventListener('click', () => dom.localFileInput.click());
                dom.localFileInput.addEventListener('change', processLocalFiles);
                dom.playPauseBtn.addEventListener('click', togglePlayPause);
                dom.barFavBtn.addEventListener('click', () => { if (dom.barFavBtn.dataset.songId) toggleFavourite(dom.barFavBtn.dataset.songId); });
                dom.nextBtn.addEventListener('click', playNext);
                dom.prevBtn.addEventListener('click', playPrevious);
                dom.shuffleBtn.addEventListener('click', toggleShuffle);
                dom.repeatBtn.addEventListener('click', toggleRepeat);
                dom.volumeSlider.addEventListener('input', e => dom.audioPlayer.volume = e.target.value);
                dom.progressBar.addEventListener('click', seek);
                dom.audioPlayer.addEventListener('timeupdate', updateProgress);
                dom.audioPlayer.addEventListener('loadedmetadata', () => dom.totalDuration.textContent = formatTime(dom.audioPlayer.duration));
                dom.audioPlayer.addEventListener('ended', handleSongEnd);
                dom.audioPlayer.addEventListener('play', () => updatePlayPauseIcon(true));
                dom.audioPlayer.addEventListener('pause', () => updatePlayPauseIcon(false));
                dom.mainContent.addEventListener('click', handleMainContentClick);

                // 移动端菜单事件监听器
                dom.mobileMenuBtn.addEventListener('click', toggleMobileMenu);
                dom.sidebarOverlay.addEventListener('click', closeMobileMenu);
                dom.sidebar.addEventListener('click', (e) => {
                    if (e.target.closest('.nav-link')) {
                        closeMobileMenu();
                    }
                });

                // 数据管理事件监听器
                dom.exportFavouritesBtn.addEventListener('click', exportFavourites);
                dom.importFavouritesBtn.addEventListener('click', () => dom.favouritesFileInput.click());
                dom.favouritesFileInput.addEventListener('change', (e) => {
                    if (e.target.files[0]) importData(e.target.files[0], 'favourites');
                });
                
                dom.exportHistoryBtn.addEventListener('click', exportHistory);
                dom.importHistoryBtn.addEventListener('click', () => dom.historyFileInput.click());
                dom.historyFileInput.addEventListener('change', (e) => {
                    if (e.target.files[0]) importData(e.target.files[0], 'history');
                });
                
                dom.exportAllDataBtn.addEventListener('click', exportAllData);
                dom.importAllDataBtn.addEventListener('click', () => dom.allDataFileInput.click());
                dom.allDataFileInput.addEventListener('change', (e) => {
                    if (e.target.files[0]) importData(e.target.files[0], 'all');
                });
                
                // 清空按钮事件监听器 - 使用事件委托
                document.addEventListener('click', function(e) {
                    if (e.target && e.target.id === 'clearFavouritesBtn') {
                        console.log('清空收藏按钮被点击');
                        clearFavourites();
                    } else if (e.target && e.target.id === 'clearHistoryBtn') {
                        console.log('清空历史按钮被点击');
                        clearHistory();
                    } else if (e.target && e.target.id === 'clearAllDataBtn') {
                        console.log('清空数据按钮被点击');
                        clearAllData();
                    }
                });
            }

            function handleMainContentClick(e) {
                const songItem = e.target.closest('.song-item');
                const pageBtn = e.target.closest('.page-btn');
                const actionBtn = e.target.closest('.action-btn');

                if (actionBtn) {
                    const songId = actionBtn.dataset.songId;
                    const allSongs = [...state.discoverPlaylist, ...state.localPlaylist, ...state.history, ...state.favourites];
                    const uniqueSongs = Array.from(new Map(allSongs.map(item => [item.id, item])).values());
                    const song = uniqueSongs.find(s => s.id.toString() === songId.toString());

                    if (actionBtn.classList.contains('fav-btn')) { toggleFavourite(songId); return; }
                    if (actionBtn.classList.contains('download-btn')) { downloadSong(song, actionBtn); return; }
                    if (actionBtn.classList.contains('delete-btn')) { deleteLocalSong(songId); return; }
                }

                if (songItem) {
                    const context = songItem.dataset.context;
                    const index = parseInt(songItem.dataset.index, 10);
                    state.currentPlaylist = getPlaylistByContext(context);
                    playSong(index);
                    return;
                }
                if (pageBtn && !pageBtn.disabled) {
                    const context = pageBtn.parentElement.dataset.context;
                    state.pagination[context] = parseInt(pageBtn.dataset.page, 10);
                    renderViewByContext(context);
                }
            }

            function getStatsTracksPlaylist() {
                // 从播放历史中统计歌曲播放次数
                const trackCounts = state.history.reduce((acc, song) => { 
                    acc[song.id] = (acc[song.id] || { ...song, count: 0 }); 
                    acc[song.id].count++; 
                    return acc; 
                }, {});
                
                // 返回按播放次数排序的歌曲列表,确保与渲染时的顺序完全一致
                return Object.values(trackCounts).sort((a, b) => b.count - a.count).slice(0, 20);
            }

            function getPlaylistByContext(context) {
                switch (context) {
                    case 'discover': return state.discoverPlaylist;
                    case 'favourites': return state.favourites;
                    case 'history': return state.history;
                    case 'local': return state.localPlaylist;
                    case 'stats-tracks': return getStatsTracksPlaylist();
                    default: return [];
                }
            }

            function renderViewByContext(context) {
                const playlist = getPlaylistByContext(context);
                const container = getListContainerByContext(context);
                renderPlaylist(playlist, container, context);
            }

            function showView(viewId) {
                document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
                document.getElementById(viewId)?.classList.add('active');
                document.querySelectorAll('.nav-link').forEach(l => l.classList.remove('active'));
                document.querySelector(\`.nav-link[data-view="\${viewId}"]\`)?.classList.add('active');
                
                if (viewId === 'local-view') {
                    renderPlaylist(state.localPlaylist, dom.localListContainer, 'local');
                }
            }

            function renderAllViews() {
                renderPlaylist(state.discoverPlaylist, dom.songListContainer, 'discover');
                renderPlaylist(state.localPlaylist, dom.localListContainer, 'local');
                renderFavourites();
                renderHistory();
                updateAndRenderStats();
            }

            function getListContainerByContext(context) {
                switch (context) {
                    case 'discover': return dom.songListContainer;
                    case 'favourites': return dom.favouritesListContainer;
                    case 'history': return dom.historyListContainer;
                    case 'local': return dom.localListContainer;
                    default: return null;
                }
            }

            function renderPlaylist(fullPlaylist, container, context) {
                const currentPage = state.pagination[context] || 1;
                const totalItems = fullPlaylist.length;
                if (!container) return;

                if (totalItems === 0) {
                    container.innerHTML = \`<p style="padding: 15px;">列表为空。</p>\`;
                    getPaginationContainer(context).innerHTML = '';
                    return;
                }
                const totalPages = Math.ceil(totalItems / state.itemsPerPage);
                const startIndex = (currentPage - 1) * state.itemsPerPage;
                const endIndex = startIndex + state.itemsPerPage;
                const paginatedItems = fullPlaylist.slice(startIndex, endIndex);

                // 检查是否为移动端
                const isMobile = window.innerWidth <= 768;

                let header = \`<div class="song-list-header">
                    <span>#</span><span>歌曲</span>\${isMobile ? '' : '<span>歌手</span><span>专辑</span>'}<span></span><span></span>
                </div>\`;
                container.innerHTML = header + paginatedItems.map((song, index) => {
                    const originalIndex = startIndex + index;
                    const isLocal = context === 'local';
                    const actionIcon = isLocal
                        ? \`<i class="action-btn delete-btn fas fa-trash" data-song-id="\${song.id}" title="从本地库删除"></i>\`
                        : \`<i class="action-btn download-btn fas fa-download" data-song-id="\${song.id}" title="下载到本地库"></i>\`;

                    return \`
                        <div class="song-item" data-index="\${originalIndex}" data-context="\${context}">
                            <span class="song-index">\${originalIndex + 1}</span>
                            <div class="song-title">
                                <span>\${song.name}\${isMobile ? \`<br><small style="color: var(--text-color-secondary); font-weight: normal;">\${song.artists.map(a => a.name).join(' / ')}</small>\` : ''}</span>
                                <span class="error-msg" id="error-\${context}-\${song.id}"></span>
                            </div>
                            \${isMobile ? '' : \`<span>\${song.artists.map(a => a.name).join(' / ')}</span><span>\${song.album}</span>\`}
                            <i class="action-btn fav-btn \${state.favourites.some(f => f.id === song.id) ? 'fas fa-heart favourited' : 'far fa-heart'}" data-song-id="\${song.id}"></i>
                            \${actionIcon}
                        </div>\`}).join('');
                renderPagination(totalPages, currentPage, context);
                updatePlaylistHighlight();
            }

            function renderPagination(totalPages, currentPage, context) {
                const container = getPaginationContainer(context);
                if (!container || totalPages <= 1) { if (container) container.innerHTML = ''; return; }
                let html = \`<button class="page-btn" data-page="\${currentPage - 1}" \${currentPage === 1 ? 'disabled' : ''}>&laquo;</button>\`;
                let startPage = Math.max(1, currentPage - 2), endPage = Math.min(totalPages, currentPage + 2);
                if (startPage > 1) html += \`<button class="page-btn" data-page="1">1</button>\${startPage > 2 ? '<span>...</span>' : ''}\`;
                for (let i = startPage; i <= endPage; i++) html += \`<button class="page-btn \${i === currentPage ? 'active' : ''}" data-page="\${i}">\${i}</button>\`;
                if (endPage < totalPages) html += \`\${endPage < totalPages - 1 ? '<span>...</span>' : ''}<button class="page-btn" data-page="\${totalPages}">\${totalPages}</button>\`;
                html += \`<button class="page-btn" data-page="\${currentPage + 1}" \${currentPage === totalPages ? 'disabled' : ''}>&raquo;</button>\`;
                container.innerHTML = html;
                container.dataset.context = context;
            }

            function getPaginationContainer(context) {
                switch (context) {
                    case 'discover': return dom.paginationDiscover;
                    case 'favourites': return dom.paginationFavourites;
                    case 'history': return dom.paginationHistory;
                    case 'local': return dom.paginationLocal;
                    default: return null;
                }
            }

            function renderFavourites() { renderPlaylist(state.favourites, dom.favouritesListContainer, 'favourites'); }
            function renderHistory() { 
                // 播放历史页面只显示每首歌曲的最新播放记录,避免重复
                const uniqueHistory = [];
                const seenIds = new Set();
                for (const song of state.history) {
                    if (!seenIds.has(song.id)) {
                        uniqueHistory.push(song);
                        seenIds.add(song.id);
                    }
                }
                renderPlaylist(uniqueHistory, dom.historyListContainer, 'history'); 
            }

            async function loadLocalSongs() {
                state.localPlaylist = await idbHelper.getSongs();
                renderPlaylist(state.localPlaylist, dom.localListContainer, 'local');
            }

            async function processLocalFiles(event) {
                const files = event.target.files;
                if (!files.length) return;
                for (const file of files) {
                    const song = {
                        id: \`local_\${Date.now()}_\${file.name}\`,
                        name: file.name.replace(/\\\\.[^\\\\/.]+$/, ""),
                        artists: [{ name: "本地文件" }],
                        album: "本地文件",
                        blob: file,
                        pic: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
                    };
                    await idbHelper.addSong(song);
                }
                await loadLocalSongs();
                alert(\`\${files.length}个文件已成功添加到本地库!\`);
            }

            async function deleteLocalSong(songId) {
                if (confirm("确定要从本地库中删除这首歌曲吗?此操作不可恢复。")) {
                    await idbHelper.deleteSong(songId);
                    await loadLocalSongs();
                }
            }

            async function fetchOnlineMusic() {
                let keyword;
                do { keyword = state.keywords[Math.floor(Math.random() * state.keywords.length)]; } while (state.keywords.length > 1 && keyword === state.lastKeyword);
                state.lastKeyword = keyword;
                dom.loadOnlineBtn.innerHTML = \`<i class="fas fa-sync-alt fa-spin"></i> 正在加载...\`;
                dom.loadOnlineBtn.disabled = true;
                await fetchAndDisplaySearchResults(keyword, true);
                dom.loadOnlineBtn.innerHTML = \`<i class="fas fa-satellite-dish"></i> 探索雷达 (\${keyword})\`;
                dom.loadOnlineBtn.disabled = false;
            }

            async function fetchAndDisplaySearchResults(keyword, shuffle = false) {
                dom.songListContainer.innerHTML = \`<p style="padding: 15px;">正在加载 "\${keyword}"...</p>\`;
                dom.paginationDiscover.innerHTML = '';
                try {
                    const songs = await API.getList(keyword);
                    if (shuffle) songs.sort(() => Math.random() - 0.5);
                    state.discoverPlaylist = songs;
                    state.pagination.discover = 1;
                    renderPlaylist(songs, dom.songListContainer, 'discover');
                } catch (error) {
                    console.error("加载在线歌曲错误:", error);
                    dom.songListContainer.innerHTML = \`<p style='padding: 15px;'>加载失败: \${error.message}</p>\`;
                }
            }

            async function playSong(index) {
                if (index < 0 || index >= state.currentPlaylist.length) return;
                state.currentTrackIndex = index;
                const song = state.currentPlaylist[index];
                updatePlayerUI(song);
                updatePlaylistHighlight();
                updatePlayPauseIcon(true);

                try {
                    if (song.blob && song.blob instanceof Blob) { // 播放本地歌曲
                        if (state.currentBlobUrl) URL.revokeObjectURL(state.currentBlobUrl);
                        state.currentBlobUrl = URL.createObjectURL(song.blob);
                        dom.audioPlayer.src = state.currentBlobUrl;
                    } else { // 播放在线歌曲
                        const urlEndpoint = API.getSongUrl(song);
                        const response = await fetch(urlEndpoint);
                        if (!response.ok) throw new Error('网络请求失败');
                        const urlData = await response.json();
                        const audioUrl = urlData.url?.replace(/^http:/, 'https');
                        if (!audioUrl) throw new Error('无法获取播放链接');
                        dom.audioPlayer.src = audioUrl;
                    }

                    await dom.audioPlayer.play();
                    addPlayHistory(song);
                    renderHistory();
                    saveStateToLocalStorage();
                } catch (error) {
                    console.error("播放失败:", error.message, song);
                    // 确定当前播放列表的上下文
                    let context = 'discover';
                    if (state.currentPlaylist === state.favourites) {
                        context = 'favourites';
                    } else if (state.currentPlaylist === state.history) {
                        context = 'history';
                    } else if (state.currentPlaylist === state.localPlaylist) {
                        context = 'local';
                    } else if (state.currentPlaylistId) {
                        // 如果是歌单播放,仍然使用discover上下文,因为歌单歌曲显示在发现音乐视图中
                        context = 'discover';
                    }
                    
                    const errorSpan = document.getElementById(\`error-\${context}-\${song.id}\`);
                    if (errorSpan) errorSpan.textContent = "无法播放";
                    updatePlayPauseIcon(false);
                    setTimeout(() => playNext(), 2000);
                }
            }

            async function downloadSong(song, buttonElement) {
                buttonElement.className = 'action-btn download-btn fas fa-spinner fa-spin';
                try {
                    const urlEndpoint = API.getSongUrl(song);
                    const response = await fetch(urlEndpoint);
                    if (!response.ok) throw new Error('网络请求失败');
                    const data = await response.json();
                    const audioUrl = data.url?.replace(/^http:/, 'https');
                    if (!audioUrl) throw new Error('无法获取下载链接');

                    const audioResponse = await fetch(audioUrl);
                    if (!audioResponse.ok) throw new Error(\`下载资源失败: \${audioResponse.statusText}\`);
                    const blob = await audioResponse.blob();

                    // 同时保存到本地库和下载到文件系统
                    const songToStore = { ...song, blob: blob };
                    await idbHelper.addSong(songToStore);

                    // 创建下载链接并触发下载
                    const fileName = \`\${song.name} - \${song.artists.map(a => a.name).join(' / ')}.mp3\`.replace(/[<>:"/\\\\|?*]/g, '_');
                    const downloadUrl = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    link.download = fileName;
                    link.style.display = 'none';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(downloadUrl);

                    await loadLocalSongs();
                    
                    // 显示下载完成提示,并提供打开下载文件夹的选项
                    showDownloadCompleteDialog(song.name, fileName);

                } catch (error) {
                    console.error("下载失败:", error);
                    alert(\`下载《\${song.name}》失败: \${error.message}\`);
                } finally {
                    buttonElement.className = 'action-btn download-btn fas fa-download';
                }
            }

            function updatePlayerUI(song) {
                if (!song) {
                    dom.barSongTitle.textContent = '--'; dom.barSongArtist.textContent = '--';
                    dom.barAlbumArt.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
                    dom.barFavBtn.dataset.songId = ''; updateFavouriteIcon(dom.barFavBtn, '');
                    return;
                }
                dom.barSongTitle.textContent = song.name;
                dom.barSongArtist.textContent = song.artists.map(a => a.name).join(' / ');
                dom.barAlbumArt.src = song.pic;
                dom.barFavBtn.dataset.songId = song.id;
                updateFavouriteIcon(dom.barFavBtn, song.id);
            }

            function updatePlaylistHighlight() {
                document.querySelectorAll('.song-item').forEach(item => {
                    const context = item.dataset.context;
                    const listForContext = getPlaylistByContext(context);
                    const index = parseInt(item.dataset.index, 10);
                    const isCurrent = state.currentPlaylist === listForContext && index === state.currentTrackIndex;
                    item.classList.toggle('current', isCurrent);
                });
            }

            function updatePlayPauseIcon(isPlaying) { state.isPlaying = isPlaying; dom.playPauseBtn.innerHTML = \`<i class="fas fa-\${isPlaying ? 'pause' : 'play'}"></i>\`; }

            function toggleFavourite(songId) {
                const allSongs = [...state.discoverPlaylist, ...state.localPlaylist, ...state.history, ...state.favourites];
                const uniqueSongs = Array.from(new Map(allSongs.map(item => [item.id, item])).values());
                const song = uniqueSongs.find(s => s.id.toString() === songId.toString());
                if (!song) return;
                const favIndex = state.favourites.findIndex(fav => fav.id.toString() === songId.toString());
                if (favIndex > -1) { state.favourites.splice(favIndex, 1); } else { state.favourites.unshift(song); }
                const totalPages = Math.ceil(state.favourites.length / state.itemsPerPage);
                if (state.pagination.favourites > totalPages) { state.pagination.favourites = totalPages || 1; }
                renderAllViews();
                if (state.currentPlaylist && state.currentPlaylist[state.currentTrackIndex]) { updatePlayerUI(state.currentPlaylist[state.currentTrackIndex]); }
                saveStateToLocalStorage();
            }

            function updateFavouriteIcon(iconElement, songId) {
                if (!songId) { iconElement.className = 'action-btn fav-btn far fa-heart'; return; }
                const isFavourited = state.favourites.some(fav => fav.id.toString() === songId.toString());
                iconElement.className = \`action-btn fav-btn \${isFavourited ? 'fas fa-heart favourited' : 'far fa-heart'}\`;
            }

            function togglePlayPause() { if (state.currentTrackIndex === -1 || !dom.audioPlayer.src) return; state.isPlaying ? dom.audioPlayer.pause() : dom.audioPlayer.play(); }
            function playNext() { let i = state.currentTrackIndex + 1; if (i >= state.currentPlaylist.length) { if (state.repeatMode === 'all') i = 0; else return; } playSong(i); }
            function playPrevious() { if (dom.audioPlayer.currentTime > 3) { dom.audioPlayer.currentTime = 0; } else { let i = state.currentTrackIndex - 1; if (i < 0) i = state.currentPlaylist.length - 1; playSong(i); } }
            function handleSongEnd() { if (state.repeatMode === 'one') playSong(state.currentTrackIndex); else playNext(); }
            function toggleShuffle() { /* shuffle logic needs to be implemented */ }
            function toggleRepeat() { const m = ['none', 'all', 'one']; state.repeatMode = m[(m.indexOf(state.repeatMode) + 1) % m.length]; dom.repeatBtn.classList.toggle('active', state.repeatMode !== 'none'); dom.audioPlayer.loop = state.repeatMode === 'one'; dom.repeatBtn.innerHTML = state.repeatMode === 'one' ? '<i class="fas fa-redo-alt"></i><sup style="font-size: 0.5em;">1</sup>' : '<i class="fas fa-redo"></i>'; }

            function saveStateToLocalStorage() { localStorage.setItem('musicDashboardData', JSON.stringify({ favourites: state.favourites, history: state.history, savedPlaylists: state.savedPlaylists })); }
            function loadStateFromLocalStorage() {
                const data = JSON.parse(localStorage.getItem('musicDashboardData') || '{}');
                state.history = data.history || []; state.favourites = data.favourites || [];
                state.savedPlaylists = data.savedPlaylists || []; // 加载保存的歌单
                const savedTheme = localStorage.getItem('theme');
                const isLight = savedTheme === 'light';
                document.body.classList.toggle('light-mode', isLight);
                document.body.classList.toggle('dark-mode', !isLight);
            }

            // 数据导出导入功能
            function exportData(data, filename) {
                const dataStr = JSON.stringify(data, null, 2);
                const dataBlob = new Blob([dataStr], { type: 'application/json' });
                const url = URL.createObjectURL(dataBlob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }

            function importData(file, dataType) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const importedData = JSON.parse(e.target.result);
                        
                        if (dataType === 'favourites') {
                            let favouritesData = null;
                            // 处理两种格式:直接数组格式和包装对象格式
                            if (Array.isArray(importedData)) {
                                favouritesData = importedData;
                            } else if (importedData.favourites && Array.isArray(importedData.favourites)) {
                                favouritesData = importedData.favourites;
                            }
                            
                            if (favouritesData) {
                                state.favourites = favouritesData;
                                alert('成功导入 ' + favouritesData.length + ' 条收藏数据');
                            } else {
                                alert('导入的收藏数据格式不正确');
                                return;
                            }
                        } else if (dataType === 'history') {
                            let historyData = null;
                            // 处理两种格式:直接数组格式和包装对象格式
                            if (Array.isArray(importedData)) {
                                historyData = importedData;
                            } else if (importedData.history && Array.isArray(importedData.history)) {
                                historyData = importedData.history;
                            }
                            
                            if (historyData) {
                                state.history = historyData;
                                alert('成功导入 ' + historyData.length + ' 条播放历史数据');
                            } else {
                                alert('导入的播放历史数据格式不正确');
                                return;
                            }
                        } else if (dataType === 'all') {
                            if (importedData.favourites && Array.isArray(importedData.favourites)) {
                                state.favourites = importedData.favourites;
                            }
                            if (importedData.history && Array.isArray(importedData.history)) {
                                state.history = importedData.history;
                            }
                            if (importedData.savedPlaylists && Array.isArray(importedData.savedPlaylists)) {
                                state.savedPlaylists = importedData.savedPlaylists;
                            }
                            alert('成功导入所有数据');
                        }
                        
                        // 保存到本地存储并更新显示
                        saveStateToLocalStorage();
                        updateAndRenderStats();
                        renderFavourites();
                        renderHistory();
                        
                    } catch (error) {
                        alert('导入失败:文件格式不正确或已损坏');
                        console.error('Import error:', error);
                    }
                };
                reader.readAsText(file);
            }

            // 导出收藏数据
            function exportFavourites() {
                const data = {
                    favourites: state.favourites,
                    exportTime: new Date().toISOString(),
                    version: '1.0'
                };
                exportData(data, 'favourites_' + new Date().toISOString().split('T')[0] + '.json');
            }

            // 导出播放历史数据
            function exportHistory() {
                const data = {
                    history: state.history,
                    exportTime: new Date().toISOString(),
                    version: '1.0'
                };
                exportData(data, 'play_history_' + new Date().toISOString().split('T')[0] + '.json');
            }

            // 导出所有数据
            function exportAllData() {
                const data = {
                    favourites: state.favourites,
                    history: state.history,
                    savedPlaylists: state.savedPlaylists,
                    exportTime: new Date().toISOString(),
                    version: '1.0'
                };
                exportData(data, 'music_data_backup_' + new Date().toISOString().split('T')[0] + '.json');
            }


            function addPlayHistory(song) { 
                // 直接添加播放记录,不删除之前的记录,这样同一首歌的多次播放都会被记录
                state.history.unshift({ ...song, playedAt: new Date().toISOString() }); 
                // 保持历史记录在合理范围内,但保留所有播放记录用于统计
                if (state.history.length > 1000) state.history = state.history.slice(0, 1000);
            }
            function updateAndRenderStats() {
                if (state.history.length === 0) { 
                    dom.statsTotalPlays.textContent = '0'; 
                    dom.statsUniqueTracks.textContent = '0'; 
                    dom.statsTopTracks.innerHTML = '<p style="padding: 15px;">暂无数据</p>'; 
                    dom.statsTopArtists.innerHTML = '<p style="padding: 15px;">暂无数据</p>'; 
                    // 更新数据计数显示
                    dom.favouritesCount.textContent = state.favourites.length;
                    dom.historyCount.textContent = state.history.length;
                    return; 
                };
                const trackCounts = state.history.reduce((acc, song) => { acc[song.id] = (acc[song.id] || { ...song, count: 0 }); acc[song.id].count++; return acc; }, {});
                const artistCounts = state.history.flatMap(s => s.artists).reduce((acc, artist) => { acc[artist.name] = (acc[artist.name] || { name: artist.name, count: 0 }); acc[artist.name].count++; return acc; }, {});
                dom.statsTotalPlays.textContent = state.history.length;
                dom.statsUniqueTracks.textContent = new Set(state.history.map(s => s.id)).size;
                
                // 更新数据计数显示
                dom.favouritesCount.textContent = state.favourites.length;
                dom.historyCount.textContent = state.history.length;
                
                // 修复统计列表HTML结构,确保移动端也能显示完整信息
                const isMobile = window.innerWidth <= 768;
                
                // 播放最多的歌曲
                const topTracksHeader = '<div class="song-list-header"><span>#</span><span>歌曲</span>' + (isMobile ? '' : '<span>歌手</span>') + '<span>播放次数</span><span></span></div>';
                const topTracksList = getStatsTracksPlaylist(); // 使用相同的函数确保一致性
                const topTracksItems = topTracksList.map((s, i) => {
                    const artistInfo = isMobile ? '<br><small style="color: var(--text-color-secondary);">' + s.artists.map(a => a.name).join(' / ') + '</small>' : '';
                    const artistColumn = isMobile ? '' : '<span>' + s.artists.map(a => a.name).join(' / ') + '</span>';
                    return '<div class="song-item" data-index="' + i + '" data-context="stats-tracks">' +
                        '<span>' + (i + 1) + '</span>' +
                        '<span class="song-title">' + s.name + artistInfo + '</span>' +
                        artistColumn +
                        '<span>' + s.count + ' 次</span>' +
                        '<span></span>' +
                        '</div>';
                }).join('');
                dom.statsTopTracks.innerHTML = topTracksHeader + topTracksItems;
                
                // 最常听的歌手
                const topArtistsHeader = '<div class="song-list-header"><span>#</span><span>歌手</span><span>播放次数</span></div>';
                const topArtistsItems = Object.values(artistCounts).sort((a, b) => b.count - a.count).slice(0, 10).map((a, i) => 
                    '<div class="song-item">' +
                        '<span>' + (i + 1) + '</span>' +
                        '<span class="song-title">' + a.name + '</span>' +
                        '<span>' + a.count + ' 次</span>' +
                    '</div>'
                ).join('');
                dom.statsTopArtists.innerHTML = topArtistsHeader + topArtistsItems;
            }
            function updateProgress() { const { currentTime, duration } = dom.audioPlayer; if (duration) { dom.progress.style.width = \`\${(currentTime / duration) * 100}%\`; dom.currentTime.textContent = formatTime(duration ? currentTime : 0); } }
            function seek(e) { const duration = dom.audioPlayer.duration; if (duration) dom.audioPlayer.currentTime = (e.offsetX / dom.progressBar.clientWidth) * duration; }
            function formatTime(seconds) { const min = Math.floor(seconds / 60); const sec = Math.floor(seconds % 60); return \`\${min}:\${sec < 10 ? '0' : ''}\${sec}\`; }

            // 移动端菜单功能
            function toggleMobileMenu() {
                const isOpen = dom.sidebar.classList.contains('open');
                if (isOpen) {
                    closeMobileMenu();
                } else {
                    openMobileMenu();
                }
            }

            function openMobileMenu() {
                dom.sidebar.classList.add('open');
                dom.sidebarOverlay.classList.add('show');
                document.body.style.overflow = 'hidden';
            }

            function closeMobileMenu() {
                dom.sidebar.classList.remove('open');
                dom.sidebarOverlay.classList.remove('show');
                document.body.style.overflow = '';
            }

            // 初始化登录状态显示
            function initLoginStatus() {
                if (dom.loginStatus && dom.loginStatusText) {
                    // 设置登录状态显示
                    dom.loginStatusText.textContent = '已登录 (10天有效)';
                    
                    // 可以添加倒计时功能,显示剩余时间
                    updateLoginStatusDisplay();
                }
            }

            // 更新登录状态显示
            function updateLoginStatusDisplay() {
                if (dom.loginStatusText) {
                    // 这里可以添加更复杂的逻辑,比如显示剩余时间
                    // 由于Cookie的Max-Age是服务器端设置的,客户端无法直接获取剩余时间
                    // 所以这里只显示基本的登录状态
                    dom.loginStatusText.textContent = '已登录 (10天有效)';
                }
            }

            // 触摸友好功能
            function initTouchFeatures() {
                // 防止双击缩放
                let lastTouchEnd = 0;
                document.addEventListener('touchend', function(event) {
                    const now = (new Date()).getTime();
                    if (now - lastTouchEnd <= 300) {
                        event.preventDefault();
                    }
                    lastTouchEnd = now;
                }, false);

                // 添加触摸反馈
                const touchableElements = document.querySelectorAll('.action-btn, .control-btn, .page-btn, .nav-link');
                touchableElements.forEach(element => {
                    element.addEventListener('touchstart', function() {
                        this.style.transform = 'scale(0.95)';
                    }, { passive: true });

                    element.addEventListener('touchend', function() {
                        this.style.transform = '';
                    }, { passive: true });
                });

                // 改进进度条触摸
                if (dom.progressBar) {
                    dom.progressBar.addEventListener('touchstart', function(e) {
                        e.preventDefault();
                        seek(e.touches[0]);
                    }, { passive: false });

                    dom.progressBar.addEventListener('touchmove', function(e) {
                        e.preventDefault();
                        seek(e.touches[0]);
                    }, { passive: false });
                }

                // 添加长按功能到歌曲项
                const songItems = document.querySelectorAll('.song-item');
                songItems.forEach(item => {
                    let longPressTimer;
                    let startTime;
                    let startX, startY;

                    item.addEventListener('touchstart', function(e) {
                        startTime = Date.now();
                        startX = e.touches[0].clientX;
                        startY = e.touches[0].clientY;

                        longPressTimer = setTimeout(() => {
                            // 长按显示更多选项
                            showSongOptions(this);
                        }, 500);
                    }, { passive: true });

                    item.addEventListener('touchmove', function(e) {
                        const moveX = Math.abs(e.touches[0].clientX - startX);
                        const moveY = Math.abs(e.touches[0].clientY - startY);

                        if (moveX > 10 || moveY > 10) {
                            clearTimeout(longPressTimer);
                        }
                    }, { passive: true });

                    item.addEventListener('touchend', function(e) {
                        clearTimeout(longPressTimer);
                        const duration = Date.now() - startTime;

                        if (duration < 500) {
                            // 短按播放歌曲
                            const context = this.dataset.context;
                            const index = parseInt(this.dataset.index, 10);
                            state.currentPlaylist = getPlaylistByContext(context);
                            playSong(index);
                        }
                    }, { passive: true });
                });
            }

            // 显示歌曲选项菜单
            function showSongOptions(songItem) {
                const songId = songItem.querySelector('.fav-btn').dataset.songId;
                const existingMenu = document.querySelector('.song-options-menu');
                if (existingMenu) existingMenu.remove();

                const menu = document.createElement('div');
                menu.className = 'song-options-menu';
                
                const downloadFunc = function() {
                    const button = {dataset: {songId: songId}, className: 'action-btn download-btn fas fa-spinner fa-spin'};
                    downloadSong(null, button);
                    menu.remove();
                };
                
                const toggleFunc = function() {
                    toggleFavourite(songId);
                    menu.remove();
                };

                menu.innerHTML = \`
                    <div class="song-options-overlay" onclick="this.parentElement.remove()"></div>
                    <div class="song-options-content">
                        <button class="option-btn" onclick="(\${toggleFunc.toString()})()">
                            <i class="fas fa-heart"></i> \${state.favourites.some(f => f.id === songId) ? '取消收藏' : '添加收藏'}
                        </button>
                        <button class="option-btn" onclick="(\${downloadFunc.toString()})()">
                            <i class="fas fa-download"></i> 下载到本地
                        </button>
                    </div>
                \`;
                document.body.appendChild(menu);
            }

            // 显示下载完成对话框
            function showDownloadCompleteDialog(songName, fileName) {
                const existingDialog = document.querySelector('.download-dialog');
                if (existingDialog) existingDialog.remove();

                const dialog = document.createElement('div');
                dialog.className = 'download-dialog';
                
                dialog.innerHTML = \`
                    <div class="download-dialog-content">
                        <div class="download-dialog-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="download-dialog-title">下载完成!</div>
                        <div class="download-dialog-message">
                            《\${songName}》已成功下载到本地库和下载文件夹<br>
                            文件名:\${fileName}
                        </div>
                        <div class="download-dialog-buttons">
                            <button class="download-dialog-btn secondary" onclick="this.closest('.download-dialog').remove()">
                                知道了
                            </button>
                            <button class="download-dialog-btn primary" onclick="openDownloadsFolder()">
                                <i class="fas fa-folder-open"></i> 打开下载文件夹
                            </button>
                        </div>
                    </div>
                \`;
                
                document.body.appendChild(dialog);
                
                // 3秒后自动关闭对话框
                setTimeout(() => {
                    if (dialog.parentNode) {
                        dialog.remove();
                    }
                }, 5000);
            }

            // 打开下载文件夹
            function openDownloadsFolder() {
                // 尝试使用现代浏览器的文件系统API
                if ('showDirectoryPicker' in window) {
                    // 现代浏览器支持,但需要用户手动选择文件夹
                    alert('请手动打开浏览器的下载文件夹查看文件。\\n\\n通常位置:\\n• Chrome: C:\\\\Users\\\\用户名\\\\Downloads\\\\\\n• Firefox: C:\\\\Users\\\\用户名\\\\Downloads\\\\\\n• Edge: C:\\\\Users\\\\用户名\\\\Downloads\\\\');
                } else {
                    // 传统方法,提供下载文件夹路径信息
                    const userAgent = navigator.userAgent;
                    let downloadPath = '';
                    
                    if (userAgent.includes('Chrome')) {
                        downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\';
                    } else if (userAgent.includes('Firefox')) {
                        downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\';
                    } else if (userAgent.includes('Edge')) {
                        downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\';
                    } else {
                        downloadPath = '浏览器的默认下载文件夹';
                    }
                    
                    alert(\`文件已下载到:\${downloadPath}\\n\\n请手动打开该文件夹查看下载的文件。\\n\\n提示:\\n• 按 Win + R 打开运行对话框\\n• 输入 %USERPROFILE%\\\\Downloads 并回车\\n• 或者直接在文件资源管理器中打开下载文件夹\`);
                }
                
                // 关闭对话框
                const dialog = document.querySelector('.download-dialog');
                if (dialog) dialog.remove();
            }

            // 将歌单相关函数设为全局,以便HTML中的onclick可以调用
            window.importPlaylist = async function() {
                const playlistIdInput = document.getElementById('playlistIdInput');
                const playlistId = playlistIdInput.value.trim();

                if (!playlistId) {
                    showNotification('请输入歌单ID或链接', 'warning');
                    return;
                }

                // 提取歌单ID(支持完整链接)
                let id = playlistId;
                if (playlistId.includes('playlist?id=')) {
                    id = playlistId.split('playlist?id=')[1].split('&')[0];
                } else if (playlistId.includes('playlist/')) {
                    id = playlistId.split('playlist/')[1].split('?')[0];
                }

                // 检查歌单是否已存在
                if (state.savedPlaylists.some(p => p.id === id)) {
                    showNotification('该歌单已存在', 'warning');
                    return;
                }

                try {
                    showNotification('正在导入歌单...', 'info');

                    // 获取歌单信息
                    const response = await fetch(\`https://music-api.gdstudio.xyz/api.php?types=playlist&source=netease&id=\${id}\`);
                    const data = await response.json();

                    if (data && data.code === 200 && data.playlist) {
                        // 转换歌单数据结构以匹配播放器需要的格式
                        const tracks = data.playlist.tracks.map(track => ({
                            id: \`netease_\${track.id}\`,
                            name: track.name,
                            artists: track.ar ? track.ar.map(artist => ({ name: artist.name })) : [{ name: '未知歌手' }],
                            album: track.al ? track.al.name : '未知专辑',
                            source: 'netease',
                            pic: track.al ? track.al.picUrl : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
                        }));

                        const playlist = {
                            id: id,
                            name: data.playlist.name,
                            tracks: tracks,
                            cover: data.playlist.coverImgUrl || '',
                            playCount: data.playlist.playCount || 0,
                            description: data.playlist.description || '',
                            creator: data.playlist.creator ? data.playlist.creator.nickname : '未知用户',
                            tags: data.playlist.tags || [],
                            createTime: new Date().toISOString()
                        };

                        // 保存到本地存储
                        state.savedPlaylists.push(playlist);
                        saveStateToLocalStorage();

                        // 更新UI
                        displaySavedPlaylists();

                        playlistIdInput.value = '';
                        showNotification(\`歌单 "\${playlist.name}" 导入成功!\`, 'success');
                    } else {
                        showNotification('无法获取歌单信息,请检查ID是否正确', 'error');
                    }
                } catch (error) {
                    console.error('导入歌单失败:', error);
                    showNotification('导入歌单失败,请检查网络连接', 'error');
                }
            }

            // 显示保存的歌单
            window.displaySavedPlaylists = function() {
                const container = document.getElementById('savedPlaylists');
                if (!container) return;
                
                container.innerHTML = '';

                if (state.savedPlaylists.length === 0) {
                    container.innerHTML = '<div class="empty-state"><div>暂无保存的歌单</div></div>';
                    return;
                }

                state.savedPlaylists.forEach((playlist, index) => {
                    const playlistItem = document.createElement('div');
                    playlistItem.className = 'playlist-item';
                    playlistItem.onclick = () => playPlaylist(index);
                    playlistItem.innerHTML = \`
                        <div class="playlist-info">
                            <div class="playlist-name">\${playlist.name}</div>
                            <div class="playlist-count">\${playlist.tracks.length} 首歌曲</div>
                        </div>
                        <div class="playlist-actions">
                            <button class="playlist-action-btn" onclick="playPlaylist(\${index}); event.stopPropagation();" title="播放歌单">
                                <i class="fas fa-play"></i>
                            </button>
                            <button class="playlist-action-btn" onclick="updatePlaylist(\${index}); event.stopPropagation();" title="更新歌单">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="playlist-action-btn delete" onclick="deletePlaylist(\${index}); event.stopPropagation();" title="删除歌单">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    \`;
                    container.appendChild(playlistItem);
                });
            }

            // 播放歌单
            window.playPlaylist = function(index) {
                if (index < 0 || index >= state.savedPlaylists.length) return;

                const playlist = state.savedPlaylists[index];
                state.currentPlaylist = playlist.tracks;
                state.currentPlaylistId = playlist.id;
                state.currentTrackIndex = 0;

                // 同时更新discoverPlaylist,这样点击歌曲时能正确播放
                state.discoverPlaylist = playlist.tracks;
                state.pagination.discover = 1;

                // 更新发现音乐视图的显示
                renderPlaylist(playlist.tracks, dom.songListContainer, 'discover');
                
                // 播放第一首歌
                if (playlist.tracks.length > 0) {
                    playSong(0);
                }

                showNotification(\`开始播放歌单 "\${playlist.name}"\`, 'success');
            }

            // 删除歌单
            window.deletePlaylist = function(index) {
                if (index < 0 || index >= state.savedPlaylists.length) return;

                const playlist = state.savedPlaylists[index];
                if (confirm(\`确定要删除歌单 "\${playlist.name}" 吗?\`)) {
                    state.savedPlaylists.splice(index, 1);
                    saveStateToLocalStorage();
                    displaySavedPlaylists();
                    showNotification('歌单已删除', 'success');
                }
            }

            // 更新歌单
            window.updatePlaylist = async function(index) {
                if (index < 0 || index >= state.savedPlaylists.length) return;

                const playlist = state.savedPlaylists[index];
                try {
                    showNotification('正在更新歌单...', 'info');

                    // 重新获取歌单信息
                    const response = await fetch(\`https://music-api.gdstudio.xyz/api.php?types=playlist&source=netease&id=\${playlist.id}\`);
                    const data = await response.json();

                    if (data && data.code === 200 && data.playlist) {
                        // 转换歌单数据结构
                        const tracks = data.playlist.tracks.map(track => ({
                            id: \`netease_\${track.id}\`,
                            name: track.name,
                            artists: track.ar ? track.ar.map(artist => ({ name: artist.name })) : [{ name: '未知歌手' }],
                            album: track.al ? track.al.name : '未知专辑',
                            source: 'netease',
                            pic: track.al ? track.al.picUrl : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
                        }));

                        // 更新歌单信息
                        state.savedPlaylists[index].tracks = tracks;
                        state.savedPlaylists[index].name = data.playlist.name;
                        state.savedPlaylists[index].cover = data.playlist.coverImgUrl || '';
                        state.savedPlaylists[index].playCount = data.playlist.playCount || 0;
                        state.savedPlaylists[index].description = data.playlist.description || '';
                        state.savedPlaylists[index].creator = data.playlist.creator ? data.playlist.creator.nickname : '未知用户';
                        state.savedPlaylists[index].tags = data.playlist.tags || [];

                        saveStateToLocalStorage();
                        displaySavedPlaylists();

                        // 如果当前正在播放这个歌单,更新当前播放列表
                        if (state.currentPlaylistId === playlist.id) {
                            state.currentPlaylist = tracks;
                            renderPlaylist(tracks, dom.songListContainer, 'discover');
                        }

                        showNotification(\`歌单 "\${data.playlist.name}" 更新成功!\`, 'success');
                    } else {
                        showNotification('更新歌单失败,请检查网络连接', 'error');
                    }
                } catch (error) {
                    console.error('更新歌单失败:', error);
                    showNotification('更新歌单失败,请检查网络连接', 'error');
                }
            }

            // 显示通知
            window.showNotification = function(message, type = 'info') {
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = \`notification notification-\${type}\`;
                notification.style.cssText = \`
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: var(--component-bg);
                    color: var(--text-color-primary);
                    padding: 12px 20px;
                    border-radius: 8px;
                    border: 1px solid var(--border-color);
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
                    z-index: 10000;
                    max-width: 300px;
                    word-wrap: break-word;
                    animation: slideInRight 0.3s ease;
                \`;

                // 根据类型设置颜色
                if (type === 'success') {
                    notification.style.borderLeftColor = 'var(--download-color)';
                } else if (type === 'error') {
                    notification.style.borderLeftColor = 'var(--danger-color)';
                } else if (type === 'warning') {
                    notification.style.borderLeftColor = '#ff9800';
                } else {
                    notification.style.borderLeftColor = 'var(--accent-color)';
                }

                notification.textContent = message;
                document.body.appendChild(notification);

                // 3秒后自动移除
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.style.animation = 'slideOutRight 0.3s ease';
                        setTimeout(() => {
                            if (notification.parentNode) {
                                notification.remove();
                            }
                        }, 300);
                    }
                }, 3000);
            }

            // 添加CSS动画
            const style = document.createElement('style');
            style.textContent = \`
                @keyframes slideInRight {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOutRight {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            \`;
            document.head.appendChild(style);

            init();
        });
    <\/script>

</body>

</html>`;

        return new Response(html, {
            headers: {
                'Content-Type': 'text/html; charset=utf-8',
                ...corsHeaders,
            },
        });
    },
};

// 登录页面渲染函数
function renderLoginPage(msg = '') {
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ws01 Music - 登录</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>♬</text></svg>">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans SC', 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradient-animation 15s ease infinite;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        @keyframes gradient-animation {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .login-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 40px 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 100%;
            max-width: 400px;
            text-align: center;
            animation: fadeInUp 0.6s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin-bottom: 20px;
            color: #333;
        }

        .logo i {
            font-size: 32px;
            color: #0F52BA;
        }

        .logo span {
            font-size: 24px;
            font-weight: bold;
        }

        .login-title {
            font-size: 22px;
            color: #333;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .login-subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .error-message {
            background: rgba(211, 47, 47, 0.1);
            color: #d32f2f;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            border: 1px solid rgba(211, 47, 47, 0.2);
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-group label {
            display: block;
            color: #333;
            margin-bottom: 8px;
            font-weight: 500;
            font-size: 14px;
        }

        .password-wrapper {
            position: relative;
            width: 100%;
        }

        .password-wrapper input {
            width: 100%;
            padding: 15px 50px 15px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
        }

        .password-wrapper input:focus {
            border-color: #0F52BA;
            box-shadow: 0 0 0 3px rgba(15, 82, 186, 0.1);
            background: #fff;
        }

        .password-wrapper input::placeholder {
            color: #999;
        }

        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 18px;
            transition: color 0.3s ease;
            padding: 5px;
        }

        .toggle-password:hover {
            color: #0F52BA;
        }

        .login-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #0F52BA, #00318C);
            border: none;
            border-radius: 12px;
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
        }

        .login-btn:hover {
            background: linear-gradient(135deg, #00318C, #001F5C);
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(15, 82, 186, 0.3);
        }

        .login-btn:active {
            transform: translateY(0);
        }

        .login-footer {
            margin-top: 20px;
            color: #666;
            font-size: 12px;
        }

        .login-footer a {
            color: #0F52BA;
            text-decoration: none;
        }

        .login-footer a:hover {
            text-decoration: underline;
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
            .login-container {
                margin: 20px;
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <i class="fas fa-headphones-alt"></i>
            <span>ws01 Music</span>
        </div>

        <h1 class="login-title">🔒 请输入密码</h1>
        <p class="login-subtitle">访问个人音乐库需要身份验证<br><small style="color: #888; font-size: 12px;">登录后10天有效,无需重复输入密码</small></p>

        ${msg ? `<div class="error-message">${msg}</div>` : ''}

        <form method="POST" action="/login">
            <div class="form-group">
                <label for="password">管理员密码</label>
                <div class="password-wrapper">
                    <input type="password" id="password" name="password" placeholder="输入登录密码" required>
                    <button type="button" class="toggle-password" onclick="togglePassword()">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="login-btn">
                <i class="fas fa-sign-in-alt"></i> 登录
            </button>
        </form>

        <div class="login-footer">
            <p>© 2025 ws01 Music 个人音乐库</p>
        </div>
    </div>

    <script>
        function togglePassword() {
            const input = document.getElementById('password');
            const icon = document.querySelector('.toggle-password i');

            if (input.type === 'password') {
                input.type = 'text';
                icon.className = 'fas fa-eye-slash';
            } else {
                input.type = 'password';
                icon.className = 'fas fa-eye';
            }
        }

        // 回车键登录
        document.getElementById('password').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.querySelector('form').submit();
            }
        });

        // 自动聚焦到密码输入框
        window.addEventListener('load', function() {
            document.getElementById('password').focus();
        });
    </script>
</body>
</html>`;
}

预览

export default { async fetch(request, env, ctx) { // 设置CORS头 const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', };

// 处理预检请求 if (request.method === 'OPTIONS') { return new Response(null, { headers: corsHeaders }); }

const url = new URL(request.url);

// 登录逻辑 if (url.pathname === '/login' && request.method === 'POST') { const formData = await request.formData(); const password = formData.get('password'); const adminPassword = env.ADMIN_PASSWORD || 'admin123'; // 默认密码,可通过环境变量设置 if (password === adminPassword) { // 登录成功,设置 Cookie, 默认24小时等于86400秒,自用30天等于2592000秒 console.log('登录成功,设置Cookie'); return new Response('', { status: 302, headers: { 'Set-Cookie': auth=1; Path=/; HttpOnly; SameSite=Lax; Max-Age=864000, 'Location': '/' } }); } else { return new Response(renderLoginPage('密码错误,请重试!'), { headers: { 'Content-Type': 'text/html;charset=utf-8' } }); } }

// 退出逻辑 if (url.pathname === '/logout') { return new Response('', { status: 302, headers: { 'Set-Cookie': auth=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0, 'Location': '/' } }); }

// 检查是否已登录 const cookie = request.headers.get('Cookie') || ''; console.log('检查Cookie:', cookie); if (!cookie.includes('auth=1')) { console.log('未找到有效Cookie,重定向到登录页面'); return new Response(renderLoginPage(), { headers: { 'Content-Type': 'text/html;charset=utf-8' } }); } console.log('Cookie验证通过,允许访问');

const html = <!DOCTYPE html> <html lang="zh-CN">

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ws01 Music - 个人音乐库</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"> <link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>♬</text></svg>"> <style> :root { --font-main: 'Noto Sans SC', 'Segoe UI', Arial, sans-serif; --accent-color: #0F52BA; --accent-color-hover: #00318C; --danger-color: #D32F2F; --download-color: #27ae60;

--bg-color-dark: #191A1C; --sidebar-bg: rgba(17, 18, 19, 0.75); --main-bg: rgba(25, 26, 28, 0.6); --player-bg: rgba(17, 18, 19, 0.75);

--text-color-primary: #F5F5F5; --text-color-secondary: #A0A0A0;

--component-bg: rgba(44, 45, 47, 0.7); --hover-bg: rgba(58, 59, 61, 0.8); --border-color: rgba(80, 80, 80, 0.5); }

.light-mode { --accent-color: #0F52BA; --accent-color-hover: #0039A6; --download-color: #2ecc71; --danger-color: #c0392b;

--bg-color-dark: #F4F6F8; --sidebar-bg: rgba(255, 255, 255, 0.7); --main-bg: rgba(244, 246, 248, 0.65); --player-bg: rgba(255, 255, 255, 0.7);

--text-color-primary: #121212; --text-color-secondary: #6B7280;

--component-bg: rgba(255, 255, 255, 0.6); --hover-bg: rgba(234, 236, 239, 0.7); --border-color: rgba(200, 200, 200, 0.6); }

* { margin: 0; padding: 0; box-sizing: border-box; }

::-webkit-scrollbar { width: 8px; }

::-webkit-scrollbar-track { background: transparent; }

::-webkit-scrollbar-thumb { background: var(--hover-bg); border-radius: 4px; }

::-webkit-scrollbar-thumb:hover { background: var(--accent-color); }

body { font-family: var(--font-main); color: var(--text-color-primary); background-color: var(--bg-color-dark); overflow: hidden; transition: background-color 0.3s; }

@keyframes gradient-animation { 0% { background-position: 0% 50%; }

50% { background-position: 100% 50%; }

100% { background-position: 0% 50%; } }

.app-container { display: grid; grid-template-columns: 240px 1fr; grid-template-rows: 1fr auto; grid-template-areas: "sidebar main" "player player"; height: 100vh; width: 100vw; background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); background-size: 400% 400%; animation: gradient-animation 15s ease infinite; }

.sidebar { grid-area: sidebar; background-color: var(--sidebar-bg); padding: 24px; display: flex; flex-direction: column; border-right: 1px solid var(--border-color); box-shadow: 2px 0 15px rgba(0, 0, 0, 0.2); transition: background-color 0.3s, border-color 0.3s; backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); }

.sidebar h1 { color: var(--text-color-primary); margin-bottom: 32px; display: flex; align-items: center; gap: 12px; }

.sidebar nav ul { list-style: none; }

.sidebar nav a { color: var(--text-color-secondary); display: flex; align-items: center; gap: 15px; padding: 12px; margin-bottom: 8px; border-radius: 8px; text-decoration: none; font-weight: 500; transition: all 0.2s ease; }

.sidebar nav a:hover { color: var(--text-color-primary); background-color: var(--hover-bg); }

.sidebar nav a.active { color: var(--accent-color); font-weight: 700; background-color: var(--hover-bg); }

.main-content { grid-area: main; overflow-y: auto; padding: 24px 32px; background-color: var(--main-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }

.search-area { position: relative; margin-bottom: 24px; }

.search-area i.fa-search { position: absolute; left: 20px; top: 50%; transform: translateY(-50%); color: var(--text-color-secondary); }

.search-area input { background-color: var(--component-bg); border: 1px solid var(--border-color); color: var(--text-color-primary); width: 100%; padding: 12px 20px 12px 50px; font-size: 1em; border-radius: 50px; outline: none; transition: all 0.3s; }

.search-area input:focus { border-color: var(--accent-color); box-shadow: 0 0 10px rgba(15, 82, 186, 0.2); }

.song-list-header, .song-item { display: grid; grid-template-columns: 40px 3fr 2fr 2fr 40px 40px; align-items: center; padding: 10px 15px; gap: 15px; }

#stats-top-tracks .song-item, #stats-top-artists .song-item { grid-template-columns: 40px 3fr 2fr 1fr 40px; }

.song-list-header { color: var(--text-color-secondary); font-size: 0.8em; border-bottom: 1px solid var(--border-color); background-color: var(--component-bg); border-radius: 8px 8px 0 0; margin-top: 10px; }

.song-item { border-radius: 8px; transition: background-color 0.2s; cursor: pointer; font-size: 0.9em; border-bottom: 1px solid var(--border-color); }

.song-list>.song-item:last-child { border-bottom: none; }

.song-item:hover { background-color: var(--hover-bg); }

.song-item.current { background-color: var(--hover-bg); }

.song-item.current .song-title>span:first-child { color: var(--accent-color); }

.song-item .song-title { display: flex; flex-direction: column; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

.song-item .song-title .error-msg { font-size: 0.8em; color: var(--danger-color); margin-top: 4px; }

.action-btn { color: var(--text-color-secondary); cursor: pointer; transition: color 0.2s, transform 0.2s; text-align: center; }

.action-btn:hover { transform: scale(1.2); }

.fav-btn.favourited { color: var(--danger-color); }

.download-btn:hover { color: var(--download-color); }

.delete-btn:hover { color: var(--danger-color); }

.now-playing-bar { grid-area: player; background-color: var(--player-bg); border-top: 1px solid var(--border-color); padding: 15px 30px; display: grid; grid-template-columns: 1fr 2fr 1fr; align-items: center; gap: 20px; box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.2); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); }

.song-info-bar { display: flex; align-items: center; gap: 15px; min-width: 0; }

.song-info-bar img { width: 56px; height: 56px; border-radius: 8px; object-fit: cover; background-color: var(--hover-bg); }

.song-info-bar .fav-btn { font-size: 1.2em; }

.song-info-bar div { overflow: hidden; }

.song-info-bar div h3, .song-info-bar div p { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.player-controls { display: flex; flex-direction: column; align-items: center; }

.control-buttons { display: flex; align-items: center; justify-content: center; gap: 24px; margin-bottom: 12px; }

#playPauseBtn { background-color: var(--text-color-primary); color: var(--player-bg); width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.5em; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; cursor: pointer; border: none; }

.light-mode #playPauseBtn { color: #FFFFFF; background-color: #121212; }

#playPauseBtn:hover { transform: scale(1.1); }

.control-btn { background: none; border: none; color: var(--text-color-secondary); font-size: 1.1em; cursor: pointer; transition: all 0.2s; }

.control-btn:hover { color: var(--text-color-primary); transform: scale(1.15); }

.control-btn.active { color: var(--accent-color); }

.progress-area { display: flex; align-items: center; gap: 10px; width: 100%; max-width: 500px; }

.progress-bar { flex-grow: 1; height: 6px; background-color: var(--hover-bg); border-radius: 3px; cursor: pointer; }

.progress { height: 100%; width: 0%; background-color: var(--accent-color); border-radius: 3px; }

.time-display span { font-size: 0.75em; color: var(--text-color-secondary); }

.extra-controls { display: flex; justify-content: flex-end; align-items: center; gap: 15px; }

.volume-area { display: flex; align-items: center; gap: 8px; width: 120px; }

input[type="range"] { -webkit-appearance: none; appearance: none; width: 100%; height: 6px; background-color: var(--hover-bg); border-radius: 3px; outline: none; cursor: pointer; }

input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 16px; height: 16px; background-color: var(--text-color-primary); border-radius: 50%; transition: background-color 0.3s; }

input[type="range"]:hover::-webkit-slider-thumb { background-color: var(--accent-color); }

.sidebar .theme-switcher { margin-top: auto; cursor: pointer; display: flex; align-items: center; gap: 15px; padding: 12px; border-radius: 8px; background-color: var(--component-bg); color: var(--text-color-secondary); font-weight: 500; transition: all 0.3s; }

.sidebar .theme-switcher:hover { color: var(--text-color-primary); background-color: var(--hover-bg); }

.view { display: none; }

.view.active { display: block; animation: fadeIn 0.5s ease; }

@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); }

to { opacity: 1; transform: translateY(0); } }

.list-section h2, .view>h2 { margin-bottom: 20px; font-size: 1.8rem; color: var(--text-color-primary); border-bottom: 2px solid var(--accent-color); padding-bottom: 10px; }

/ 数据管理界面样式 / .data-management-controls { background: var(--card-bg); border-radius: 12px; padding: 24px; margin-bottom: 20px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }

.data-control-group { margin-bottom: 24px; padding: 16px; background: var(--bg-color); border-radius: 8px; border: 1px solid var(--border-color); }

.data-control-group:last-child { margin-bottom: 0; }

.data-control-group h3 { margin: 0 0 12px 0; font-size: 1.2rem; color: var(--text-color-primary); display: flex; align-items: center; gap: 8px; }

.data-control-group h3::before { content: ''; width: 4px; height: 20px; background: var(--accent-color); border-radius: 2px; }

.data-control-group .control-buttons { display: flex; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }

.data-control-group .control-btn { background: var(--accent-color); color: white; border: none; padding: 10px 16px; border-radius: 6px; font-size: 0.9rem; font-weight: 500; cursor: pointer; transition: all 0.2s ease; display: flex; align-items: center; gap: 6px; }

.data-control-group .control-btn:hover { background: var(--accent-color-hover); transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); }

.data-control-group .control-btn:active { transform: translateY(0); }

.data-info { margin: 0; font-size: 0.9rem; color: var(--text-color-secondary); font-weight: 500; }

.data-info span { color: var(--accent-color); font-weight: 600; }

/ 清空按钮样式 / .control-btn.clear-btn { background: #e74c3c; color: white; }

.control-btn.clear-btn:hover { background: #c0392b; transform: translateY(-1px); }

.control-btn.clear-btn:active { transform: translateY(0); }

/ 移动端数据管理适配 / @media (max-width: 768px) { .data-management-controls { padding: 16px; }

.data-control-group { padding: 12px; }

.data-control-group .control-buttons { gap: 8px; }

.data-control-group .control-btn { padding: 8px 12px; font-size: 0.85rem; } }

.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }

.stat-card { background-color: var(--component-bg); padding: 20px; border-radius: 12px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }

.stat-card h3 { color: var(--text-color-secondary); font-size: 0.9rem; margin-bottom: 8px; }

.stat-card p { font-size: 2rem; font-weight: bold; }

.pagination-controls { display: flex; justify-content: center; align-items: center; padding: 20px 0; gap: 8px; user-select: none; }

.page-btn { background-color: var(--component-bg); border: 1px solid var(--border-color); color: var(--text-color-secondary); padding: 8px 14px; min-width: 40px; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.2s ease; }

.page-btn:hover { background-color: var(--hover-bg); color: var(--text-color-primary); border-color: var(--accent-color); }

.page-btn.active { background-color: var(--accent-color); color: #FFFFFF; border-color: var(--accent-color); font-weight: 700; }

.page-btn:disabled { opacity: 0.5; cursor: not-allowed; }

.action-button { padding: 10px 15px; margin-bottom: 20px; border-radius: 20px; border: none; background: var(--accent-color); color: white; font-weight: bold; cursor: pointer; min-width: 120px; }

/ 移动端响应式设计 / @media (max-width: 768px) { .app-container { grid-template-columns: 1fr; grid-template-rows: 1fr auto auto; grid-template-areas: "main" "player" "sidebar"; }

.sidebar { grid-area: sidebar; position: fixed; top: 0; left: -280px; width: 280px; height: 100vh; z-index: 1000; transition: left 0.3s ease; background-color: var(--sidebar-bg); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); box-shadow: 2px 0 15px rgba(0, 0, 0, 0.3); }

.sidebar.open { left: 0; }

.sidebar .theme-switcher { position: absolute; bottom: 20px; left: 24px; right: 24px; }

.sidebar h1 { margin-bottom: 20px; font-size: 1.5rem; }

.sidebar nav a { padding: 16px; font-size: 1rem; }

/ 移动端主内容区域 / .main-content { grid-area: main; padding: 16px 20px; }

/ 移动端播放控制栏 / .now-playing-bar { grid-area: player; padding: 20px; flex-direction: column; gap: 20px; }

.song-info-bar { width: 100%; gap: 15px; justify-content: center; }

.song-info-bar img { width: 50px; height: 60px; }

/ 在移动端隐藏歌曲信息和收藏按钮,只保留封面 / @media (max-width: 768px) { .song-info-bar div, .song-info-bar .fav-btn { display: none; }

.song-info-bar img { margin: 0 auto; } }

.player-controls { width: 100%; }

.control-buttons { gap: 20px; }

.progress-area { max-width: none; width: 100%; }

.extra-controls { justify-content: center; width: 100%; }

.volume-area { width: 80px; }

/ 移动端歌曲列表 / .song-list-header, .song-item { grid-template-columns: 30px 1fr 30px 30px; padding: 12px 8px; gap: 8px; }

.song-list-header span:nth-child(2), .song-list-header span:nth-child(3), .song-list-header span:nth-child(4) { display: none; }

.song-item .song-title { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: 100%; }

.song-item span:nth-child(3), .song-item span:nth-child(4) { display: none; }

.song-item .song-index { font-size: 0.8rem; }

.action-btn { font-size: 1rem; min-width: 44px; min-height: 44px; display: flex; align-items: center; justify-content: center; }

/ 移动端搜索框 / .search-area input { padding: 14px 20px 14px 50px; font-size: 1rem; }

.search-area i.fa-search { left: 18px; font-size: 1.1rem; }

/ 移动端按钮优化 / .action-button { padding: 14px 20px; font-size: 1rem; min-width: 100%; margin-bottom: 16px; }

/ 移动端分页 / .pagination-controls { padding: 16px 0; }

.page-btn { padding: 10px 16px; min-width: 44px; font-size: 1rem; }

/ 移动端统计卡片 / .stats-grid { grid-template-columns: 1fr; gap: 16px; }

.stat-card { padding: 16px; }

.stat-card h3 { font-size: 0.85rem; }

.stat-card p { font-size: 1.8rem; }

/ 移动端列表标题 / .list-section h2, .view > h2 { font-size: 1.5rem; margin-bottom: 16px; } }

/ 移动端统计列表特殊适配 / @media (max-width: 768px) { #stats-top-tracks .song-item { grid-template-columns: 30px 1fr 1fr 1fr 30px !important; padding: 12px 8px; gap: 8px; }

#stats-top-tracks .song-list-header { grid-template-columns: 30px 1fr 1fr 1fr 30px !important; }

#stats-top-tracks .song-item span:nth-child(3), #stats-top-tracks .song-item span:nth-child(4) { display: block !important; font-size: 0.8rem; color: var(--text-color-secondary); }

#stats-top-tracks .song-item .song-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

/ 最常听的歌手在移动端使用3列布局 / #stats-top-artists .song-item { grid-template-columns: 30px 1fr 1fr !important; padding: 12px 8px; gap: 8px; }

#stats-top-artists .song-list-header { grid-template-columns: 30px 1fr 1fr !important; }

#stats-top-artists .song-item span:nth-child(3) { display: block !important; font-size: 0.8rem; color: var(--text-color-secondary); text-align: right; }

#stats-top-artists .song-item .song-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } }

/ 超小屏幕统计适配 / @media (max-width: 480px) { #stats-top-tracks .song-item { grid-template-columns: 25px 1fr 1fr 25px !important; font-size: 0.8rem; }

#stats-top-tracks .song-list-header { grid-template-columns: 25px 1fr 1fr 25px !important; font-size: 0.7rem; }

#stats-top-tracks .song-item span:nth-child(4) { display: none !important; }

#stats-top-tracks .song-item span:nth-child(3) { text-align: right; }

/ 最常听的歌手在超小屏幕下使用3列布局 / #stats-top-artists .song-item { grid-template-columns: 25px 1fr 1fr !important; font-size: 0.8rem; }

#stats-top-artists .song-list-header { grid-template-columns: 25px 1fr 1fr !important; font-size: 0.7rem; }

#stats-top-artists .song-item span:nth-child(3) { text-align: right; } }

/ 超小屏幕适配 / @media (max-width: 480px) { .sidebar { width: 100%; left: -100%; }

.sidebar.open { left: 0; }

.main-content { padding: 12px 16px; }

.now-playing-bar { padding: 16px; }

.control-buttons { gap: 16px; }

#playPauseBtn { width: 50px; height: 50px; font-size: 1.2em; }

.control-btn { font-size: 1.2em; }

.song-info-bar img { width: 40px; height: 50px; }

.volume-area { width: 60px; } }

/ 遮罩层 / .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 999; }

.sidebar-overlay.show { display: block; }

/ 移动端菜单按钮 / .mobile-menu-btn { display: none; position: fixed; top: 20px; left: 20px; z-index: 1001; background-color: var(--component-bg); border: 1px solid var(--border-color); border-radius: 8px; padding: 12px; cursor: pointer; color: var(--text-color-primary); font-size: 1.2rem; transition: all 0.2s; }

.mobile-menu-btn:hover { background-color: var(--hover-bg); }

@media (max-width: 768px) { .mobile-menu-btn { display: block; } }

/ 歌曲选项菜单样式 / .song-options-menu { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 2000; display: flex; align-items: center; justify-content: center; }

/ 下载完成对话框样式 / .download-dialog { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 3000; display: flex; align-items: center; justify-content: center; background-color: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }

.download-dialog-content { background-color: var(--component-bg); border-radius: 12px; padding: 25px; margin: 20px; width: 100%; max-width: 400px; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); animation: dialogSlideIn 0.3s ease; text-align: center; }

@keyframes dialogSlideIn { from { opacity: 0; transform: scale(0.8) translateY(20px); } to { opacity: 1; transform: scale(1) translateY(0); } }

.download-dialog-icon { font-size: 48px; color: var(--download-color); margin-bottom: 15px; }

.download-dialog-title { font-size: 18px; font-weight: 600; color: var(--text-color-primary); margin-bottom: 10px; }

.download-dialog-message { color: var(--text-color-secondary); margin-bottom: 20px; line-height: 1.5; }

.download-dialog-buttons { display: flex; gap: 12px; justify-content: center; }

.download-dialog-btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; transition: all 0.2s; min-width: 100px; }

.download-dialog-btn.primary { background-color: var(--accent-color); color: white; }

.download-dialog-btn.primary:hover { background-color: var(--accent-color-hover); transform: translateY(-1px); }

.download-dialog-btn.secondary { background-color: var(--hover-bg); color: var(--text-color-primary); border: 1px solid var(--border-color); }

.download-dialog-btn.secondary:hover { background-color: var(--component-bg); transform: translateY(-1px); }

.song-options-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }

.song-options-content { position: relative; background-color: var(--component-bg); border-radius: 12px; padding: 20px; margin: 20px; width: 100%; max-width: 300px; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); animation: menuSlideIn 0.3s ease; }

@keyframes menuSlideIn { from { opacity: 0; transform: scale(0.8) translateY(20px); } to { opacity: 1; transform: scale(1) translateY(0); } }

.option-btn { display: flex; align-items: center; gap: 12px; width: 100%; padding: 16px 20px; background: none; border: none; color: var(--text-color-primary); font-size: 1rem; cursor: pointer; border-radius: 8px; transition: all 0.2s; margin-bottom: 8px; }

.option-btn:last-child { margin-bottom: 0; }

.option-btn:hover { background-color: var(--hover-bg); transform: translateY(-1px); }

.option-btn:active { transform: translateY(0); }

/ 歌单导入相关样式 / .playlist-import { background-color: var(--component-bg); border-radius: 12px; padding: 20px; margin-bottom: 20px; border: 1px solid var(--border-color); }

.section-title { color: var(--text-color-primary); font-size: 1.2rem; font-weight: 600; margin-bottom: 15px; display: flex; align-items: center; gap: 10px; }

.import-form { display: flex; gap: 10px; margin-bottom: 20px; }

.import-input { flex: 1; padding: 12px 15px; background: var(--hover-bg); border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-color-primary); outline: none; font-size: 14px; transition: all 0.3s ease; }

.import-input:focus { border-color: var(--accent-color); box-shadow: 0 0 0 2px rgba(15, 82, 186, 0.2); }

.import-input::placeholder { color: var(--text-color-secondary); }

.import-btn { padding: 12px 20px; background: var(--accent-color); border: none; border-radius: 8px; color: white; cursor: pointer; transition: all 0.3s ease; font-size: 14px; display: flex; align-items: center; gap: 8px; font-weight: 500; }

.import-btn:hover { background: var(--accent-color-hover); transform: translateY(-1px); }

.saved-playlists { margin-top: 20px; }

.playlist-item { padding: 12px 15px; background: var(--hover-bg); border-radius: 8px; margin-bottom: 10px; cursor: pointer; transition: all 0.3s ease; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border-color); }

.playlist-item:hover { background: var(--component-bg); transform: translateY(-1px); }

.playlist-item .playlist-info { flex: 1; min-width: 0; margin-right: 10px; }

.playlist-item .playlist-name { font-weight: 500; color: var(--text-color-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 4px; }

.playlist-item .playlist-count { font-size: 13px; color: var(--text-color-secondary); }

.playlist-actions { display: flex; gap: 8px; }

.playlist-action-btn { background: none; border: 1px solid var(--border-color); border-radius: 6px; color: var(--text-color-secondary); cursor: pointer; padding: 6px 10px; transition: all 0.2s ease; font-size: 12px; }

.playlist-action-btn:hover { background: var(--accent-color); color: white; border-color: var(--accent-color); }

.playlist-action-btn.delete { color: var(--danger-color); border-color: var(--danger-color); }

.playlist-action-btn.delete:hover { background: var(--danger-color); color: white; }

.empty-state { text-align: center; color: var(--text-color-secondary); padding: 20px; font-style: italic; }

/ 移动端歌单导入样式适配 / @media (max-width: 768px) { .playlist-import { padding: 15px; margin-bottom: 15px; }

.import-form { flex-direction: column; gap: 10px; }

.import-btn { justify-content: center; }

.playlist-item { padding: 10px 12px; }

.playlist-item .playlist-name { font-size: 14px; }

.playlist-item .playlist-count { font-size: 12px; }

.playlist-actions { gap: 6px; }

.playlist-action-btn { padding: 4px 8px; font-size: 11px; } } </style> </head>

<body class="dark-mode">

<audio id="audioPlayer"></audio>

<div class="app-container"> <!-- 移动端菜单按钮 --> <button class="mobile-menu-btn" id="mobileMenuBtn"> <i class="fas fa-bars"></i> </button>

<!-- 侧边栏遮罩层 --> <div class="sidebar-overlay" id="sidebarOverlay"></div>

<aside class="sidebar" id="sidebar"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px;"> <h1 style="margin: 0;"><i class="fas fa-headphones-alt"></i> Music</h1> <a href="/logout" style="color: var(--text-color-secondary); text-decoration: none; padding: 8px; border-radius: 6px; transition: all 0.2s;" onmouseover="this.style.backgroundColor='var(--hover-bg)'; this.style.color='var(--text-color-primary)'" onmouseout="this.style.backgroundColor='transparent'; this.style.color='var(--text-color-secondary)'" title="退出登录"> <i class="fas fa-sign-out-alt"></i> </a> </div> <nav> <ul> <li><a href="#" class="nav-link active" data-view="discover-view"><i class="fas fa-compass"></i>发现音乐</a></li> <!-- [] 本地音乐库的导航链接 --> <li><a href="#" class="nav-link" data-view="local-view"><i class="fas fa-hdd"></i>我的本地</a></li> <li><a href="#" class="nav-link" data-view="favourites-view"><i class="fas fa-heart"></i>我的收藏</a> </li> <li><a href="#" class="nav-link" data-view="history-view"><i class="fas fa-history"></i>播放历史</a> </li> <li><a href="#" class="nav-link" data-view="stats-view"><i class="fas fa-chart-pie"></i>听歌统计</a> </li> <li><a href="#" class="nav-link" data-view="data-management-view"><i class="fas fa-database"></i>数据管理</a> </li> </ul> </nav> <div class="login-status" id="loginStatus" style="margin-top: 20px; padding: 12px; background: var(--card-bg); border-radius: 8px; font-size: 0.85rem; color: var(--text-color-secondary); text-align: center;"> <i class="fas fa-user-check"></i> <span id="loginStatusText">已登录</span> </div> <div class="theme-switcher" id="themeToggle"><i class="fas fa-sun"></i> <span>切换模式</span></div> </aside>

<main class="main-content"> <div id="discover-view" class="view active"> <div class="search-area"> <i class="fas fa-search"></i> <input type="search" id="searchInput" placeholder="搜索歌曲、歌手..."> </div> <button id="loadOnlineBtn" class="action-button"> <i class="fas fa-satellite-dish"></i> 探索雷达 </button>

<!-- 歌单导入区域 --> <div class="playlist-import"> <h2 class="section-title"> <i class="fas fa-folder-plus"></i> 导入网易云歌单 </h2> <div class="import-form"> <input type="text" class="import-input" id="playlistIdInput" placeholder="粘贴歌单ID或链接"/> <button class="import-btn" onclick="importPlaylist()"> <i class="fas fa-download"></i> <span>导入</span> </button> </div> <div class="saved-playlists" id="savedPlaylists"> <!-- 保存的歌单将在这里显示 --> </div> </div>

<div id="song-list-container" class="song-list"></div> <div id="pagination-discover" class="pagination-controls"></div> </div>

<!-- [] 本地音乐库的视图 --> <div id="local-view" class="view"> <h2><i class="fas fa-hdd"></i> 我的本地音乐</h2> <button id="addLocalFilesBtn" class="action-button"> <i class="fas fa-folder-plus"></i> 添加本地音乐 </button> <input type="file" id="localFileInput" multiple accept="audio/*" style="display: none;"> <div id="local-list-container" class="song-list"></div> <div id="pagination-local" class="pagination-controls"></div> </div>

<div id="favourites-view" class="view"> <h2><i class="fas fa-heart"></i> 我的收藏</h2> <div id="favourites-list-container" class="song-list"></div> <div id="pagination-favourites" class="pagination-controls"></div> </div> <div id="history-view" class="view"> <h2><i class="fas fa-history"></i> 播放历史</h2> <div id="history-list-container" class="song-list"></div> <div id="pagination-history" class="pagination-controls"></div> </div> <div id="stats-view" class="view"> <h2><i class="fas fa-chart-pie"></i> 听歌统计</h2> <div class="stats-grid"> <div class="stat-card"> <h3>总播放量</h3> <p id="stats-total-plays">0</p> </div> <div class="stat-card"> <h3>不同歌曲</h3> <p id="stats-unique-tracks">0</p> </div> </div>

<div class="list-section"> <h2>播放最多的歌曲</h2> <div id="stats-top-tracks" class="song-list"></div> </div> <div class="list-section" style="margin-top: 30px;"> <h2>最常听的歌手</h2> <div id="stats-top-artists" class="song-list"></div> </div> </div>

<div id="data-management-view" class="view"> <h2><i class="fas fa-database"></i> 数据管理</h2> <div class="data-management-controls"> <div class="data-control-group"> <h3>我的收藏</h3> <div class="control-buttons"> <button class="control-btn" id="exportFavouritesBtn" title="导出收藏数据"> <i class="fas fa-download"></i> 导出 </button> <button class="control-btn" id="importFavouritesBtn" title="导入收藏数据"> <i class="fas fa-upload"></i> 导入 </button> <button class="control-btn clear-btn" id="clearFavouritesBtn" title="清空收藏数据"> <i class="fas fa-trash"></i> 清空 </button> <input type="file" id="favouritesFileInput" accept=".json" style="display: none;"> </div> <p class="data-info">收藏数量: <span id="favourites-count">0</span></p> </div>

<div class="data-control-group"> <h3>播放历史</h3> <div class="control-buttons"> <button class="control-btn" id="exportHistoryBtn" title="导出播放历史"> <i class="fas fa-download"></i> 导出 </button> <button class="control-btn" id="importHistoryBtn" title="导入播放历史"> <i class="fas fa-upload"></i> 导入 </button> <button class="control-btn clear-btn" id="clearHistoryBtn" title="清空播放历史"> <i class="fas fa-trash"></i> 清空 </button> <input type="file" id="historyFileInput" accept=".json" style="display: none;"> </div> <p class="data-info">历史记录: <span id="history-count">0</span></p> </div>

<div class="data-control-group"> <h3>全部数据</h3> <div class="control-buttons"> <button class="control-btn" id="exportAllDataBtn" title="导出所有数据"> <i class="fas fa-download"></i> 导出 </button> <button class="control-btn" id="importAllDataBtn" title="导入所有数据"> <i class="fas fa-upload"></i> 导入 </button> <button class="control-btn clear-btn" id="clearAllDataBtn" title="清空所有数据"> <i class="fas fa-trash"></i> 清空 </button> <input type="file" id="allDataFileInput" accept=".json" style="display: none;"> </div> </div> </div> </div> </main>

<footer class="now-playing-bar"> <div class="song-info-bar"> <img id="bar-album-art" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="> <div> <h3 id="bar-song-title">--</h3> <p id="bar-song-artist">--</p> </div> <i class="action-btn fav-btn far fa-heart" id="bar-fav-btn" title="添加到我的收藏"></i> </div> <div class="player-controls"> <div class="control-buttons"> <button class="control-btn" id="shuffleBtn" title="随机"><i class="fas fa-random"></i></button> <button class="control-btn" id="prevBtn" title="上一曲"><i class="fas fa-backward-step"></i></button> <button id="playPauseBtn" title="播放"><i class="fas fa-play"></i></button> <button class="control-btn" id="nextBtn" title="下一曲"><i class="fas fa-forward-step"></i></button> <button class="control-btn" id="repeatBtn" title="循环"><i class="fas fa-redo"></i></button> </div> <div class="progress-area"> <span class="time-display" id="currentTime">0:00</span> <div class="progress-bar" id="progressBar"> <div class="progress" id="progress"></div> </div> <span class="time-display" id="totalDuration">0:00</span> </div> </div> <div class="extra-controls"> <div class="volume-area"><i class="fas fa-volume-down"></i><input type="range" id="volumeSlider" min="0" max="1" step="0.01" value="0.8"></div> </div> </footer> </div>

<script> document.addEventListener('DOMContentLoaded', () => { // [] IndexedDB 帮助对象 const idbHelper = { db: null, init() { return new Promise((resolve, reject) => { const request = indexedDB.open("musicDB", 1); request.onupgradeneeded = (event) => { this.db = event.target.result; if (!this.db.objectStoreNames.contains('songs')) { this.db.createObjectStore('songs', { keyPath: 'id' }); } }; request.onsuccess = (event) => { this.db = event.target.result; resolve(this.db); }; request.onerror = (event) => reject("IndexedDB error: " + event.target.errorCode); }); }, addSong(song) { return new Promise((resolve, reject) => { const transaction = this.db.transaction(['songs'], 'readwrite'); const store = transaction.objectStore('songs'); const request = store.put(song); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, getSongs() { return new Promise((resolve, reject) => { const transaction = this.db.transaction(['songs'], 'readonly'); const store = transaction.objectStore('songs'); const request = store.getAll(); request.onsuccess = () => resolve(request.result); request.onerror = (event) => reject(event.target.error); }); }, deleteSong(id) { return new Promise((resolve, reject) => { const transaction = this.db.transaction(['songs'], 'readwrite'); const store = transaction.objectStore('songs'); const request = store.delete(id); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, };

const dom = { audioPlayer: document.getElementById('audioPlayer'), themeToggle: document.getElementById('themeToggle'), mainContent: document.querySelector('.main-content'), songListContainer: document.getElementById('song-list-container'), favouritesListContainer: document.getElementById('favourites-list-container'), historyListContainer: document.getElementById('history-list-container'), localListContainer: document.getElementById('local-list-container'), // paginationDiscover: document.getElementById('pagination-discover'), paginationFavourites: document.getElementById('pagination-favourites'), paginationHistory: document.getElementById('pagination-history'), paginationLocal: document.getElementById('pagination-local'), // searchInput: document.getElementById('searchInput'), loadOnlineBtn: document.getElementById('loadOnlineBtn'), addLocalFilesBtn: document.getElementById('addLocalFilesBtn'), localFileInput: document.getElementById('localFileInput'), // mobileMenuBtn: document.getElementById('mobileMenuBtn'), sidebarOverlay: document.getElementById('sidebarOverlay'), sidebar: document.getElementById('sidebar'), barAlbumArt: document.getElementById('bar-album-art'), barSongTitle: document.getElementById('bar-song-title'), barSongArtist: document.getElementById('bar-song-artist'), barFavBtn: document.getElementById('bar-fav-btn'), playPauseBtn: document.getElementById('playPauseBtn'), prevBtn: document.getElementById('prevBtn'), nextBtn: document.getElementById('nextBtn'), shuffleBtn: document.getElementById('shuffleBtn'), repeatBtn: document.getElementById('repeatBtn'), currentTime: document.getElementById('currentTime'), totalDuration: document.getElementById('totalDuration'), progressBar: document.getElementById('progressBar'), progress: document.getElementById('progress'), volumeSlider: document.getElementById('volumeSlider'), statsTotalPlays: document.getElementById('stats-total-plays'), statsUniqueTracks: document.getElementById('stats-unique-tracks'), statsTopTracks: document.getElementById('stats-top-tracks'), statsTopArtists: document.getElementById('stats-top-artists'), // 数据管理相关DOM元素 exportFavouritesBtn: document.getElementById('exportFavouritesBtn'), importFavouritesBtn: document.getElementById('importFavouritesBtn'), favouritesFileInput: document.getElementById('favouritesFileInput'), exportHistoryBtn: document.getElementById('exportHistoryBtn'), importHistoryBtn: document.getElementById('importHistoryBtn'), historyFileInput: document.getElementById('historyFileInput'), exportAllDataBtn: document.getElementById('exportAllDataBtn'), importAllDataBtn: document.getElementById('importAllDataBtn'), allDataFileInput: document.getElementById('allDataFileInput'), favouritesCount: document.getElementById('favourites-count'), historyCount: document.getElementById('history-count'), // 清空按钮相关DOM元素 clearFavouritesBtn: document.getElementById('clearFavouritesBtn'), clearHistoryBtn: document.getElementById('clearHistoryBtn'), clearAllDataBtn: document.getElementById('clearAllDataBtn'), // 登录状态相关DOM元素 loginStatus: document.getElementById('loginStatus'), loginStatusText: document.getElementById('loginStatusText'), };

const API = { getList: async (keyword) => { const url = \https://music-api.gdstudio.xyz/api.php?types=search&source=netease,kuwo&name=\${encodeURIComponent(keyword)}&count=100\; const response = await fetch(url); if (!response.ok) throw new Error('API request failed'); const data = await response.json(); if (!Array.isArray(data)) throw new Error('Invalid API response'); return data.map(song => ({ id: \\${song.source}_\${song.id}\, name: song.name, artists: [{ name: song.artist.join(' / ') }], album: song.album || '未知专辑', source: song.source, lyricid: song.lyricid, pic: \https://picsum.photos/400/400?random=\${encodeURIComponent(song.name)}\ })); }, getSongUrl: (song) => \https://music-api.gdstudio.xyz/api.php?types=url&id=\${song.id.split('_')[1]}&source=\${song.source}&br=320000\ };

const state = { discoverPlaylist: [], localPlaylist: [], currentPlaylist: [], currentTrackIndex: -1, isPlaying: false, isShuffle: false, repeatMode: 'none', history: [], favourites: [], itemsPerPage: 20, pagination: { discover: 1, favourites: 1, history: 1, local: 1 }, keywords: ['热门', '华语', '流行', '摇滚', '民谣', '电子', '说唱', '经典老歌', '刀郞', '张学友', '刘德华', '宋祖英', '王二妮', 'Beyond', '纯音乐', 'DJ', 'ACG'], lastKeyword: null, currentBlobUrl: null, savedPlaylists: [], currentPlaylistId: null, // 歌单相关状态 };

async function init() { try { await idbHelper.init(); loadStateFromLocalStorage(); setupEventListeners(); await loadLocalSongs(); // 先加载本地歌曲 renderAllViews(); displaySavedPlaylists(); // 显示保存的歌单 showView('discover-view'); fetchOnlineMusic(); initTouchFeatures(); // 初始化触摸功能 initLoginStatus(); // 初始化登录状态显示 } catch (error) { console.error("初始化失败:", error); alert("无法初始化数据库,本地功能将不可用。"); } }

// 清空收藏数据 function clearFavourites() { console.log('clearFavourites 函数被调用'); if (confirm('确定要清空所有收藏数据吗?此操作不可恢复!')) { console.log('用户确认清空收藏数据'); state.favourites = []; saveStateToLocalStorage(); renderFavourites(); updateAndRenderStats(); alert('收藏数据已清空'); } else { console.log('用户取消清空收藏数据'); } }

// 清空播放历史 function clearHistory() { console.log('clearHistory 函数被调用'); if (confirm('确定要清空所有播放历史吗?此操作不可恢复!')) { console.log('用户确认清空播放历史'); state.history = []; saveStateToLocalStorage(); renderHistory(); updateAndRenderStats(); alert('播放历史已清空'); } else { console.log('用户取消清空播放历史'); } }

// 清空所有数据 function clearAllData() { console.log('clearAllData 函数被调用'); if (confirm('确定要清空所有数据吗?包括收藏、播放历史、歌单等,此操作不可恢复!')) { console.log('用户确认清空所有数据'); state.favourites = []; state.history = []; state.savedPlaylists = []; saveStateToLocalStorage(); renderFavourites(); renderHistory(); updateAndRenderStats(); // 清空歌单显示 const savedPlaylists = document.getElementById('savedPlaylists'); if (savedPlaylists) { savedPlaylists.innerHTML = ''; } alert('所有数据已清空'); } else { console.log('用户取消清空所有数据'); } }

function setupEventListeners() { document.querySelectorAll('.nav-link').forEach(link => link.addEventListener('click', e => { e.preventDefault(); showView(e.currentTarget.dataset.view); })); dom.themeToggle.addEventListener('click', () => { const isLight = document.body.classList.toggle('light-mode'); document.body.classList.toggle('dark-mode', !isLight); localStorage.setItem('theme', isLight ? 'light' : 'dark'); }); dom.searchInput.addEventListener('keypress', e => { if (e.key === 'Enter' && e.target.value.trim()) fetchAndDisplaySearchResults(e.target.value.trim()); }); dom.loadOnlineBtn.addEventListener('click', () => fetchOnlineMusic()); dom.addLocalFilesBtn.addEventListener('click', () => dom.localFileInput.click()); dom.localFileInput.addEventListener('change', processLocalFiles); dom.playPauseBtn.addEventListener('click', togglePlayPause); dom.barFavBtn.addEventListener('click', () => { if (dom.barFavBtn.dataset.songId) toggleFavourite(dom.barFavBtn.dataset.songId); }); dom.nextBtn.addEventListener('click', playNext); dom.prevBtn.addEventListener('click', playPrevious); dom.shuffleBtn.addEventListener('click', toggleShuffle); dom.repeatBtn.addEventListener('click', toggleRepeat); dom.volumeSlider.addEventListener('input', e => dom.audioPlayer.volume = e.target.value); dom.progressBar.addEventListener('click', seek); dom.audioPlayer.addEventListener('timeupdate', updateProgress); dom.audioPlayer.addEventListener('loadedmetadata', () => dom.totalDuration.textContent = formatTime(dom.audioPlayer.duration)); dom.audioPlayer.addEventListener('ended', handleSongEnd); dom.audioPlayer.addEventListener('play', () => updatePlayPauseIcon(true)); dom.audioPlayer.addEventListener('pause', () => updatePlayPauseIcon(false)); dom.mainContent.addEventListener('click', handleMainContentClick);

// 移动端菜单事件监听器 dom.mobileMenuBtn.addEventListener('click', toggleMobileMenu); dom.sidebarOverlay.addEventListener('click', closeMobileMenu); dom.sidebar.addEventListener('click', (e) => { if (e.target.closest('.nav-link')) { closeMobileMenu(); } });

// 数据管理事件监听器 dom.exportFavouritesBtn.addEventListener('click', exportFavourites); dom.importFavouritesBtn.addEventListener('click', () => dom.favouritesFileInput.click()); dom.favouritesFileInput.addEventListener('change', (e) => { if (e.target.files[0]) importData(e.target.files[0], 'favourites'); });

dom.exportHistoryBtn.addEventListener('click', exportHistory); dom.importHistoryBtn.addEventListener('click', () => dom.historyFileInput.click()); dom.historyFileInput.addEventListener('change', (e) => { if (e.target.files[0]) importData(e.target.files[0], 'history'); });

dom.exportAllDataBtn.addEventListener('click', exportAllData); dom.importAllDataBtn.addEventListener('click', () => dom.allDataFileInput.click()); dom.allDataFileInput.addEventListener('change', (e) => { if (e.target.files[0]) importData(e.target.files[0], 'all'); });

// 清空按钮事件监听器 - 使用事件委托 document.addEventListener('click', function(e) { if (e.target && e.target.id === 'clearFavouritesBtn') { console.log('清空收藏按钮被点击'); clearFavourites(); } else if (e.target && e.target.id === 'clearHistoryBtn') { console.log('清空历史按钮被点击'); clearHistory(); } else if (e.target && e.target.id === 'clearAllDataBtn') { console.log('清空数据按钮被点击'); clearAllData(); } }); }

function handleMainContentClick(e) { const songItem = e.target.closest('.song-item'); const pageBtn = e.target.closest('.page-btn'); const actionBtn = e.target.closest('.action-btn');

if (actionBtn) { const songId = actionBtn.dataset.songId; const allSongs = [...state.discoverPlaylist, ...state.localPlaylist, ...state.history, ...state.favourites]; const uniqueSongs = Array.from(new Map(allSongs.map(item => [item.id, item])).values()); const song = uniqueSongs.find(s => s.id.toString() === songId.toString());

if (actionBtn.classList.contains('fav-btn')) { toggleFavourite(songId); return; } if (actionBtn.classList.contains('download-btn')) { downloadSong(song, actionBtn); return; } if (actionBtn.classList.contains('delete-btn')) { deleteLocalSong(songId); return; } }

if (songItem) { const context = songItem.dataset.context; const index = parseInt(songItem.dataset.index, 10); state.currentPlaylist = getPlaylistByContext(context); playSong(index); return; } if (pageBtn && !pageBtn.disabled) { const context = pageBtn.parentElement.dataset.context; state.pagination[context] = parseInt(pageBtn.dataset.page, 10); renderViewByContext(context); } }

function getStatsTracksPlaylist() { // 从播放历史中统计歌曲播放次数 const trackCounts = state.history.reduce((acc, song) => { acc[song.id] = (acc[song.id] || { ...song, count: 0 }); acc[song.id].count++; return acc; }, {});

// 返回按播放次数排序的歌曲列表,确保与渲染时的顺序完全一致 return Object.values(trackCounts).sort((a, b) => b.count - a.count).slice(0, 20); }

function getPlaylistByContext(context) { switch (context) { case 'discover': return state.discoverPlaylist; case 'favourites': return state.favourites; case 'history': return state.history; case 'local': return state.localPlaylist; case 'stats-tracks': return getStatsTracksPlaylist(); default: return []; } }

function renderViewByContext(context) { const playlist = getPlaylistByContext(context); const container = getListContainerByContext(context); renderPlaylist(playlist, container, context); }

function showView(viewId) { document.querySelectorAll('.view').forEach(v => v.classList.remove('active')); document.getElementById(viewId)?.classList.add('active'); document.querySelectorAll('.nav-link').forEach(l => l.classList.remove('active')); document.querySelector(\.nav-link[data-view="\${viewId}"]\)?.classList.add('active');

if (viewId === 'local-view') { renderPlaylist(state.localPlaylist, dom.localListContainer, 'local'); } }

function renderAllViews() { renderPlaylist(state.discoverPlaylist, dom.songListContainer, 'discover'); renderPlaylist(state.localPlaylist, dom.localListContainer, 'local'); renderFavourites(); renderHistory(); updateAndRenderStats(); }

function getListContainerByContext(context) { switch (context) { case 'discover': return dom.songListContainer; case 'favourites': return dom.favouritesListContainer; case 'history': return dom.historyListContainer; case 'local': return dom.localListContainer; default: return null; } }

function renderPlaylist(fullPlaylist, container, context) { const currentPage = state.pagination[context] || 1; const totalItems = fullPlaylist.length; if (!container) return;

if (totalItems === 0) { container.innerHTML = \<p style="padding: 15px;">列表为空。</p>\; getPaginationContainer(context).innerHTML = ''; return; } const totalPages = Math.ceil(totalItems / state.itemsPerPage); const startIndex = (currentPage - 1) * state.itemsPerPage; const endIndex = startIndex + state.itemsPerPage; const paginatedItems = fullPlaylist.slice(startIndex, endIndex);

// 检查是否为移动端 const isMobile = window.innerWidth <= 768;

let header = \<div class="song-list-header"> <span>#</span><span>歌曲</span>\${isMobile ? '' : '<span>歌手</span><span>专辑</span>'}<span></span><span></span> </div>\; container.innerHTML = header + paginatedItems.map((song, index) => { const originalIndex = startIndex + index; const isLocal = context === 'local'; const actionIcon = isLocal ? \<i class="action-btn delete-btn fas fa-trash" data-song-id="\${song.id}" title="从本地库删除"></i>\ : \<i class="action-btn download-btn fas fa-download" data-song-id="\${song.id}" title="下载到本地库"></i>\;

return \ <div class="song-item" data-index="\${originalIndex}" data-context="\${context}"> <span class="song-index">\${originalIndex + 1}</span> <div class="song-title"> <span>\${song.name}\${isMobile ? \<br><small style="color: var(--text-color-secondary); font-weight: normal;">\${song.artists.map(a => a.name).join(' / ')}</small>\ : ''}</span> <span class="error-msg" id="error-\${context}-\${song.id}"></span> </div> \${isMobile ? '' : \<span>\${song.artists.map(a => a.name).join(' / ')}</span><span>\${song.album}</span>\} <i class="action-btn fav-btn \${state.favourites.some(f => f.id === song.id) ? 'fas fa-heart favourited' : 'far fa-heart'}" data-song-id="\${song.id}"></i> \${actionIcon} </div>\}).join(''); renderPagination(totalPages, currentPage, context); updatePlaylistHighlight(); }

function renderPagination(totalPages, currentPage, context) { const container = getPaginationContainer(context); if (!container || totalPages <= 1) { if (container) container.innerHTML = ''; return; } let html = \<button class="page-btn" data-page="\${currentPage - 1}" \${currentPage === 1 ? 'disabled' : ''}>&laquo;</button>\; let startPage = Math.max(1, currentPage - 2), endPage = Math.min(totalPages, currentPage + 2); if (startPage > 1) html += \<button class="page-btn" data-page="1">1</button>\${startPage > 2 ? '<span>...</span>' : ''}\; for (let i = startPage; i <= endPage; i++) html += \<button class="page-btn \${i === currentPage ? 'active' : ''}" data-page="\${i}">\${i}</button>\; if (endPage < totalPages) html += \\${endPage < totalPages - 1 ? '<span>...</span>' : ''}<button class="page-btn" data-page="\${totalPages}">\${totalPages}</button>\; html += \<button class="page-btn" data-page="\${currentPage + 1}" \${currentPage === totalPages ? 'disabled' : ''}>&raquo;</button>\; container.innerHTML = html; container.dataset.context = context; }

function getPaginationContainer(context) { switch (context) { case 'discover': return dom.paginationDiscover; case 'favourites': return dom.paginationFavourites; case 'history': return dom.paginationHistory; case 'local': return dom.paginationLocal; default: return null; } }

function renderFavourites() { renderPlaylist(state.favourites, dom.favouritesListContainer, 'favourites'); } function renderHistory() { // 播放历史页面只显示每首歌曲的最新播放记录,避免重复 const uniqueHistory = []; const seenIds = new Set(); for (const song of state.history) { if (!seenIds.has(song.id)) { uniqueHistory.push(song); seenIds.add(song.id); } } renderPlaylist(uniqueHistory, dom.historyListContainer, 'history'); }

async function loadLocalSongs() { state.localPlaylist = await idbHelper.getSongs(); renderPlaylist(state.localPlaylist, dom.localListContainer, 'local'); }

async function processLocalFiles(event) { const files = event.target.files; if (!files.length) return; for (const file of files) { const song = { id: \local\${Date.now()}\${file.name}\, name: file.name.replace(/\\\\.[^\\\\/.]+$/, ""), artists: [{ name: "本地文件" }], album: "本地文件", blob: file, pic: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' }; await idbHelper.addSong(song); } await loadLocalSongs(); alert(\\${files.length}个文件已成功添加到本地库!\); }

async function deleteLocalSong(songId) { if (confirm("确定要从本地库中删除这首歌曲吗?此操作不可恢复。")) { await idbHelper.deleteSong(songId); await loadLocalSongs(); } }

async function fetchOnlineMusic() { let keyword; do { keyword = state.keywords[Math.floor(Math.random() * state.keywords.length)]; } while (state.keywords.length > 1 && keyword === state.lastKeyword); state.lastKeyword = keyword; dom.loadOnlineBtn.innerHTML = \<i class="fas fa-sync-alt fa-spin"></i> 正在加载...\; dom.loadOnlineBtn.disabled = true; await fetchAndDisplaySearchResults(keyword, true); dom.loadOnlineBtn.innerHTML = \<i class="fas fa-satellite-dish"></i> 探索雷达 (\${keyword})\; dom.loadOnlineBtn.disabled = false; }

async function fetchAndDisplaySearchResults(keyword, shuffle = false) { dom.songListContainer.innerHTML = \<p style="padding: 15px;">正在加载 "\${keyword}"...</p>\; dom.paginationDiscover.innerHTML = ''; try { const songs = await API.getList(keyword); if (shuffle) songs.sort(() => Math.random() - 0.5); state.discoverPlaylist = songs; state.pagination.discover = 1; renderPlaylist(songs, dom.songListContainer, 'discover'); } catch (error) { console.error("加载在线歌曲错误:", error); dom.songListContainer.innerHTML = \<p style='padding: 15px;'>加载失败: \${error.message}</p>\; } }

async function playSong(index) { if (index < 0 || index >= state.currentPlaylist.length) return; state.currentTrackIndex = index; const song = state.currentPlaylist[index]; updatePlayerUI(song); updatePlaylistHighlight(); updatePlayPauseIcon(true);

try { if (song.blob && song.blob instanceof Blob) { // 播放本地歌曲 if (state.currentBlobUrl) URL.revokeObjectURL(state.currentBlobUrl); state.currentBlobUrl = URL.createObjectURL(song.blob); dom.audioPlayer.src = state.currentBlobUrl; } else { // 播放在线歌曲 const urlEndpoint = API.getSongUrl(song); const response = await fetch(urlEndpoint); if (!response.ok) throw new Error('网络请求失败'); const urlData = await response.json(); const audioUrl = urlData.url?.replace(/^http:/, 'https'); if (!audioUrl) throw new Error('无法获取播放链接'); dom.audioPlayer.src = audioUrl; }

await dom.audioPlayer.play(); addPlayHistory(song); renderHistory(); saveStateToLocalStorage(); } catch (error) { console.error("播放失败:", error.message, song); // 确定当前播放列表的上下文 let context = 'discover'; if (state.currentPlaylist === state.favourites) { context = 'favourites'; } else if (state.currentPlaylist === state.history) { context = 'history'; } else if (state.currentPlaylist === state.localPlaylist) { context = 'local'; } else if (state.currentPlaylistId) { // 如果是歌单播放,仍然使用discover上下文,因为歌单歌曲显示在发现音乐视图中 context = 'discover'; }

const errorSpan = document.getElementById(\error-\${context}-\${song.id}\); if (errorSpan) errorSpan.textContent = "无法播放"; updatePlayPauseIcon(false); setTimeout(() => playNext(), 2000); } }

async function downloadSong(song, buttonElement) { buttonElement.className = 'action-btn download-btn fas fa-spinner fa-spin'; try { const urlEndpoint = API.getSongUrl(song); const response = await fetch(urlEndpoint); if (!response.ok) throw new Error('网络请求失败'); const data = await response.json(); const audioUrl = data.url?.replace(/^http:/, 'https'); if (!audioUrl) throw new Error('无法获取下载链接');

const audioResponse = await fetch(audioUrl); if (!audioResponse.ok) throw new Error(\下载资源失败: \${audioResponse.statusText}\); const blob = await audioResponse.blob();

// 同时保存到本地库和下载到文件系统 const songToStore = { ...song, blob: blob }; await idbHelper.addSong(songToStore);

// 创建下载链接并触发下载 const fileName = \\${song.name} - \${song.artists.map(a => a.name).join(' / ')}.mp3\.replace(/[<>:"/\\\\|?*]/g, '_'); const downloadUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = fileName; link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(downloadUrl);

await loadLocalSongs();

// 显示下载完成提示,并提供打开下载文件夹的选项 showDownloadCompleteDialog(song.name, fileName);

} catch (error) { console.error("下载失败:", error); alert(\下载《\${song.name}》失败: \${error.message}\); } finally { buttonElement.className = 'action-btn download-btn fas fa-download'; } }

function updatePlayerUI(song) { if (!song) { dom.barSongTitle.textContent = '--'; dom.barSongArtist.textContent = '--'; dom.barAlbumArt.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; dom.barFavBtn.dataset.songId = ''; updateFavouriteIcon(dom.barFavBtn, ''); return; } dom.barSongTitle.textContent = song.name; dom.barSongArtist.textContent = song.artists.map(a => a.name).join(' / '); dom.barAlbumArt.src = song.pic; dom.barFavBtn.dataset.songId = song.id; updateFavouriteIcon(dom.barFavBtn, song.id); }

function updatePlaylistHighlight() { document.querySelectorAll('.song-item').forEach(item => { const context = item.dataset.context; const listForContext = getPlaylistByContext(context); const index = parseInt(item.dataset.index, 10); const isCurrent = state.currentPlaylist === listForContext && index === state.currentTrackIndex; item.classList.toggle('current', isCurrent); }); }

function updatePlayPauseIcon(isPlaying) { state.isPlaying = isPlaying; dom.playPauseBtn.innerHTML = \<i class="fas fa-\${isPlaying ? 'pause' : 'play'}"></i>\; }

function toggleFavourite(songId) { const allSongs = [...state.discoverPlaylist, ...state.localPlaylist, ...state.history, ...state.favourites]; const uniqueSongs = Array.from(new Map(allSongs.map(item => [item.id, item])).values()); const song = uniqueSongs.find(s => s.id.toString() === songId.toString()); if (!song) return; const favIndex = state.favourites.findIndex(fav => fav.id.toString() === songId.toString()); if (favIndex > -1) { state.favourites.splice(favIndex, 1); } else { state.favourites.unshift(song); } const totalPages = Math.ceil(state.favourites.length / state.itemsPerPage); if (state.pagination.favourites > totalPages) { state.pagination.favourites = totalPages || 1; } renderAllViews(); if (state.currentPlaylist && state.currentPlaylist[state.currentTrackIndex]) { updatePlayerUI(state.currentPlaylist[state.currentTrackIndex]); } saveStateToLocalStorage(); }

function updateFavouriteIcon(iconElement, songId) { if (!songId) { iconElement.className = 'action-btn fav-btn far fa-heart'; return; } const isFavourited = state.favourites.some(fav => fav.id.toString() === songId.toString()); iconElement.className = \action-btn fav-btn \${isFavourited ? 'fas fa-heart favourited' : 'far fa-heart'}\; }

function togglePlayPause() { if (state.currentTrackIndex === -1 || !dom.audioPlayer.src) return; state.isPlaying ? dom.audioPlayer.pause() : dom.audioPlayer.play(); } function playNext() { let i = state.currentTrackIndex + 1; if (i >= state.currentPlaylist.length) { if (state.repeatMode === 'all') i = 0; else return; } playSong(i); } function playPrevious() { if (dom.audioPlayer.currentTime > 3) { dom.audioPlayer.currentTime = 0; } else { let i = state.currentTrackIndex - 1; if (i < 0) i = state.currentPlaylist.length - 1; playSong(i); } } function handleSongEnd() { if (state.repeatMode === 'one') playSong(state.currentTrackIndex); else playNext(); } function toggleShuffle() { / shuffle logic needs to be implemented / } function toggleRepeat() { const m = ['none', 'all', 'one']; state.repeatMode = m[(m.indexOf(state.repeatMode) + 1) % m.length]; dom.repeatBtn.classList.toggle('active', state.repeatMode !== 'none'); dom.audioPlayer.loop = state.repeatMode === 'one'; dom.repeatBtn.innerHTML = state.repeatMode === 'one' ? '<i class="fas fa-redo-alt"></i><sup style="font-size: 0.5em;">1</sup>' : '<i class="fas fa-redo"></i>'; }

function saveStateToLocalStorage() { localStorage.setItem('musicDashboardData', JSON.stringify({ favourites: state.favourites, history: state.history, savedPlaylists: state.savedPlaylists })); } function loadStateFromLocalStorage() { const data = JSON.parse(localStorage.getItem('musicDashboardData') || '{}'); state.history = data.history || []; state.favourites = data.favourites || []; state.savedPlaylists = data.savedPlaylists || []; // 加载保存的歌单 const savedTheme = localStorage.getItem('theme'); const isLight = savedTheme === 'light'; document.body.classList.toggle('light-mode', isLight); document.body.classList.toggle('dark-mode', !isLight); }

// 数据导出导入功能 function exportData(data, filename) { const dataStr = JSON.stringify(data, null, 2); const dataBlob = new Blob([dataStr], { type: 'application/json' }); const url = URL.createObjectURL(dataBlob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }

function importData(file, dataType) { const reader = new FileReader(); reader.onload = function(e) { try { const importedData = JSON.parse(e.target.result);

if (dataType === 'favourites') { let favouritesData = null; // 处理两种格式:直接数组格式和包装对象格式 if (Array.isArray(importedData)) { favouritesData = importedData; } else if (importedData.favourites && Array.isArray(importedData.favourites)) { favouritesData = importedData.favourites; }

if (favouritesData) { state.favourites = favouritesData; alert('成功导入 ' + favouritesData.length + ' 条收藏数据'); } else { alert('导入的收藏数据格式不正确'); return; } } else if (dataType === 'history') { let historyData = null; // 处理两种格式:直接数组格式和包装对象格式 if (Array.isArray(importedData)) { historyData = importedData; } else if (importedData.history && Array.isArray(importedData.history)) { historyData = importedData.history; }

if (historyData) { state.history = historyData; alert('成功导入 ' + historyData.length + ' 条播放历史数据'); } else { alert('导入的播放历史数据格式不正确'); return; } } else if (dataType === 'all') { if (importedData.favourites && Array.isArray(importedData.favourites)) { state.favourites = importedData.favourites; } if (importedData.history && Array.isArray(importedData.history)) { state.history = importedData.history; } if (importedData.savedPlaylists && Array.isArray(importedData.savedPlaylists)) { state.savedPlaylists = importedData.savedPlaylists; } alert('成功导入所有数据'); }

// 保存到本地存储并更新显示 saveStateToLocalStorage(); updateAndRenderStats(); renderFavourites(); renderHistory();

} catch (error) { alert('导入失败:文件格式不正确或已损坏'); console.error('Import error:', error); } }; reader.readAsText(file); }

// 导出收藏数据 function exportFavourites() { const data = { favourites: state.favourites, exportTime: new Date().toISOString(), version: '1.0' }; exportData(data, 'favourites_' + new Date().toISOString().split('T')[0] + '.json'); }

// 导出播放历史数据 function exportHistory() { const data = { history: state.history, exportTime: new Date().toISOString(), version: '1.0' }; exportData(data, 'playhistory' + new Date().toISOString().split('T')[0] + '.json'); }

// 导出所有数据 function exportAllData() { const data = { favourites: state.favourites, history: state.history, savedPlaylists: state.savedPlaylists, exportTime: new Date().toISOString(), version: '1.0' }; exportData(data, 'musicdatabackup_' + new Date().toISOString().split('T')[0] + '.json'); }

function addPlayHistory(song) { // 直接添加播放记录,不删除之前的记录,这样同一首歌的多次播放都会被记录 state.history.unshift({ ...song, playedAt: new Date().toISOString() }); // 保持历史记录在合理范围内,但保留所有播放记录用于统计 if (state.history.length > 1000) state.history = state.history.slice(0, 1000); } function updateAndRenderStats() { if (state.history.length === 0) { dom.statsTotalPlays.textContent = '0'; dom.statsUniqueTracks.textContent = '0'; dom.statsTopTracks.innerHTML = '<p style="padding: 15px;">暂无数据</p>'; dom.statsTopArtists.innerHTML = '<p style="padding: 15px;">暂无数据</p>'; // 更新数据计数显示 dom.favouritesCount.textContent = state.favourites.length; dom.historyCount.textContent = state.history.length; return; }; const trackCounts = state.history.reduce((acc, song) => { acc[song.id] = (acc[song.id] || { ...song, count: 0 }); acc[song.id].count++; return acc; }, {}); const artistCounts = state.history.flatMap(s => s.artists).reduce((acc, artist) => { acc[artist.name] = (acc[artist.name] || { name: artist.name, count: 0 }); acc[artist.name].count++; return acc; }, {}); dom.statsTotalPlays.textContent = state.history.length; dom.statsUniqueTracks.textContent = new Set(state.history.map(s => s.id)).size;

// 更新数据计数显示 dom.favouritesCount.textContent = state.favourites.length; dom.historyCount.textContent = state.history.length;

// 修复统计列表HTML结构,确保移动端也能显示完整信息 const isMobile = window.innerWidth <= 768;

// 播放最多的歌曲 const topTracksHeader = '<div class="song-list-header"><span>#</span><span>歌曲</span>' + (isMobile ? '' : '<span>歌手</span>') + '<span>播放次数</span><span></span></div>'; const topTracksList = getStatsTracksPlaylist(); // 使用相同的函数确保一致性 const topTracksItems = topTracksList.map((s, i) => { const artistInfo = isMobile ? '<br><small style="color: var(--text-color-secondary);">' + s.artists.map(a => a.name).join(' / ') + '</small>' : ''; const artistColumn = isMobile ? '' : '<span>' + s.artists.map(a => a.name).join(' / ') + '</span>'; return '<div class="song-item" data-index="' + i + '" data-context="stats-tracks">' + '<span>' + (i + 1) + '</span>' + '<span class="song-title">' + s.name + artistInfo + '</span>' + artistColumn + '<span>' + s.count + ' 次</span>' + '<span></span>' + '</div>'; }).join(''); dom.statsTopTracks.innerHTML = topTracksHeader + topTracksItems;

// 最常听的歌手 const topArtistsHeader = '<div class="song-list-header"><span>#</span><span>歌手</span><span>播放次数</span></div>'; const topArtistsItems = Object.values(artistCounts).sort((a, b) => b.count - a.count).slice(0, 10).map((a, i) => '<div class="song-item">' + '<span>' + (i + 1) + '</span>' + '<span class="song-title">' + a.name + '</span>' + '<span>' + a.count + ' 次</span>' + '</div>' ).join(''); dom.statsTopArtists.innerHTML = topArtistsHeader + topArtistsItems; } function updateProgress() { const { currentTime, duration } = dom.audioPlayer; if (duration) { dom.progress.style.width = \\${(currentTime / duration) * 100}%\; dom.currentTime.textContent = formatTime(duration ? currentTime : 0); } } function seek(e) { const duration = dom.audioPlayer.duration; if (duration) dom.audioPlayer.currentTime = (e.offsetX / dom.progressBar.clientWidth) * duration; } function formatTime(seconds) { const min = Math.floor(seconds / 60); const sec = Math.floor(seconds % 60); return \\${min}:\${sec < 10 ? '0' : ''}\${sec}\; }

// 移动端菜单功能 function toggleMobileMenu() { const isOpen = dom.sidebar.classList.contains('open'); if (isOpen) { closeMobileMenu(); } else { openMobileMenu(); } }

function openMobileMenu() { dom.sidebar.classList.add('open'); dom.sidebarOverlay.classList.add('show'); document.body.style.overflow = 'hidden'; }

function closeMobileMenu() { dom.sidebar.classList.remove('open'); dom.sidebarOverlay.classList.remove('show'); document.body.style.overflow = ''; }

// 初始化登录状态显示 function initLoginStatus() { if (dom.loginStatus && dom.loginStatusText) { // 设置登录状态显示 dom.loginStatusText.textContent = '已登录 (10天有效)';

// 可以添加倒计时功能,显示剩余时间 updateLoginStatusDisplay(); } }

// 更新登录状态显示 function updateLoginStatusDisplay() { if (dom.loginStatusText) { // 这里可以添加更复杂的逻辑,比如显示剩余时间 // 由于Cookie的Max-Age是服务器端设置的,客户端无法直接获取剩余时间 // 所以这里只显示基本的登录状态 dom.loginStatusText.textContent = '已登录 (10天有效)'; } }

// 触摸友好功能 function initTouchFeatures() { // 防止双击缩放 let lastTouchEnd = 0; document.addEventListener('touchend', function(event) { const now = (new Date()).getTime(); if (now - lastTouchEnd <= 300) { event.preventDefault(); } lastTouchEnd = now; }, false);

// 添加触摸反馈 const touchableElements = document.querySelectorAll('.action-btn, .control-btn, .page-btn, .nav-link'); touchableElements.forEach(element => { element.addEventListener('touchstart', function() { this.style.transform = 'scale(0.95)'; }, { passive: true });

element.addEventListener('touchend', function() { this.style.transform = ''; }, { passive: true }); });

// 改进进度条触摸 if (dom.progressBar) { dom.progressBar.addEventListener('touchstart', function(e) { e.preventDefault(); seek(e.touches[0]); }, { passive: false });

dom.progressBar.addEventListener('touchmove', function(e) { e.preventDefault(); seek(e.touches[0]); }, { passive: false }); }

// 添加长按功能到歌曲项 const songItems = document.querySelectorAll('.song-item'); songItems.forEach(item => { let longPressTimer; let startTime; let startX, startY;

item.addEventListener('touchstart', function(e) { startTime = Date.now(); startX = e.touches[0].clientX; startY = e.touches[0].clientY;

longPressTimer = setTimeout(() => { // 长按显示更多选项 showSongOptions(this); }, 500); }, { passive: true });

item.addEventListener('touchmove', function(e) { const moveX = Math.abs(e.touches[0].clientX - startX); const moveY = Math.abs(e.touches[0].clientY - startY);

if (moveX > 10 || moveY > 10) { clearTimeout(longPressTimer); } }, { passive: true });

item.addEventListener('touchend', function(e) { clearTimeout(longPressTimer); const duration = Date.now() - startTime;

if (duration < 500) { // 短按播放歌曲 const context = this.dataset.context; const index = parseInt(this.dataset.index, 10); state.currentPlaylist = getPlaylistByContext(context); playSong(index); } }, { passive: true }); }); }

// 显示歌曲选项菜单 function showSongOptions(songItem) { const songId = songItem.querySelector('.fav-btn').dataset.songId; const existingMenu = document.querySelector('.song-options-menu'); if (existingMenu) existingMenu.remove();

const menu = document.createElement('div'); menu.className = 'song-options-menu';

const downloadFunc = function() { const button = {dataset: {songId: songId}, className: 'action-btn download-btn fas fa-spinner fa-spin'}; downloadSong(null, button); menu.remove(); };

const toggleFunc = function() { toggleFavourite(songId); menu.remove(); };

menu.innerHTML = \ <div class="song-options-overlay" onclick="this.parentElement.remove()"></div> <div class="song-options-content"> <button class="option-btn" onclick="(\${toggleFunc.toString()})()"> <i class="fas fa-heart"></i> \${state.favourites.some(f => f.id === songId) ? '取消收藏' : '添加收藏'} </button> <button class="option-btn" onclick="(\${downloadFunc.toString()})()"> <i class="fas fa-download"></i> 下载到本地 </button> </div> \; document.body.appendChild(menu); }

// 显示下载完成对话框 function showDownloadCompleteDialog(songName, fileName) { const existingDialog = document.querySelector('.download-dialog'); if (existingDialog) existingDialog.remove();

const dialog = document.createElement('div'); dialog.className = 'download-dialog';

dialog.innerHTML = \ <div class="download-dialog-content"> <div class="download-dialog-icon"> <i class="fas fa-check-circle"></i> </div> <div class="download-dialog-title">下载完成!</div> <div class="download-dialog-message"> 《\${songName}》已成功下载到本地库和下载文件夹<br> 文件名:\${fileName} </div> <div class="download-dialog-buttons"> <button class="download-dialog-btn secondary" onclick="this.closest('.download-dialog').remove()"> 知道了 </button> <button class="download-dialog-btn primary" onclick="openDownloadsFolder()"> <i class="fas fa-folder-open"></i> 打开下载文件夹 </button> </div> </div> \;

document.body.appendChild(dialog);

// 3秒后自动关闭对话框 setTimeout(() => { if (dialog.parentNode) { dialog.remove(); } }, 5000); }

// 打开下载文件夹 function openDownloadsFolder() { // 尝试使用现代浏览器的文件系统API if ('showDirectoryPicker' in window) { // 现代浏览器支持,但需要用户手动选择文件夹 alert('请手动打开浏览器的下载文件夹查看文件。\\n\\n通常位置:\\n• Chrome: C:\\\\Users\\\\用户名\\\\Downloads\\\\\\n• Firefox: C:\\\\Users\\\\用户名\\\\Downloads\\\\\\n• Edge: C:\\\\Users\\\\用户名\\\\Downloads\\\\'); } else { // 传统方法,提供下载文件夹路径信息 const userAgent = navigator.userAgent; let downloadPath = '';

if (userAgent.includes('Chrome')) { downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\'; } else if (userAgent.includes('Firefox')) { downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\'; } else if (userAgent.includes('Edge')) { downloadPath = 'C:\\\\Users\\\\' + (navigator.userAgentData?.userData?.username || '用户名') + '\\\\Downloads\\\\'; } else { downloadPath = '浏览器的默认下载文件夹'; }

alert(\文件已下载到:\${downloadPath}\\n\\n请手动打开该文件夹查看下载的文件。\\n\\n提示:\\n• 按 Win + R 打开运行对话框\\n• 输入 %USERPROFILE%\\\\Downloads 并回车\\n• 或者直接在文件资源管理器中打开下载文件夹\); }

// 关闭对话框 const dialog = document.querySelector('.download-dialog'); if (dialog) dialog.remove(); }

// 将歌单相关函数设为全局,以便HTML中的onclick可以调用 window.importPlaylist = async function() { const playlistIdInput = document.getElementById('playlistIdInput'); const playlistId = playlistIdInput.value.trim();

if (!playlistId) { showNotification('请输入歌单ID或链接', 'warning'); return; }

// 提取歌单ID(支持完整链接) let id = playlistId; if (playlistId.includes('playlist?id=')) { id = playlistId.split('playlist?id=')[1].split('&')[0]; } else if (playlistId.includes('playlist/')) { id = playlistId.split('playlist/')[1].split('?')[0]; }

// 检查歌单是否已存在 if (state.savedPlaylists.some(p => p.id === id)) { showNotification('该歌单已存在', 'warning'); return; }

try { showNotification('正在导入歌单...', 'info');

// 获取歌单信息 const response = await fetch(\https://music-api.gdstudio.xyz/api.php?types=playlist&source=netease&id=\${id}\); const data = await response.json();

if (data && data.code === 200 && data.playlist) { // 转换歌单数据结构以匹配播放器需要的格式 const tracks = data.playlist.tracks.map(track => ({ id: \netease_\${track.id}\, name: track.name, artists: track.ar ? track.ar.map(artist => ({ name: artist.name })) : [{ name: '未知歌手' }], album: track.al ? track.al.name : '未知专辑', source: 'netease', pic: track.al ? track.al.picUrl : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' }));

const playlist = { id: id, name: data.playlist.name, tracks: tracks, cover: data.playlist.coverImgUrl || '', playCount: data.playlist.playCount || 0, description: data.playlist.description || '', creator: data.playlist.creator ? data.playlist.creator.nickname : '未知用户', tags: data.playlist.tags || [], createTime: new Date().toISOString() };

// 保存到本地存储 state.savedPlaylists.push(playlist); saveStateToLocalStorage();

// 更新UI displaySavedPlaylists();

playlistIdInput.value = ''; showNotification(\歌单 "\${playlist.name}" 导入成功!\, 'success'); } else { showNotification('无法获取歌单信息,请检查ID是否正确', 'error'); } } catch (error) { console.error('导入歌单失败:', error); showNotification('导入歌单失败,请检查网络连接', 'error'); } }

// 显示保存的歌单 window.displaySavedPlaylists = function() { const container = document.getElementById('savedPlaylists'); if (!container) return;

container.innerHTML = '';

if (state.savedPlaylists.length === 0) { container.innerHTML = '<div class="empty-state"><div>暂无保存的歌单</div></div>'; return; }

state.savedPlaylists.forEach((playlist, index) => { const playlistItem = document.createElement('div'); playlistItem.className = 'playlist-item'; playlistItem.onclick = () => playPlaylist(index); playlistItem.innerHTML = \ <div class="playlist-info"> <div class="playlist-name">\${playlist.name}</div> <div class="playlist-count">\${playlist.tracks.length} 首歌曲</div> </div> <div class="playlist-actions"> <button class="playlist-action-btn" onclick="playPlaylist(\${index}); event.stopPropagation();" title="播放歌单"> <i class="fas fa-play"></i> </button> <button class="playlist-action-btn" onclick="updatePlaylist(\${index}); event.stopPropagation();" title="更新歌单"> <i class="fas fa-sync-alt"></i> </button> <button class="playlist-action-btn delete" onclick="deletePlaylist(\${index}); event.stopPropagation();" title="删除歌单"> <i class="fas fa-trash"></i> </button> </div> \; container.appendChild(playlistItem); }); }

// 播放歌单 window.playPlaylist = function(index) { if (index < 0 || index >= state.savedPlaylists.length) return;

const playlist = state.savedPlaylists[index]; state.currentPlaylist = playlist.tracks; state.currentPlaylistId = playlist.id; state.currentTrackIndex = 0;

// 同时更新discoverPlaylist,这样点击歌曲时能正确播放 state.discoverPlaylist = playlist.tracks; state.pagination.discover = 1;

// 更新发现音乐视图的显示 renderPlaylist(playlist.tracks, dom.songListContainer, 'discover');

// 播放第一首歌 if (playlist.tracks.length > 0) { playSong(0); }

showNotification(\开始播放歌单 "\${playlist.name}"\, 'success'); }

// 删除歌单 window.deletePlaylist = function(index) { if (index < 0 || index >= state.savedPlaylists.length) return;

const playlist = state.savedPlaylists[index]; if (confirm(\确定要删除歌单 "\${playlist.name}" 吗?\)) { state.savedPlaylists.splice(index, 1); saveStateToLocalStorage(); displaySavedPlaylists(); showNotification('歌单已删除', 'success'); } }

// 更新歌单 window.updatePlaylist = async function(index) { if (index < 0 || index >= state.savedPlaylists.length) return;

const playlist = state.savedPlaylists[index]; try { showNotification('正在更新歌单...', 'info');

// 重新获取歌单信息 const response = await fetch(\https://music-api.gdstudio.xyz/api.php?types=playlist&source=netease&id=\${playlist.id}\); const data = await response.json();

if (data && data.code === 200 && data.playlist) { // 转换歌单数据结构 const tracks = data.playlist.tracks.map(track => ({ id: \netease_\${track.id}\, name: track.name, artists: track.ar ? track.ar.map(artist => ({ name: artist.name })) : [{ name: '未知歌手' }], album: track.al ? track.al.name : '未知专辑', source: 'netease', pic: track.al ? track.al.picUrl : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' }));

// 更新歌单信息 state.savedPlaylists[index].tracks = tracks; state.savedPlaylists[index].name = data.playlist.name; state.savedPlaylists[index].cover = data.playlist.coverImgUrl || ''; state.savedPlaylists[index].playCount = data.playlist.playCount || 0; state.savedPlaylists[index].description = data.playlist.description || ''; state.savedPlaylists[index].creator = data.playlist.creator ? data.playlist.creator.nickname : '未知用户'; state.savedPlaylists[index].tags = data.playlist.tags || [];

saveStateToLocalStorage(); displaySavedPlaylists();

// 如果当前正在播放这个歌单,更新当前播放列表 if (state.currentPlaylistId === playlist.id) { state.currentPlaylist = tracks; renderPlaylist(tracks, dom.songListContainer, 'discover'); }

showNotification(\歌单 "\${data.playlist.name}" 更新成功!\, 'success'); } else { showNotification('更新歌单失败,请检查网络连接', 'error'); } } catch (error) { console.error('更新歌单失败:', error); showNotification('更新歌单失败,请检查网络连接', 'error'); } }

// 显示通知 window.showNotification = function(message, type = 'info') { // 创建通知元素 const notification = document.createElement('div'); notification.className = \notification notification-\${type}\; notification.style.cssText = \ position: fixed; top: 20px; right: 20px; background: var(--component-bg); color: var(--text-color-primary); padding: 12px 20px; border-radius: 8px; border: 1px solid var(--border-color); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); z-index: 10000; max-width: 300px; word-wrap: break-word; animation: slideInRight 0.3s ease; \;

// 根据类型设置颜色 if (type === 'success') { notification.style.borderLeftColor = 'var(--download-color)'; } else if (type === 'error') { notification.style.borderLeftColor = 'var(--danger-color)'; } else if (type === 'warning') { notification.style.borderLeftColor = '#ff9800'; } else { notification.style.borderLeftColor = 'var(--accent-color)'; }

notification.textContent = message; document.body.appendChild(notification);

// 3秒后自动移除 setTimeout(() => { if (notification.parentNode) { notification.style.animation = 'slideOutRight 0.3s ease'; setTimeout(() => { if (notification.parentNode) { notification.remove(); } }, 300); } }, 3000); }

// 添加CSS动画 const style = document.createElement('style'); style.textContent = \ @keyframes slideInRight { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes slideOutRight { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } } \; document.head.appendChild(style);

init(); }); <\/script>

</body>

</html>;

return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8', ...corsHeaders, }, }); }, };

// 登录页面渲染函数 function renderLoginPage(msg = '') { return <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ws01 Music - 登录</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"> <link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>♬</text></svg>"> <style> * { margin: 0; padding: 0; box-sizing: border-box; }

body { font-family: 'Noto Sans SC', 'Segoe UI', Arial, sans-serif; background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); background-size: 400% 400%; animation: gradient-animation 15s ease infinite; height: 100vh; display: flex; justify-content: center; align-items: center; overflow: hidden; }

@keyframes gradient-animation { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }

.login-container { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-radius: 20px; padding: 40px 30px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); width: 100%; max-width: 400px; text-align: center; animation: fadeInUp 0.6s ease-out; }

@keyframes fadeInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }

.logo { display: flex; align-items: center; justify-content: center; gap: 12px; margin-bottom: 20px; color: #333; }

.logo i { font-size: 32px; color: #0F52BA; }

.logo span { font-size: 24px; font-weight: bold; }

.login-title { font-size: 22px; color: #333; margin-bottom: 10px; font-weight: 600; }

.login-subtitle { color: #666; margin-bottom: 30px; font-size: 14px; }

.error-message { background: rgba(211, 47, 47, 0.1); color: #d32f2f; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; border: 1px solid rgba(211, 47, 47, 0.2); }

.form-group { margin-bottom: 20px; text-align: left; }

.form-group label { display: block; color: #333; margin-bottom: 8px; font-weight: 500; font-size: 14px; }

.password-wrapper { position: relative; width: 100%; }

.password-wrapper input { width: 100%; padding: 15px 50px 15px 15px; border: 2px solid #e0e0e0; border-radius: 12px; font-size: 16px; outline: none; transition: all 0.3s ease; background: rgba(255, 255, 255, 0.9); }

.password-wrapper input:focus { border-color: #0F52BA; box-shadow: 0 0 0 3px rgba(15, 82, 186, 0.1); background: #fff; }

.password-wrapper input::placeholder { color: #999; }

.toggle-password { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #666; cursor: pointer; font-size: 18px; transition: color 0.3s ease; padding: 5px; }

.toggle-password:hover { color: #0F52BA; }

.login-btn { width: 100%; padding: 15px; background: linear-gradient(135deg, #0F52BA, #00318C); border: none; border-radius: 12px; color: #fff; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; margin-top: 10px; }

.login-btn:hover { background: linear-gradient(135deg, #00318C, #001F5C); transform: translateY(-2px); box-shadow: 0 10px 25px rgba(15, 82, 186, 0.3); }

.login-btn:active { transform: translateY(0); }

.login-footer { margin-top: 20px; color: #666; font-size: 12px; }

.login-footer a { color: #0F52BA; text-decoration: none; }

.login-footer a:hover { text-decoration: underline; }

/ 响应式设计 / @media (max-width: 480px) { .login-container { margin: 20px; padding: 30px 20px; } } </style> </head> <body> <div class="login-container"> <div class="logo"> <i class="fas fa-headphones-alt"></i> <span>ws01 Music</span> </div>

<h1 class="login-title">🔒 请输入密码</h1> <p class="login-subtitle">访问个人音乐库需要身份验证<br><small style="color: #888; font-size: 12px;">登录后10天有效,无需重复输入密码</small></p>

${msg ? <div class="error-message">${msg}</div> : ''}

<form method="POST" action="/login"> <div class="form-group"> <label for="password">管理员密码</label> <div class="password-wrapper"> <input type="password" id="password" name="password" placeholder="输入登录密码" required> <button type="button" class="toggle-password" onclick="togglePassword()"> <i class="fas fa-eye"></i> </button> </div> </div>

<button type="submit" class="login-btn"> <i class="fas fa-sign-in-alt"></i> 登录 </button> </form>

<div class="login-footer"> <p>© 2025 ws01 Music 个人音乐库</p> </div> </div>

<script> function togglePassword() { const input = document.getElementById('password'); const icon = document.querySelector('.toggle-password i');

if (input.type === 'password') { input.type = 'text'; icon.className = 'fas fa-eye-slash'; } else { input.type = 'password'; icon.className = 'fas fa-eye'; } }

// 回车键登录 document.getElementById('password').addEventListener('keypress', function(e) { if (e.key === 'Enter') { document.querySelector('form').submit(); } });

// 自动聚焦到密码输入框 window.addEventListener('load', function() { document.getElementById('password').focus(); }); </script> </body> </html>; }