<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宇之然内容创作平台 - 数据分析</title>
    <link rel="stylesheet" href="element-plus.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: #f5f7fa; }
        .navbar { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 16px 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .navbar-content { display: flex; justify-content: space-between; align-items: center; max-width: 1400px; margin: 0 auto; }
        .navbar-title { font-size: 20px; font-weight: 600; }
        .navbar-user { display: flex; align-items: center; gap: 16px; }
        .user-info { display: flex; align-items: center; gap: 8px; }
        .avatar { width: 32px; height: 32px; border-radius: 50%; background: rgba(255,255,255,0.2); display: flex; align-items: center; justify-content: center; font-size: 14px; }
        .main-content { display: flex; flex: 1; max-width: 1400px; margin: 0 auto; }
        .sidebar { width: 180px; background: white; padding: 12px; box-shadow: 2px 0 8px rgba(0,0,0,0.05); }
        .content-area { flex: 1; padding: 24px; overflow-y: auto; }
        .card { background: white; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; padding: 20px; color: white; text-align: center; }
        .stat-card.success { background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%); }
        .stat-card.warning { background: linear-gradient(135deg, #e6a23c 0%, #f5c543 100%); }
        .stat-card.danger { background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%); }
        .stat-value { font-size: 32px; font-weight: 700; }
        .stat-label { font-size: 14px; opacity: 0.9; margin-top: 4px; }
        .mobile-nav { display: none; position: fixed; bottom: 0; left: 0; right: 0; background: white; box-shadow: 0 -2px 8px rgba(0,0,0,0.1); padding: 8px 0; z-index: 1000; }
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .mobile-nav { display: flex; }
            .content-area { padding: 16px; padding-bottom: 80px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr) !important; gap: 12px !important; }
            .chart-container { height: 250px !important; }
        }
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px; }
        .chart-container { background: white; border-radius: 12px; padding: 20px; margin-bottom: 24px; height: 350px; }
        .platform-chart { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
        @media (max-width: 768px) {
            .platform-chart { grid-template-columns: 1fr; }
        }
    </style>
    <script src="navigation-component.js"></script>
    <script src="navbar-component.js"></script>
</head>
<body>
    <div id="app">
        <navbar-component title="数据分析" :username="currentUser.username" :is-admin="isAdmin" @logout="handleLogout"></navbar-component>
        <navigation-component current-page="metrics" :is-admin="isAdmin" @navigate="redirectToPage"></navigation-component>
        <div class="main-content">
            <main class="content-area">
                <h2 style="font-size: 24px; font-weight: 700; margin-bottom: 24px; color: #303133;">📊 数据分析</h2>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-value">{{ dashboard.total_topics }}</div>
                        <div class="stat-label">选题总数</div>
                    </div>
                    <div class="stat-card success">
                        <div class="stat-value">{{ dashboard.total_published }}</div>
                        <div class="stat-label">已发布</div>
                    </div>
                    <div class="stat-card warning">
                        <div class="stat-value">{{ dashboard.total_views }}</div>
                        <div class="stat-label">总阅读</div>
                    </div>
                    <div class="stat-card danger">
                        <div class="stat-value">{{ dashboard.avg_engagement_rate }}%</div>
                        <div class="stat-label">平均互动率</div>
                    </div>
                </div>
                <div class="card">
                    <h3 style="font-size: 18px; margin-bottom: 16px;">📈 选题状态分布</h3>
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div v-for="(count, status) in dashboard.topics_by_status" :key="status" style="text-align: center;">
                            <div style="font-size: 28px; font-weight: 700; color: #409eff;">{{ count }}</div>
                            <div style="font-size: 14px; color: #909399;">{{ getStatusLabel(status) }}</div>
                        </div>
                    </div>
                </div>
                <div class="card">
                    <h3 style="font-size: 18px; margin-bottom: 16px;">🔥 热门选题 TOP10</h3>
                    <el-table :data="dashboard.top_topics" stripe size="small">
                        <el-table-column prop="topic_id" label="ID" width="80"></el-table-column>
                        <el-table-column prop="title" label="标题"></el-table-column>
                        <el-table-column prop="total_views" label="阅读" width="100">
                            <template #default="scope">{{ scope.row.total_views || 0 }}</template>
                        </el-table-column>
                        <el-table-column prop="total_likes" label="点赞" width="100">
                            <template #default="scope">{{ scope.row.total_likes || 0 }}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="card">
                    <h3 style="font-size: 18px; margin-bottom: 16px;">📉 数据趋势</h3>
                    <div style="display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap;">
                        <el-button-group>
                            <el-button :type="trendDays === 7 ? 'primary' : ''" @click="trendDays = 7; fetchTrend()">7天</el-button>
                            <el-button :type="trendDays === 30 ? 'primary' : ''" @click="trendDays = 30; fetchTrend()">30天</el-button>
                            <el-button :type="trendDays === 90 ? 'primary' : ''" @click="trendDays = 90; fetchTrend()">90天</el-button>
                        </el-button-group>
                    </div>
                    <div class="chart-container" style="overflow-x: auto;">
                        <div style="min-width: 600px;">
                            <div v-for="(item, idx) in trendData" :key="idx" style="display: flex; align-items: center; margin-bottom: 12px; gap: 16px;">
                                <div style="width: 100px; font-size: 13px; color: #606266;">{{ item.period }}</div>
                                <div style="flex: 1; background: #f0f9eb; border-radius: 4px; height: 24px; position: relative;">
                                    <div :style="{ width: (item.views / maxViews * 100) + '%', background: '#67c23a', height: '100%', borderRadius: '4px', transition: 'width 0.3s' }"></div>
                                </div>
                                <div style="width: 80px; font-size: 13px; text-align: right;">{{ item.views || 0 }} 阅读</div>
                            </div>
                            <div v-if="trendData.length === 0" style="text-align: center; color: #909399; padding: 40px;">暂无数据</div>
                        </div>
                    </div>
                </div>
                <div class="card">
                    <h3 style="font-size: 18px; margin-bottom: 16px;">🏆 平台对比</h3>
                    <el-table :data="platformData" stripe size="small">
                        <el-table-column prop="platform" label="平台" width="120">
                            <template #default="scope">{{ getPlatformName(scope.row.platform) }}</template>
                        </el-table-column>
                        <el-table-column prop="count" label="文章数" width="100"></el-table-column>
                        <el-table-column prop="total_views" label="总阅读" width="120"></el-table-column>
                        <el-table-column prop="avg_views" label="平均阅读" width="120">
                            <template #default="scope">{{ Math.round(scope.row.avg_views || 0) }}</template>
                        </el-table-column>
                        <el-table-column prop="total_likes" label="总点赞" width="120"></el-table-column>
                        <el-table-column prop="avg_likes" label="平均点赞" width="120">
                            <template #default="scope">{{ Math.round(scope.row.avg_likes || 0) }}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="card">
                    <h3 style="font-size: 18px; margin-bottom: 16px;">💡 选题推荐</h3>
                    <el-table :data="recommendations" stripe size="small">
                        <el-table-column prop="topic_id" label="ID" width="80"></el-table-column>
                        <el-table-column prop="title" label="推荐选题"></el-table-column>
                        <el-table-column prop="field" label="领域" width="120"></el-table-column>
                        <el-table-column prop="avg_engagement" label="互动率" width="100">
                            <template #default="scope">{{ scope.row.avg_engagement }}%</template>
                        </el-table-column>
                        <el-table-column prop="max_views" label="最高阅读" width="120"></el-table-column>
                        <el-table-column prop="reason" label="推荐理由"></el-table-column>
                    </el-table>
                </div>
            </main>
        </div>
    </div>
    <script src="vue.global.prod.js"></script>
    <script src="element-plus.full.js"></script>
    <script>
const MetricsApp = {
    data() {
        return {
            currentUser: { username: '' },
            isAdmin: false,
            isLoggedIn: false,
            dashboard: { total_topics: 0, topics_by_status: {}, total_published: 0, total_views: 0, total_likes: 0, avg_engagement_rate: 0, top_topics: [], recent_metrics: [] },
            trendDays: 30,
            trendData: [],
            maxViews: 1,
            platformData: [],
            recommendations: []
        }
    },
    methods: {
        handleLogout() { localStorage.removeItem('authToken'); localStorage.removeItem('userRole'); localStorage.removeItem('currentUser'); window.location.href = '/login.html'; },
        redirectToPage(page) { window.location.href = page.startsWith('/') ? page : '/' + page; },
        checkAuth() {
            const token = localStorage.getItem('authToken');
            if (!token) { window.location.href = '/login.html'; return; }
            fetch('/api/auth/me', { headers: { 'Authorization': 'Bearer ' + token } })
                .then(r => r.ok ? r.json() : Promise.reject())
                .then(data => {
                    this.currentUser = data.user;
                    this.isAdmin = data.user.role === 'admin';
                    this.isLoggedIn = true;
                    this.fetchDashboard();
                    this.fetchTrend();
                    this.fetchPlatformData();
                    this.fetchRecommendations();
                })
                .catch(() => { localStorage.removeItem('authToken'); localStorage.removeItem('userRole'); localStorage.removeItem('currentUser'); window.location.href = '/login.html'; });
        },
        getStatusLabel(status) {
            const map = { 'pending': '待处理', 'review': '待审查', 'ready': '待发布', 'published': '已发布' };
            return map[status] || status;
        },
        getPlatformName(platform) {
            const map = { 'zhihu': '知乎', 'wechat': '微信公众号', 'xiaohongshu': '小红书' };
            return map[platform] || platform;
        },
        async fetchDashboard() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/metrics/dashboard?days=' + this.trendDays, { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.dashboard = await res.json();
            } catch (e) { console.error(e); }
        },
        async fetchTrend() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/metrics/trend?days=' + this.trendDays, { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) {
                    this.trendData = await res.json();
                    this.maxViews = Math.max(...this.trendData.map(t => t.views || 0), 1);
                }
            } catch (e) { console.error(e); }
        },
        async fetchPlatformData() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/metrics/by-platform', { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.platformData = await res.json();
            } catch (e) { console.error(e); }
        },
        async fetchRecommendations() {
            try {
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/metrics/recommend-topics?limit=10', { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.recommendations = await res.json();
            } catch (e) { console.error(e); }
        }
    },
    mounted() {
        this.checkAuth();
    }
};
const app = Vue.createApp(MetricsApp);
app.use(ElementPlus);
if (window.installNavbar) { window.installNavbar(app); }
if (window.installNavigation) { window.installNavigation(app); } else if (window.NavigationComponent) { app.component("navigation-component", window.NavigationComponent); }
app.mount('#app');
    </script>
</body>
</html>
