
<% @active_page = 'tasks' %>
 
  <div id="app">
    <div class="app-wrapper">
        
      <main class="main-content">
         <div class="page-header">
           <h1>任务列表</h1>
         </div>
         
         <el-card class="card" style="margin-bottom: 24px;">
           <template #header>
             <div class="card-header">
               <h2 style="margin: 0; font-size: 16px; font-weight: 600; color: #303133;">
                 <i class="el-icon-magic-stick" style="margin-right: 8px;"></i>自然语言生成任务
               </h2>
             </div>
           </template>
           <div class="card-body">
             <el-form :model="form" label-width="0">
               <el-form-item>
                 <el-input
                   v-model="form.natural_language"
                   type="textarea"
                   :rows="3"
                   placeholder="请用自然语言描述您要执行的任务，例如：'巡检所有华为设备'"
                 ></el-input>
               </el-form-item>
               <el-form-item>
                 <el-button 
                   type="primary" 
                   @click="createTask" 
                   :loading="creating"
                   style="width: 100%;"
                 >
                   生成任务
                 </el-button>
               </el-form-item>
             </el-form>
           </div>
         </el-card>
        
        <el-card class="card">
          <div class="card-body">
            <el-table :data="tasks" stripe style="width: 100%" v-loading="loading">
              <el-table-column prop="name" label="任务名称" min-width="200">
                <template #default="scope">
                  <el-link type="primary" @click="goToDetail(scope.row.id)">
                    {{ scope.row.name }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip></el-table-column>
               <el-table-column prop="status" label="状态" width="120">
                 <template #default="scope">
                   <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status_text }}</el-tag>
                 </template>
               </el-table-column>
              <el-table-column prop="progress" label="进度" width="150">
                <template #default="scope">
                  <el-progress :percentage="scope.row.progress || 0" :stroke-width="8"></el-progress>
                </template>
              </el-table-column>
              <el-table-column prop="device_count" label="设备数" width="80" align="center"></el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="170">
                <template #default="scope">
                  {{ formatTime(scope.row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                  <el-button type="primary" size="small" link @click="goToDetail(scope.row.id)">详情</el-button>
                  <el-button type="warning" size="small" link @click="goToEdit(scope.row.id)">编辑</el-button>
                  <el-button
                    type="success"
                    size="small"
                    link
                    @click="startTask(scope.row.id)"
                    v-if="scope.row.status === 'pending'"
                  >启动</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div class="empty-state" v-if="!loading && tasks.length === 0" style="text-align: center; padding: 60px 20px; color: #909399;">
              <div style="font-size: 64px; margin-bottom: 20px;">📋</div>
              <p>暂无任务</p>
            </div>
          </div>
        </el-card>
      </main>
    </div>
  </div>
<% content_for :xxx do %>
  <script>
     const { createApp, ref, reactive, onMounted } = Vue;
     const app = createApp({
       setup() {
         const tasks = ref([]);
         const loading = ref(true);
         const creating = ref(false);
         const form = reactive({
           natural_language: ''
         });
         
         const fetchTasks = async () => {
           try {
             loading.value = true;
             const response = await fetch('/api/tasks');
             tasks.value = await response.json();
           } catch (error) {
             console.error('获取任务列表失败:', error);
             ElementPlus.ElMessage.error('获取任务列表失败');
           } finally {
             loading.value = false;
           }
         };
         
         const createTask = async () => {
           if (!form.natural_language.trim()) {
             ElementPlus.ElMessage.warning('请输入任务描述');
             return;
           }
           
           try {
             creating.value = true;
             const formData = new FormData();
             formData.append('natural_language', form.natural_language);
             
             const response = await fetch('/tasks/natural', {
               method: 'POST',
               body: formData
             });
             
             if (response.redirected) {
               window.location.href = response.url;
             } else {
               ElementPlus.ElMessage.error('创建任务失败');
             }
           } catch (error) {
             console.error('创建任务失败:', error);
             ElementPlus.ElMessage.error('创建任务失败');
           } finally {
             creating.value = false;
           }
         };
         
         const goToDetail = (taskId) => {
           window.location.href = `/tasks/${taskId}/vue`;
         };

         const goToEdit = (taskId) => {
           window.location.href = `/tasks/${taskId}/edit`;
         };
         
         const startTask = async (taskId) => {
           try {
             const formData = new FormData();
             const response = await fetch(`/tasks/${taskId}/start`, {
               method: 'POST',
               body: formData
             });
             if (response.ok) {
               ElementPlus.ElMessage.success('任务已启动');
               fetchTasks();
             } else {
               ElementPlus.ElMessage.error('启动任务失败');
             }
           } catch (error) {
             console.error('启动任务失败:', error);
             ElementPlus.ElMessage.error('启动任务失败');
           }
         };
         
         const formatTime = (timestamp) => {
           if (!timestamp) return '';
           const date = new Date(timestamp);
           const year = date.getFullYear();
           const month = String(date.getMonth() + 1).padStart(2, '0');
           const day = String(date.getDate()).padStart(2, '0');
           const hours = String(date.getHours()).padStart(2, '0');
           const minutes = String(date.getMinutes()).padStart(2, '0');
           return `${year}-${month}-${day} ${hours}:${minutes}`;
         };
         
          const getStatusType = (status) => {
            const types = {
              'completed': 'success',
              'running': 'info',
              'failed': 'danger',
              'pending': 'warning',
              'cancelled': 'info'
            };
            return types[status] || 'info';
          };
         
         onMounted(() => {
           fetchTasks();
         });
         
          return {
            tasks,
            loading,
            creating,
            form,
            fetchTasks,
            createTask,
            goToDetail,
            goToEdit,
            startTask,
            formatTime,
            getStatusType
          };
       }
     });
    app.use(ElementPlus);
  app.mount('#app');
  </script>
<% end %>