<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>宇之然内容创作平台</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="/static/vue.global.prod.js?v=20260427"></script>
  <link rel="stylesheet" href="/static/element-plus.css?v=20260427" />
  <script src="/static/element-plus.full.js?v=20260427"></script>
  <style>
    .page { padding: 24px; max-width: 1400px; margin: 0 auto; }
    .card { background: white; border-radius: 12px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); transition: all 0.3s; }
    .card:hover { box-shadow: 0 4px 16px rgba(0,0,0,0.12); }
    .stat-card { text-align: center; padding: 20px; cursor: pointer; transition: transform 0.2s; }
    .stat-card:hover { transform: translateY(-4px); }
    .stat-value { font-size: 2.5rem; font-weight: bold; color: #409EFF; line-height: 1.2; }
    .stat-label { color: #909399; font-size: 0.9rem; margin-top: 8px; }
    .action-btn-group { display: flex; gap: 8px; flex-wrap: wrap; }
    .quick-filter { display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; }
    .quick-filter .el-tag { cursor: pointer; transition: all 0.2s; }
    .quick-filter .el-tag:hover { transform: translateY(-2px); }
    .preview-container { position: relative; }
    .preview-actions { position: absolute; top: 16px; right: 16px; z-index: 10; }
    .loading-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.8); display: flex; align-items: center; justify-content: center; z-index: 9999; }
    .table-header-bg { background: #f5f7fa; }
    .status-badge { display: inline-flex; align-items: center; gap: 4px; }
    .status-dot { width: 6px; height: 6px; border-radius: 50%; }
    .status-dot.pending { background: #E6A23C; }
    .status-dot.review { background: #F56C6C; }
    .status-dot.ready { background: #67C23A; }
    .status-dot.published { background: #409EFF; }
    aside button { width: 100%; text-align: left; border: none; background: transparent; border-radius: 8px; margin-bottom: 4px; }
    aside button:hover { background-color: #f3f4f6; }
    @media (max-width: 768px) { main { padding-bottom: 70px; } }
    .thumbnail[src=""] { display: none; }
    .nav-title { text-align: center; }
  </style>
</head>
<body>
  <div id="app">
    <div v-if="!isLoggedIn" class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100">
      <div class="bg-white p-8 rounded-xl shadow-lg w-full max-w-md">
        <h2 class="text-2xl font-bold text-center mb-6 text-blue-600">宇之然内容创作平台</h2>
        <div v-if="loginError" class="mb-4 p-3 bg-red-50 text-red-600 rounded text-sm">{{ loginError }}</div>
        <el-form @submit.prevent="handleLogin">
          <el-form-item label="用户名"><el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User"></el-input></el-form-item>
          <el-form-item label="密码"><el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" @keyup.enter="handleLogin"></el-input></el-form-item>
          <el-button type="primary" class="w-full" @click="handleLogin" :loading="loadingLogin">登 录</el-button>
        </el-form>
      </div>
    </div>
    <div v-else>
      <nav class="bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg">
        <div class="container mx-auto px-6 py-4 flex justify-between items-center">
          <h1 class="text-2xl font-bold nav-title">宇之然内容创作平台</h1>
          <div class="flex items-center gap-3">
            <span class="text-sm">{{ currentUser?.username || '管理员' }}</span>
            <el-button type="danger" size="small" @click="handleLogout">退出</el-button>
          </div>
        </div>
      </nav>
      <div class="page flex gap-6">
        <aside class="w-48 flex-shrink-0 hidden md:block">
          <button @click="currentPage = 'overview'" :class="['px-4 py-2 rounded-lg', currentPage === 'overview' ? 'bg-blue-50 text-blue-600 font-semibold' : 'text-gray-600']">📊 系统概览</button>
          <button @click="currentPage = 'topics'" :class="['px-4 py-2 rounded-lg', currentPage === 'topics' ? 'bg-blue-50 text-blue-600 font-semibold' : 'text-gray-600']">📋 选题管理</button>
          <button @click="currentPage = 'logs'" :class="['px-4 py-2 rounded-lg', currentPage === 'logs' ? 'bg-blue-50 text-blue-600 font-semibold' : 'text-gray-600']">📄 系统日志</button>
          <button v-if="isAdmin" @click="currentPage = 'users'" :class="['px-4 py-2 rounded-lg', currentPage === 'users' ? 'bg-blue-50 text-blue-600 font-semibold' : 'text-gray-600']">👥 用户管理</button>
        </aside>
        <main class="flex-1">
          <div v-if="currentPage === 'overview'">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">📊 系统概览</h2>
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
              <div class="stat-card card" @click="goToTopicsWithFilter('total')"><div class="stat-value">{{ status.total_topics || 0 }}</div><div class="stat-label">选题总数</div></div>
              <div class="stat-card card" @click="goToTopicsWithFilter('待处理')"><div class="stat-value">{{ countByStatus('待处理') }}</div><div class="stat-label">待处理</div></div>
              <div class="stat-card card" @click="goToTopicsWithFilter('待审查')"><div class="stat-value">{{ countByStatus('待审查') }}</div><div class="stat-label">待审查</div></div>
              <div class="stat-card card" @click="goToTopicsWithFilter('待发布')"><div class="stat-value">{{ countByStatus('待发布') }}</div><div class="stat-label">待发布</div></div>
              <div class="stat-card card" @click="goToTopicsWithFilter('已发布')"><div class="stat-value">{{ countByStatus('已发布') }}</div><div class="stat-label">已发布</div></div>
              <div class="stat-card card" @click="goToTopicsWithFilter('today')"><div class="stat-value">{{ status.today_articles || 0 }}</div><div class="stat-label">今日新选题</div></div>
            </div>
            <div class="card"><h3 class="text-lg font-bold mb-4">🔄 流水线状态</h3>
              <div v-if="pipelineLoading" class="text-center py-4">加载中...</div>
              <div v-else class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div v-for="mod in pipelineModules" :key="mod.module" class="p-4 bg-gray-50 rounded-lg">
                  <div class="flex items-center gap-2 mb-2"><el-tag :type="mod.status_ok ? 'success' : 'danger'" size="small">{{ mod.status_text }}</el-tag><span class="font-semibold">{{ mod.module }}</span></div>
                  <div class="text-sm text-gray-500">最后运行：{{ mod.last_run }}</div>
                  <div v-if="mod.error" class="text-red-500 text-sm mt-1">{{ mod.error }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="currentPage === 'topics'" style="width: calc(100vw - 160px); max-width: calc(100vw - 160px); overflow-x: auto;">
            <div class="flex justify-between items-center mb-6"><h2 class="text-2xl font-bold text-gray-800">📋 选题管理</h2></div>
            <div class="card mb-6" style="display: inline-block; min-width: fit-content;"><div class="flex flex-wrap gap-2 items-center">
              <el-button type="primary" size="small" @click="refreshAll">🔄 批量刷新</el-button>
              <el-button type="success" size="small" @click="triggerGenerateSelected" :disabled="selectedTopicIds.length === 0">▶ 批量创作</el-button>
              <el-button type="warning" size="small" @click="triggerOptimizeSelected" :disabled="selectedTopicIds.length === 0">🔍 批量优化</el-button>
              <span class="ml-auto text-sm text-gray-500" v-if="selectedTopicIds.length > 0">已选 {{ selectedTopicIds.length }} 项</span>
            </div></div>
            <div class="quick-filter mb-4">
              <el-tag size="large" :type="filterStatus === '' ? 'primary' : ''" @click="filterStatus = ''">全部 ({{ topics.length }})</el-tag>
              <el-tag size="large" :type="filterStatus === '待处理' ? 'primary' : ''" @click="filterStatus = '待处理'">待处理 ({{ countByStatus('待处理') }})</el-tag>
              <el-tag size="large" :type="filterStatus === '待审查' ? 'primary' : ''" @click="filterStatus = '待审查'">待审查 ({{ countByStatus('待审查') }})</el-tag>
              <el-tag size="large" :type="filterStatus === '待发布' ? 'primary' : ''" @click="filterStatus = '待发布'">待发布 ({{ countByStatus('待发布') }})</el-tag>
              <el-tag size="large" :type="filterStatus === '已发布' ? 'primary' : ''" @click="filterStatus = '已发布'">已发布 ({{ countByStatus('已发布') }})</el-tag>
            </div>
            <div class="card">
              <el-table :data="filteredTopics" style=" max-"> stripe v-loading="loadingTable" :row-key="topic => topic.id" @selection-change="selectedTopicIds = $event">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="ID" width="70" fixed></el-table-column>
                <el-table-column prop="title" label="标题" min-width="220"></el-table-column>
                <el-table-column prop="field" label="领域" width="100"></el-table-column>
                <el-table-column prop="priority_score" label="优先级" width="70"><template #default="scope"><el-tag :type="getPriorityType(scope.row.priority_score)" size="small">{{ scope.row.priority_score }}</el-tag></template></el-table-column>
                <el-table-column prop="status" label="状态" width="90"><template #default="scope"><span class="status-badge"><span class="status-dot" :class="getStatusClass(scope.row.status)"></span>{{ scope.row.status }}</span></template></el-table-column>
                <el-table-column prop="compliance_score" label="合规分" width="90"><template #default="scope"><el-progress :percentage="scope.row.compliance_score || 0" :format="() => scope.row.compliance_score || '-'" :stroke-width="15"></el-progress></template></el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="140"><template #default="scope">{{ formatDate(scope.row.created_at) }}</template></el-table-column>
                <el-table-column prop="generated_at" label="创作时间" width="140"><template #default="scope">{{ scope.row.generated_at ? formatDate(scope.row.generated_at) : '-' }}</template></el-table-column>
                <el-table-column prop="published_at" label="发布时间" width="140"><template #default="scope">{{ scope.row.published_at ? formatDate(scope.row.published_at) : '-' }}</template></el-table-column>
                <el-table-column prop="updated_at" label="更新时间" width="140"><template #default="scope">{{ formatDate(scope.row.updated_at) }}</template></el-table-column>
                <el-table-column label="操作" width="300" fixed="right">
                  <template #default="scope">
                    <div class="flex gap-1 flex-wrap" style="max-width: 200px;">
                      <el-button size="small" @click="openPreview(scope.row)" type="primary">预览</el-button>
                      <el-button size="small" type="success" :disabled="scope.row.status !== '待处理'" @click="createTopic(scope.row)">创作</el-button>
                      <el-button size="small" type="warning" :disabled="scope.row.status !== '待审查'" @click="optimizeTopic(scope.row)">审查</el-button>
                      <el-button v-if="scope.row.status === '待发布'" size="small" type="primary" @click="handlePublish(scope.row)">发布</el-button>
                      <el-button size="small" type="danger" @click="deleteTopic(scope.row.id)">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div v-if="currentPage === 'logs'">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">📄 系统日志</h2>
            <div class="card">
              <div class="flex flex-wrap gap-4 mb-4">
                <el-select v-model="logType" placeholder="日志类型" size="default"><el-option label="创作日志" value="creator"></el-option><el-option label="优化日志" value="optimizer"></el-option><el-option label="收集日志" value="collector"></el-option></el-select>
                <el-date-picker v-model="logDate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="default"></el-date-picker>
                <el-button type="primary" @click="fetchLogs" :loading="loadingLogs">加载日志</el-button>
              </div>
              <el-card v-if="logContent" class="font-mono text-sm bg-gray-50" style="max-height: 600px; overflow-y: auto;"><pre>{{ logContent }}</pre></el-card>
              <el-empty v-else description="请先选择类型和日期，然后点击加载"></el-empty>
            </div>
          </div>
          <div v-if="currentPage === 'users' && isAdmin">
            <h2 class="text-2xl font-bold mb-6 text-gray-800">👥 用户管理</h2>
            <div class="card">
              <div class="flex justify-between items-center mb-4"><h3 class="text-lg font-bold">用户列表</h3><el-button type="primary" @click="openCreateUserModal">+ 新建用户</el-button></div>
              <el-table :data="users" stripe v-loading="loadingUsers">
                <el-table-column prop="id" label="ID" width="70"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="role" label="角色" width="100"><template #default="scope"><el-tag :type="scope.row.role === 'admin' ? 'danger' : 'info'">{{ scope.row.role }}</el-tag></template></el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180"><template #default="scope">{{ formatDate(scope.row.created_at) }}</template></el-table-column>
                <el-table-column label="操作" width="150"><template #default="scope"><el-button size="small" type="danger" @click="deleteUser(scope.row.id)" :disabled="scope.row.role === 'admin'">删除</el-button></template></el-table-column>
              </el-table>
            </div>
          </div>
        </main>
      </div>
      <div v-if="loadingOverlay" class="loading-overlay"><el-spinner type="spinning" :size="50"></el-spinner><p class="ml-4 text-lg">{{ loadingText }}</p></div>
      <el-dialog v-model="previewVisible" title="文章预览" width="80%" top="5vh">
        <div class="preview-container">
          <div class="preview-actions"><el-button type="primary" size="small" @click="copyPreviewHtml">📋 复制 HTML</el-button><el-button type="success" size="small" @click="expandPreview">⛶ 全屏</el-button></div>
          <el-card v-if="previewHtml" class="mt-4" style="max-height: 60vh; overflow-y: auto;"><div v-html="previewHtml"></div></el-card>
          <el-empty v-else description="暂无预览内容"></el-empty>
        </div>
      </el-dialog>
      <el-dialog v-model="createTopicModalVisible" title="新建选题" width="500px">
        <el-form :model="newTopicForm" label-width="100px">
          <el-form-item label="标题"><el-input v-model="newTopicForm.title" placeholder="请输入标题"></el-input></el-form-item>
          <el-form-item label="领域"><el-input v-model="newTopicForm.field" placeholder="请输入领域"></el-input></el-form-item>
          <el-form-item label="优先级"><el-select v-model="newTopicForm.priority" placeholder="请选择"><el-option label="高" value="高"></el-option><el-option label="中" value="中"></el-option><el-option label="低" value="低"></el-option></el-select></el-form-item>
        </el-form>
        <template #footer><el-button @click="createTopicModalVisible = false">取消</el-button><el-button type="primary" @click="confirmCreateTopic">确定</el-button></template>
      </el-dialog>
      <el-dialog v-model="createUserModalVisible" title="新建用户" width="500px">
        <el-form :model="newUserForm" label-width="100px">
          <el-form-item label="用户名"><el-input v-model="newUserForm.username" placeholder="请输入用户名"></el-input></el-form-item>
          <el-form-item label="密码"><el-input v-model="newUserForm.password" type="password" placeholder="请输入密码"></el-input></el-form-item>
          <el-form-item label="角色"><el-select v-model="newUserForm.role" placeholder="请选择"><el-option label="管理员" value="admin"></el-option><el-option label="普通用户" value="user"></el-option></el-select></el-form-item>
        </el-form>
        <template #footer><el-button @click="createUserModalVisible = false">取消</el-button><el-button type="primary" @click="confirmCreateUser">确定</el-button></template>
      </el-dialog>
      <el-dialog v-model="publishModalVisible" title="发布选题" width="500px">
        <el-form :model="publishForm" label-width="100px">
          <el-form-item label="平台"><el-select v-model="publishForm.platform" placeholder="请选择平台"><el-option label="知乎" value="zhihu"></el-option><el-option label="微信公众号" value="wechat"></el-option><el-option label="小红书" value="xiaohongshu"></el-option></el-select></el-form-item>
          <el-form-item label="URL"><el-input v-model="publishForm.url" placeholder="发布后的链接"></el-input></el-form-item>
          <el-form-item label="说明"><el-input type="textarea" v-model="publishForm.description" placeholder="发布说明"></el-input></el-form-item>
        </el-form>
        <template #footer><el-button @click="publishModalVisible = false">取消</el-button><el-button type="primary" @click="confirmPublish">确定</el-button></template>
      </el-dialog>
    </div>
    <nav class="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 flex justify-around py-2 z-50" v-if="isLoggedIn">
      <button @click="currentPage = 'overview'" :class="['flex flex-col items-center px-4 py-1', currentPage === 'overview' ? 'text-blue-600' : 'text-gray-500']"><span class="text-xl">📊</span><span class="text-xs mt-1">概览</span></button>
      <button @click="currentPage = 'topics'" :class="['flex flex-col items-center px-4 py-1', currentPage === 'topics' ? 'text-blue-600' : 'text-gray-500']"><span class="text-xl">📋</span><span class="text-xs mt-1">选题</span></button>
      <button @click="currentPage = 'logs'" :class="['flex flex-col items-center px-4 py-1', currentPage === 'logs' ? 'text-blue-600' : 'text-gray-500']"><span class="text-xl">📄</span><span class="text-xs mt-1">日志</span></button>
      <button v-if="isAdmin" @click="currentPage = 'users'" :class="['flex flex-col items-center px-4 py-1', currentPage === 'users' ? 'text-blue-600' : 'text-gray-500']"><span class="text-xl">👥</span><span class="text-xs mt-1">用户</span></button>
    </nav>
  </div>
  <script>
    const { ref, reactive, computed, onMounted, watch } = Vue;
    const { ElMessage, ElNotification } = ElementPlus;
    const app = Vue.createApp({
      name: 'YuZhiRanPlatform',
      setup() {
        const API_BASE = "";
        const token = ref(localStorage.getItem('token') || '');
        const isLoggedIn = ref(!!token.value);
        const currentUser = ref(null);
        const isAdmin = ref(false);
        const loginForm = reactive({ username: '', password: '' });
        const loginError = ref('');
        const loadingLogin = ref(false);
        const authFetch = (url, options = {}) => {
          const headers = { 'Content-Type': 'application/json', ...options.headers };
          if (token.value) headers['Authorization'] = 'Bearer ' + token.value;
          return fetch(url, { ...options, headers }).then(async res => {
            if (res.status === 401) {
              token.value = ''; localStorage.removeItem('token'); isLoggedIn.value = false;
              ElMessage.error('登录已过期，请重新登录');
              setTimeout(() => location.reload(), 1500);
              return Promise.reject(new Error('未授权'));
            }
            return res;
          });
        };
        const handleLogin = async () => {
          loadingLogin.value = true;
          try {
            const res = await authFetch(API_BASE + '/api/auth/login', { method: 'POST', body: JSON.stringify(loginForm) });
            if (res.ok) {
              const data = await res.json();
              token.value = data.token; localStorage.setItem('token', data.token); isLoggedIn.value = true;
              currentUser.value = data.user; isAdmin.value = data.role === 'admin';
              loginForm.username = ''; loginForm.password = ''; loginError.value = '';
              ElMessage.success('登录成功'); refresh(); refreshPipeline();
            } else { const err = await res.json(); loginError.value = err.detail || '登录失败'; }
          } catch (e) { loginError.value = '网络错误：' + e.message; }
          finally { loadingLogin.value = false; }
        };
        const handleLogout = () => { localStorage.removeItem('token'); token.value = ''; isLoggedIn.value = false; currentUser.value = null; isAdmin.value = false; ElMessage.info('已退出登录'); };
        const status = ref({}), topics = ref([]), filterStatus = ref(''), generating = ref(false), optimizing = ref(false);
        const loadingAll = ref(false), loadingTable = ref(false), loadingLogs = ref(false), loadingUsers = ref(false);
        const loadingOverlay = ref(false), loadingText = ref(''), selectedTopicIds = ref([]);
        const pipeline = ref({ status_distribution: {} }), pipelineLoading = ref(false), pipelineModules = ref([]);
        const previewVisible = ref(false), previewTopic = ref({ title: '' }), previewPlatform = ref('zhihu'), previewHtml = ref('');
        const fullScreenPreview = ref(false), showLogs = ref(false), logType = ref('creator'), logDate = ref(new Date().toISOString().split('T')[0]), logContent = ref('');
        const currentPage = ref('overview'), users = ref([]), createTopicModalVisible = ref(false);
        const newUserForm = reactive({ username: '', password: '', role: 'user' }), createUserModalVisible = ref(false);
        const publishModalVisible = ref(false), publishForm = reactive({ platform: 'zhihu', url: '', description: '' });
        const newTopicForm = reactive({ title: '', field: '', priority: '中' });
        const filteredTopics = computed(() => filterStatus.value ? topics.value.filter(t => t.status === filterStatus.value) : topics.value);
        const countByStatus = (s) => s === 'total' ? status.value.total_topics || 0 : s === 'today' ? status.value.today_articles || 0 : status.value.topics_by_status?.[s] || 0;
        const getPriorityType = (s) => s >= 20 ? 'success' : s >= 15 ? 'warning' : 'info';
        const getStatusClass = (s) => ({ '待处理': 'pending', '待审查': 'review', '待发布': 'ready', '已发布': 'published' })[s] || 'pending';
        const formatDate = (v) => v ? new Date(v).toLocaleString('zh-CN', { hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '-';
        const refresh = async () => { try { const [s, t] = await Promise.all([authFetch(API_BASE + '/api/system/status').then(r => r.json()), authFetch(API_BASE + '/api/topics').then(r => r.json())]); status.value = s; topics.value = t; } catch (e) { ElMessage.error('刷新失败：' + e.message); } };
        const refreshPipeline = async () => { pipelineLoading.value = true; try { const res = await authFetch(API_BASE + '/api/system/pipeline/status'); if (res.ok) { const data = await res.json(); pipeline.value = data; pipelineModules.value = Object.entries(data.pipeline_modules || {}).map(([n, i]) => ({ module: n, last_run: i.last_run || '未运行', status_ok: !i.has_error && i.exists, status_text: i.exists && !i.has_error ? '正常' : i.exists ? '有错误' : '缺失', error: i.has_error ? '检测到错误' : '' })); } } catch (e) { ElMessage.error('获取流水线状态失败'); } finally { pipelineLoading.value = false; } };
        const refreshAll = async () => { loadingAll.value = true; try { await Promise.all([refresh(), refreshPipeline()]); ElMessage.success('刷新成功'); } catch (e) { ElMessage.error('刷新失败'); } finally { loadingAll.value = false; } };
        const triggerGenerate = async (id) => { generating.value = true; try { const res = await authFetch(API_BASE + '/api/system/generate/run?topic_id=' + id, { method: 'POST' }); const data = await res.json(); if (data.result && data.result.ok) { ElMessage.success('创作任务已启动'); setTimeout(refresh, 3000); } else ElMessage.error('启动失败：' + (data.error || '未知错误')); } catch (e) { ElMessage.error('请求失败：' + e.message); } finally { generating.value = false; } };
        const triggerGenerateSelected = async () => { if (!selectedTopicIds.value.length) return; loadingOverlay.value = true; loadingText.value = '正在批量创作...'; try { for (const t of selectedTopicIds.value) await triggerGenerate(t.id); ElMessage.success('批量创作完成'); selectedTopicIds.value = []; refresh(); } catch (e) { ElMessage.error('批量创作失败：' + e.message); } finally { loadingOverlay.value = false; } };
        const triggerOptimize = async (ids) => { optimizing.value = true; try { const res = await authFetch(API_BASE + '/api/system/optimize/run', { method: 'POST', body: JSON.stringify({ topic_ids: ids || [] }) }); const data = await res.json(); if (data.summary) { ElNotification({ title: '优化完成', message: '自动通过 ' + (data.summary.passed_auto || 0) + ' 篇，需人工 ' + (data.summary.need_manual || 0) + ' 篇', type: 'success' }); await refresh(); } else ElMessage.success('优化完成'); } catch (e) { ElMessage.error('优化失败：' + e.message); } finally { optimizing.value = false; } };
        const triggerOptimizeSelected = async () => { if (!selectedTopicIds.value.length) return; loadingOverlay.value = true; loadingText.value = '正在批量优化...'; try { const ids = selectedTopicIds.value.map(t => t.id); await triggerOptimize(ids); ElMessage.success('批量优化完成'); selectedTopicIds.value = []; } catch (e) { ElMessage.error('批量优化失败：' + e.message); } finally { loadingOverlay.value = false; } };
        const openPreview = async (topic) => { previewTopic.value = topic; previewPlatform.value = 'zhihu'; previewVisible.value = true; loadingText.value = '加载中...'; loadingOverlay.value = true; try { const res = await authFetch(API_BASE + '/api/topics/' + topic.id + '/preview?platform=zhihu'); const data = await res.json(); previewHtml.value = data.html; } catch (e) { ElMessage.error('预览加载失败：' + e.message); previewHtml.value = ''; } finally { loadingOverlay.value = false; loadingText.value = ''; } };
        const loadPreview = async () => { try { const res = await authFetch(API_BASE + '/api/topics/' + previewTopic.value.id + '/preview?platform=' + previewPlatform.value); const data = await res.json(); previewHtml.value = data.html; } catch (e) { ElMessage.error('预览加载失败'); previewHtml.value = ''; } };
        const copyPreviewHtml = () => { navigator.clipboard.writeText(previewHtml.value).then(() => ElMessage.success('HTML 已复制到剪贴板')).catch(() => ElMessage.error('复制失败')); };
        const expandPreview = () => { fullScreenPreview.value = !fullScreenPreview.value; };
        const fetchLogs = async () => { loadingLogs.value = true; logContent.value = ''; try { const res = await authFetch(API_BASE + '/api/system/logs/' + logDate.value + '?log_type=' + logType.value); if (res.status === 404) { logContent.value = '日志文件不存在或为空。'; ElMessage.info('该日期无日志记录'); } else { const data = await res.json(); logContent.value = data.content.join('\n'); } } catch (e) { if (e.message.includes('未授权')) return; ElMessage.error('加载日志失败：' + e.message); } finally { loadingLogs.value = false; } };
        const createTopic = (topic) => { if (topic && topic.status === '待处理') triggerGenerate(topic.id); else ElMessage.info('仅待处理选题可创作'); };
        const optimizeTopic = (topic) => { if (topic && topic.status === '待审查') triggerOptimize([topic.id]); else ElMessage.info('仅待审查选题可优化'); };
        const handlePublish = (topic) => { publishModalVisible.value = true; publishForm.platform = 'zhihu'; publishForm.url = ''; publishForm.description = ''; publishTopicId = topic.id; };

        const deleteTopic = async (id) => {
          if (!confirm('确定删除该选题？删除后无法恢复。')) return;
          try {
            await authFetch(API_BASE + '/api/topics/' + id, { method: 'DELETE' });
            ElMessage.success('删除成功');
            refresh();
          } catch (e) { if (e.message.includes('未授权')) return; ElMessage.error('删除失败：' + e.message); }
        };
        const confirmPublish = async () => { try { await authFetch(API_BASE + '/api/topics/' + publishTopicId + '/publish', { method: 'POST', body: JSON.stringify({ platform: publishForm.platform, platform_urls: { [publishForm.platform]: publishForm.url }, description: publishForm.description }) }); ElMessage.success('发布成功'); publishModalVisible.value = false; refresh(); } catch (e) { ElMessage.error('发布失败：' + e.message); } };
        const openCreateTopic = () => { createTopicModalVisible.value = true; newTopicForm.title = ''; newTopicForm.field = ''; newTopicForm.priority = '中'; };
        const confirmCreateTopic = () => { ElMessage.info('新建选题功能待实现'); createTopicModalVisible.value = false; };
        const openCreateUserModal = () => { createUserModalVisible.value = true; newUserForm.username = ''; newUserForm.password = ''; newUserForm.role = 'user'; };
        const confirmCreateUser = async () => { try { await authFetch(API_BASE + '/api/admin/users', { method: 'POST', body: JSON.stringify(newUserForm) }); ElMessage.success('用户创建成功'); createUserModalVisible.value = false; loadUsers(); } catch (e) { ElMessage.error('创建失败：' + e.message); } };
        const deleteUser = async (id) => { if (!confirm('确定删除？')) return; try { await authFetch(API_BASE + '/api/admin/users/' + id, { method: 'DELETE' }); ElMessage.success('删除成功'); loadUsers(); } catch (e) { ElMessage.error('删除失败：' + e.message); } };
        const loadUsers = async () => { loadingUsers.value = true; try { const res = await authFetch(API_BASE + '/api/admin/users'); users.value = await res.json(); } catch (e) { ElMessage.error('加载用户失败'); } finally { loadingUsers.value = false; } };
        const goToTopicsWithFilter = (s) => { if (s === 'total') filterStatus.value = ''; else if (s === 'today') { ElMessage.info('今日新选题筛选待实现'); } else filterStatus.value = s; currentPage.value = 'topics'; };
        let publishTopicId = null;
        onMounted(() => { if (isLoggedIn.value) { refresh(); refreshPipeline(); loadUsers(); } });
        return { token, isLoggedIn, currentUser, isAdmin, loginForm, loginError, loadingLogin, handleLogin, handleLogout, status, topics, filterStatus, generating, optimizing, loadingAll, loadingTable, loadingLogs, loadingUsers, loadingOverlay, loadingText, selectedTopicIds, pipeline, pipelineLoading, pipelineModules, previewVisible, previewTopic, previewPlatform, previewHtml, fullScreenPreview, showLogs, logType, logDate, logContent, currentPage, users, createTopicModalVisible, newUserForm, createUserModalVisible, publishModalVisible, publishForm, newTopicForm, filteredTopics, countByStatus, getPriorityType, getStatusClass, formatDate, refresh, refreshPipeline, refreshAll, triggerGenerate, triggerGenerateSelected, triggerOptimize, triggerOptimizeSelected, openPreview, loadPreview, copyPreviewHtml, expandPreview, fetchLogs, createTopic, optimizeTopic, handlePublish, confirmPublish, openCreateTopic, confirmCreateTopic, openCreateUserModal, confirmCreateUser, deleteUser, loadUsers, goToTopicsWithFilter };
      }
    });
    app.use(ElementPlus);
    app.mount('#app');
  </script>
