<!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); }
        .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; }
        .task-card { border: 1px solid #ebeef5; border-radius: 12px; padding: 16px; margin-bottom: 12px; transition: all 0.3s; }
        .task-card:hover { border-color: #409eff; box-shadow: 0 2px 12px rgba(64,158,255,0.15); }
        .task-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
        .task-id { font-size: 13px; color: #909399; }
        .task-stage { display: inline-block; padding: 4px 12px; border-radius: 16px; font-size: 12px; font-weight: 500; }
        .stage-creator { background: #f0f9eb; color: #67c23a; }
        .stage-optimize { background: #fdf6ec; color: #e6a23c; }
        .stage-review { background: #fef0f0; color: #f56c6c; }
        .stage-publish { background: #ecf5ff; color: #409eff; }
        .task-body { margin-bottom: 12px; }
        .task-message { font-size: 14px; color: #606266; margin-bottom: 8px; }
        .task-meta { display: flex; gap: 16px; font-size: 13px; color: #909399; flex-wrap: wrap; }
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .mobile-nav { display: flex; }
            .content-area { padding: 16px; padding-bottom: 80px; }
        }
        .status-badge { display: inline-flex; align-items: center; gap: 4px; padding: 4px 12px; border-radius: 16px; font-size: 13px; }
        .status-pending { background: #f4f4f5; color: #909399; }
        .status-running { background: #f0f9eb; color: #67c23a; }
        .status-completed { background: #ecf5ff; color: #409eff; }
        .status-failed { background: #fef0f0; color: #f56c6c; }
        .status-cancelled { background: #f4f4f5; color: #c0c4cc; }
    </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="tasks" :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="card">
                    <div style="display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 16px;">
                        <el-button-group>
                            <el-button :type="filterStatus === '' ? 'primary' : ''" @click="filterStatus = ''; loadTasks()">全部</el-button>
                            <el-button :type="filterStatus === 'running' ? 'primary' : ''" @click="filterStatus = 'running'; loadTasks()">进行中</el-button>
                            <el-button :type="filterStatus === 'pending' ? 'primary' : ''" @click="filterStatus = 'pending'; loadTasks()">等待中</el-button>
                            <el-button :type="filterStatus === 'completed' ? 'primary' : ''" @click="filterStatus = 'completed'; loadTasks()">已完成</el-button>
                            <el-button :type="filterStatus === 'failed' ? 'primary' : ''" @click="filterStatus = 'failed'; loadTasks()">失败</el-button>
                        </el-button-group>
                        <el-button @click="loadTasks">🔄 刷新</el-button>
                    </div>
                    <div v-if="loading" style="text-align: center; padding: 40px;">加载中...</div>
                    <div v-else-if="tasks.length === 0" style="text-align: center; padding: 40px; color: #909399;">
                        <div style="font-size: 48px; margin-bottom: 16px;">📋</div>
                        <div>暂无任务</div>
                    </div>
                    <div v-else>
                        <div v-for="task in tasks" :key="task.task_id" class="task-card">
                            <div class="task-header">
                                <div style="display: flex; align-items: center; gap: 12px;">
                                    <span class="task-id">#{{ task.task_id }}</span>
                                    <span class="status-badge" :class="'status-' + task.status">{{ getStatusLabel(task.status) }}</span>
                                    <span class="task-stage" :class="'stage-' + task.stage">{{ getStageLabel(task.stage) }}</span>
                                </div>
                                <div style="display: flex; gap: 8px;">
                                    <el-button v-if="task.status === 'running'" size="small" type="danger" @click="cancelTask(task.task_id)">取消</el-button>
                                    <el-button v-if="task.status === 'failed'" size="small" type="primary" @click="retryTask(task)">重试</el-button>
                                    <el-button size="small" type="info" @click="viewTaskDetail(task)">详情</el-button>
                                </div>
                            </div>
                            <div class="task-body">
                                <div class="task-message">{{ task.message || '无消息' }}</div>
                                <div v-if="task.status === 'running'" style="margin-top: 8px;">
                                    <el-progress :percentage="task.progress || 0" :stroke-width="12" :show-text="true"></el-progress>
                                </div>
                            </div>
                            <div class="task-meta">
                                <span>创建: {{ formatDate(task.created_at) }}</span>
                                <span v-if="task.started_at">开始: {{ formatDate(task.started_at) }}</span>
                                <span v-if="task.finished_at">完成: {{ formatDate(task.finished_at) }}</span>
                                <span v-if="task.duration">耗时: {{ task.duration }}秒</span>
                                <span>创建人: {{ task.created_by }}</span>
                            </div>
                            <div v-if="task.error_msg" style="margin-top: 8px; padding: 8px; background: #fef0f0; border-radius: 4px; font-size: 13px; color: #f56c6c;">
                                错误: {{ task.error_msg }}
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
        <el-dialog v-model="showDetailDialog" title="任务详情" width="600px">
            <div v-if="detailTask">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="任务ID">{{ detailTask.task_id }}</el-descriptions-item>
                    <el-descriptions-item label="状态">{{ getStatusLabel(detailTask.status) }}</el-descriptions-item>
                    <el-descriptions-item label="阶段">{{ getStageLabel(detailTask.stage) }}</el-descriptions-item>
                    <el-descriptions-item label="进度">{{ detailTask.progress }}%</el-descriptions-item>
                    <el-descriptions-item label="选题ID" :span="2">{{ detailTask.topic_id || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ formatDate(detailTask.created_at) }}</el-descriptions-item>
                    <el-descriptions-item label="开始时间">{{ formatDate(detailTask.started_at) }}</el-descriptions-item>
                    <el-descriptions-item label="完成时间">{{ formatDate(detailTask.finished_at) }}</el-descriptions-item>
                    <el-descriptions-item label="耗时">{{ detailTask.duration ? detailTask.duration + '秒' : '-' }}</el-descriptions-item>
                    <el-descriptions-item label="创建人">{{ detailTask.created_by }}</el-descriptions-item>
                    <el-descriptions-item label="消息" :span="2">{{ detailTask.message || '-' }}</el-descriptions-item>
                    <el-descriptions-item v-if="detailTask.error_msg" label="错误信息" :span="2">
                        <span style="color: #f56c6c;">{{ detailTask.error_msg }}</span>
                    </el-descriptions-item>
                </el-descriptions>
                <div v-if="detailTask.result_data" style="margin-top: 16px;">
                    <div style="font-weight: 600; margin-bottom: 8px;">结果数据:</div>
                    <pre style="background: #f5f7fa; padding: 12px; border-radius: 8px; overflow: auto; max-height: 300px; font-size: 13px;">{{ JSON.stringify(detailTask.result_data, null, 2) }}</pre>
                </div>
            </div>
        </el-dialog>
    </div>
    <script src="vue.global.prod.js"></script>
    <script src="element-plus.full.js"></script>
    <script>
const TasksApp = {
    data() {
        return {
            currentUser: { username: '' },
            isAdmin: false,
            isLoggedIn: false,
            tasks: [],
            loading: false,
            filterStatus: '',
            showDetailDialog: false,
            detailTask: null
        }
    },
    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.loadTasks();
                })
                .catch(() => { localStorage.removeItem('authToken'); localStorage.removeItem('userRole'); localStorage.removeItem('currentUser'); window.location.href = '/login.html'; });
        },
        getStatusLabel(status) {
            const map = { 'pending': '等待中', 'running': '进行中', 'completed': '已完成', 'failed': '失败', 'cancelled': '已取消' };
            return map[status] || status;
        },
        getStageLabel(stage) {
            const map = { 'creator': '创作', 'optimize': '优化', 'review': '审查', 'publish': '发布' };
            return map[stage] || stage;
        },
        formatDate(dateStr) {
            if (!dateStr) return '-';
            return new Date(dateStr).toLocaleString('zh-CN');
        },
        async loadTasks() {
            this.loading = true;
            try {
                const token = localStorage.getItem('authToken');
                let url = '/api/tasks?limit=50';
                if (this.filterStatus) url += '&status=' + this.filterStatus;
                const res = await fetch(url, { headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) this.tasks = await res.json();
            } catch (e) { console.error(e); }
            finally { this.loading = false; }
        },
        viewTaskDetail(task) { this.detailTask = task; this.showDetailDialog = true; },
        async cancelTask(taskId) {
            try {
                await this.$confirm('确定取消该任务？', '提示', { type: 'warning' });
                const token = localStorage.getItem('authToken');
                const res = await fetch('/api/tasks/' + taskId, { method: 'DELETE', headers: { 'Authorization': 'Bearer ' + token } });
                if (res.ok) { this.$message.success('任务已取消'); this.loadTasks(); }
            } catch (e) { if (e !== 'cancel') this.$message.error(e.message || '操作失败'); }
        },
        retryTask(task) {
            this.$message.info('重试功能开发中...');
        }
    },
    mounted() {
        this.checkAuth();
    }
};
const app = Vue.createApp(TasksApp);
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>
