<% @page_title = '任务详情 - 清巡' %>
<% @active_page = 'tasks' %>

  <div id="app">
    <div class="app-wrapper">

      <main class="main-content">
        <div class="page-header">
          <h1>任务详情</h1>
          <div>
            <el-button type="success" @click="goToReport">查看报告</el-button>
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>

        <div v-loading="loading">
          <el-card v-if="task" class="card">
            <template #header>
              <div class="card-header">
                <h2>基本信息</h2>
                <div>
                  <el-button type="primary" size="small" @click="editMode = !editMode">
                    {{ editMode ? '取消编辑' : '编辑' }}
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="saveTask"
                    v-if="editMode"
                    :loading="saving"
                  >保存</el-button>
                  <!-- 重置按钮：在基本信息卡片中提供重置当前任务的快速操作 -->
                  <el-button
                    type="warning"
                    size="small"
                    @click="resetTask"
                    :loading="resetting"
                    style="margin-left: 6px;"
                  >重置</el-button>
                   <el-button
                     type="primary"
                     size="small"
                     @click="startTask"
                     v-if="task.status === 'pending'"
                     style="margin-left: 6px;"
                   >开始执行</el-button>
                </div>
              </div>
            </template>

            <div class="card-body">
              <el-form v-if="editMode" :model="taskForm" label-width="100px">
                <el-form-item label="任务名称">
                  <el-input v-model="taskForm.name" style="width: 400px;"></el-input>
                </el-form-item>
                <el-form-item label="描述">
                  <el-input
                    v-model="taskForm.description"
                    type="textarea"
                    :rows="3"
                    style="width: 400px;"
                  ></el-input>
                </el-form-item>
              </el-form>

               <div v-else class="info-section">
                  <!-- 核心信息网格 -->
                  <div class="info-grid">
                    <div class="info-item">
                      <span class="info-label">任务名称</span>
                      <span class="info-value info-value--primary">{{ task.name }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">状态</span>
                      <span class="info-value"><el-tag :type="getStatusType(task.status)" size="small">{{ task.status_text }}</el-tag></span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">设备数</span>
                      <span class="info-value">{{ task.device_count || 0 }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">创建时间</span>
                      <span class="info-value">{{ formatTime(task.created_at) }}</span>
                    </div>
                    <div class="info-item" v-if="task.started_at">
                      <span class="info-label">开始时间</span>
                      <span class="info-value">{{ formatTime(task.started_at) }}</span>
                    </div>
                    <div class="info-item" v-if="task.completed_at">
                      <span class="info-label">完成时间</span>
                      <span class="info-value">{{ formatTime(task.completed_at) }}</span>
                    </div>
                  </div>

                  <!-- 进度条 -->
                  <div class="info-progress" v-if="task.progress !== undefined">
                    <span class="info-label">进度</span>
                    <div class="info-progress-bar">
                      <el-progress :percentage="task.progress || 0" :stroke-width="6"></el-progress>
                    </div>
                  </div>

                  <!-- 描述 -->
                  <div class="info-description" v-if="task.description">
                    <span class="info-label">描述</span>
                    <span class="info-value info-value--muted">{{ task.description }}</span>
                  </div>

                  <!-- 错误信息 -->
                  <div class="info-error" v-if="task.error_message">
                    <span class="info-label">错误</span>
                    <span class="info-value info-value--error">{{ task.error_message }}</span>
                  </div>
                </div>
            </div>
          </el-card>

          <el-card v-if="task && task.execution_units" class="card">
            <template #header>
              <div class="card-header">
                <h2>网元</h2>
              </div>
            </template>
            <div class="card-body">
              <el-table :data="task.execution_units" style="width: 100%">
                <el-table-column prop="device_name" label="设备名称" width="150"></el-table-column>
                <el-table-column prop="device_ip" label="IP地址" width="130"></el-table-column>
                <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getUnitStatusType(scope.row.status)" size="small">
                      {{ 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="6"></el-progress>
                  </template>
                </el-table-column>
                <el-table-column prop="current_script" label="当前正在执行中的脚本" width="250">
                  <template #default="scope">
                    <span v-if="scope.row.current_script">{{ scope.row.current_script }}</span>
                    <span v-else>-</span>
                    <el-button
                      v-if="scope.row.current_script"
                      type="primary"
                      size="small"
                      link
                      @click="showCurrentScriptLog(scope.row)"
                      style="margin-left: 8px;"
                    >
                      查看日志
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="showUnitDetail(scope.row)">
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <el-card v-if="task && task.output" class="card">
            <template #header>
              <div class="card-header">
                <h2>输出日志</h2>
              </div>
            </template>
            <div class="card-body">
              <div class="json-preview" style="white-space: normal; overflow-x: auto;" v-html="formattedTaskOutput"></div>
            </div>
          </el-card>
        </div>
      </main>
    </div>

    <el-dialog
      v-model="unitDetailDialogVisible"
      :title="`详情 - ${currentUnit?.device_name || ''}`"
      width="60%"
    >
      <div v-if="currentUnit">
        <h3 style="margin-bottom: 16px;">脚本列表</h3>
        <el-table :data="currentUnit.scripts || []" style="width: 100%; margin-bottom: 24px;">
          <el-table-column prop="name" label="脚本名称" width="200"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getScriptStatusType(scope.row.status)" size="small">
                {{ scope.row.status || 'pending' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="showScriptLog(scope.row)">
                查看日志
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <template #footer>
        <el-button @click="unitDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="logDetailDialogVisible"
      :title="`脚本日志 - ${currentScript?.name || ''}`"
      width="70%"
    >
      <div v-if="currentScript">
        <div style="margin-bottom: 16px;">
          <el-tag :type="getScriptStatusType(currentScript.status)" size="small">
            {{ currentScript.status || 'pending' }}
          </el-tag>
          <span v-if="currentScript.started_at" style="margin-left: 12px; color: #909399;">
            开始: {{ formatTime(currentScript.started_at) }}
          </span>
          <span v-if="currentScript.completed_at" style="margin-left: 12px; color: #909399;">
            完成: {{ formatTime(currentScript.completed_at) }}
          </span>
        </div>
        <div v-if="currentScript.error || currentScript.error_message" style="margin-bottom: 16px; color: #f56c6c;">
          <strong>错误:</strong> {{ currentScript.error || currentScript.error_message }}
        </div>
        <div style="margin-bottom: 12px;">
          <el-button type="primary" size="small" @click="refreshScriptLog">
            刷新日志
          </el-button>
          <el-button type="primary" size="small" @click="copyLog">
            复制日志
          </el-button>
        </div>
        <div class="json-preview" style="white-space: normal; max-height: 400px; overflow-y: auto; overflow-x: auto; background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 4px; font-family: monospace; font-size: 13px;" v-html="formattedScriptLog">
        </div>
      </div>
      <template #footer>
        <el-button @click="logDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>

  <script>
    window.taskId = <%= @task_id.to_json %>;
  </script>
  <% content_for :xxx do %>

  <script>
    const { createApp, ref, reactive, onMounted, onUnmounted, computed, nextTick, watch } = Vue;
    const app = createApp({
      setup() {
        const taskId = window.taskId;
        const task = ref(null);
        const loading = ref(true);
        const saving = ref(false);
        const editMode = ref(false);
        const taskForm = reactive({
          name: '',
          description: ''
        });
        const resetting = ref(false);
        let refreshInterval = null;
        const FAST_REFRESH_INTERVAL = 2000;  // 任务运行时2秒刷新一次
        const NORMAL_REFRESH_INTERVAL = 10000; // 正常10秒刷新一次

        const unitDetailDialogVisible = ref(false);
        const currentUnit = ref(null);

        const logDetailDialogVisible = ref(false);
        const currentScript = ref(null);
        const currentScriptLog = ref('');
        let logRefreshInterval = null;

        // 格式化脚本日志（HTML转义 + 换行符处理）
        const formattedScriptLog = computed(() => {
          const log = currentScriptLog.value;
          if (!log || log.trim() === '') return '暂无日志';
          // HTML转义
          const escaped = log
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
          // 换行符转换
          return escaped.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>');
        });

        // 格式化任务输出日志
        const formattedTaskOutput = computed(() => {
          const output = task.value?.output;
          if (!output || output.trim() === '') return '';
          // HTML转义
          const escaped = output
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
          // 换行符转换
          return escaped.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>');
        });

        const showUnitDetail = (unit) => {
          currentUnit.value = unit;
          unitDetailDialogVisible.value = true;
        };

        const showCurrentScriptLog = (unit) => {
          currentUnit.value = unit;
          // 从 unit 的 scripts 中找到正在运行的脚本
          const runningScript = (unit.scripts || []).find(s => s.status === 'running');
          if (runningScript) {
            showScriptLog(runningScript);
          }
        };

        // 刷新脚本日志
        const refreshScriptLog = async () => {
          if (!currentScript.value || !task.value?.latest_execution_id) return;

          try {
            const deviceIp = currentUnit.value?.device_ip || currentUnit.value?.ip;
            const scriptName = currentScript.value?.script_name || currentScript.value?.name;

            if (deviceIp && scriptName) {
              const response = await fetch(`/api/executions/${task.value.latest_execution_id}/logs/${encodeURIComponent(deviceIp)}/${encodeURIComponent(scriptName)}`);
              if (response.ok) {
                const data = await response.json();
                if (data?.log && data.log.trim() !== '') {
                  currentScriptLog.value = data.log;
                }
              }
            }
          } catch (err) {
            console.error('刷新日志失败:', err);
          }
        };

        const showScriptLog = async (script) => {
          currentScript.value = script;
          // 先尝试使用内存中的 output 字段
          let logContent = script?.output || script?.log || currentUnit.value?.logs || '';

          // 如果有日志文件路径或有 execution_id，尝试从文件读取
          if (task.value?.latest_execution_id) {
            try {
              const deviceIp = currentUnit.value?.device_ip || currentUnit.value?.ip;
              const scriptName = script?.script_name || script?.name;

              if (deviceIp && scriptName) {
                const url = `/api/executions/${task.value.latest_execution_id}/logs/${encodeURIComponent(deviceIp)}/${encodeURIComponent(scriptName)}`;
                const response = await fetch(url);
                if (response.ok) {
                  const data = await response.json();
                  if (data?.log && data.log.trim() !== '') {
                    logContent = data.log;
                  }
                }
              }
            } catch (err) {
              console.error('读取日志文件失败:', err);
            }
          }

          currentScriptLog.value = logContent;
          logDetailDialogVisible.value = true;

          // 如果脚本正在运行，启动自动刷新
          if (script?.status === 'running') {
            if (logRefreshInterval) {
              clearInterval(logRefreshInterval);
            }
            logRefreshInterval = setInterval(refreshScriptLog, 2000);
          }
        };

        const copyLog = async () => {
          try {
            await navigator.clipboard.writeText(currentScriptLog.value);
            ElementPlus.ElMessage.success('日志已复制到剪贴板');
          } catch (err) {
            ElementPlus.ElMessage.error('复制失败');
          }
        };

        const getScriptStatusType = (status) => {
          const types = {
            'completed': 'success',
            'running': 'info',
            'failed': 'danger',
            'pending': 'warning'
          };
          return types[status] || 'info';
        };

        const getUnitStatusType = (status) => {
          const types = {
            'completed': 'success',
            'running': 'info',
            'failed': 'danger',
            'pending': 'warning',
            'assigned': 'info',
            'cancelled': 'info'
          };
          return types[status] || 'info';
        };

        // 根据任务状态确定刷新间隔
        const getRefreshInterval = () => {
          if (task.value && task.value.status === 'running') {
            return FAST_REFRESH_INTERVAL;
          }
          return NORMAL_REFRESH_INTERVAL;
        };

        // 重新设置刷新定时器
        const resetRefreshInterval = () => {
          if (refreshInterval) {
            clearInterval(refreshInterval);
          }
          const interval = getRefreshInterval();
          refreshInterval = setInterval(() => {
            if (!editMode.value) {
              fetchTask();
            }
          }, interval);
        };

        // 检查任务是否已结束
        const isTaskEnded = (status) => {
          return ['completed', 'failed', 'cancelled'].includes(status);
        };

        const fetchTask = async () => {
          try {
            const oldStatus = task.value?.status;
            // 只有在首次加载时才显示 loading，刷新时不显示
            if (!task.value) {
              loading.value = true;
            }
            const response = await fetch(`/api/v1/tasks/${taskId}`);
            if (!response.ok) {
              throw new Error('获取任务失败');
            }
            task.value = await response.json();
            taskForm.name = task.value.name || '';
            taskForm.description = task.value.description || '';

            // 如果任务状态发生变化，调整刷新频率
            const newStatus = task.value.status;
            if (oldStatus !== newStatus) {
              if (newStatus === 'running') {
                // 任务开始运行，加快刷新频率
                resetRefreshInterval();
              } else if (isTaskEnded(newStatus)) {
                // 任务结束，降低刷新频率或停止
                if (refreshInterval) {
                  clearInterval(refreshInterval);
                  refreshInterval = null;
                }
              }
            }
          } catch (error) {
            console.error('获取任务失败:', error);
            // 只在首次加载失败时显示错误提示
            if (!task.value) {
              ElementPlus.ElMessage.error('获取任务失败');
            }
          } finally {
            loading.value = false;
          }
        };

        const saveTask = async () => {
          try {
            saving.value = true;
            const response = await fetch(`/api/v1/tasks/${taskId}`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(taskForm)
            });
            if (response.ok) {
              ElementPlus.ElMessage.success('保存成功');
              editMode.value = false;
              await fetchTask();
            } else {
              const error = await response.json();
              ElementPlus.ElMessage.error(error.error || '保存失败');
            }
          } catch (error) {
            console.error('保存失败:', error);
            ElementPlus.ElMessage.error('保存失败');
          } finally {
            saving.value = false;
          }
        };

        // 重置任务
        const resetTask = async () => {
          try {
            resetting.value = true;
            const resp = await fetch(`/api/v1/tasks/${taskId}/reset`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              }
            });
            if (resp.ok) {
              ElementPlus.ElMessage.success('任务已重置');
              await fetchTask();
              // 任务重置后，重新启动刷新
              if (!refreshInterval) {
                resetRefreshInterval();
              }
            } else {
              const err = await resp.json();
              ElementPlus.ElMessage.error(err.error || '重置失败');
            }
          } catch (err) {
            console.error('重置失败:', err);
            ElementPlus.ElMessage.error('重置失败');
          } finally {
            resetting.value = false;
          }
        };

         const startTask = async () => {
           try {
             // 创建一个表单并提交，使用POST请求
             const form = document.createElement('form');
             form.method = 'POST';
             form.action = `/tasks/${taskId}/start`;
             document.body.appendChild(form);
             form.submit();
           } catch (error) {
             console.error('启动任务失败:', error);
             ElementPlus.ElMessage.error('启动任务失败');
           }
         };

        const goBack = () => {
          window.location.href = '/tasks';
        };

        const goToReport = () => {
          window.location.href = `/tasks/${taskId}/report`;
        };

        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');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };

         const getStatusType = (status) => {
           const types = {
             'completed': 'success',
             'running': 'info',
             'failed': 'danger',
             'pending': 'warning',
             'cancelled': 'info'
           };
           return types[status] || 'info';
         };

        // 监听日志对话框关闭，停止自动刷新
        watch(logDetailDialogVisible, (newVal) => {
          if (!newVal && logRefreshInterval) {
            clearInterval(logRefreshInterval);
            logRefreshInterval = null;
          }
        });

        onMounted(() => {
           fetchTask().then(() => {
             // 首次获取任务后，如果任务还没结束，启动刷新
             if (task.value && !isTaskEnded(task.value.status)) {
               resetRefreshInterval();
             }
           });
          });

         onUnmounted(() => {
           if (refreshInterval) {
             clearInterval(refreshInterval);
           }
           if (logRefreshInterval) {
             clearInterval(logRefreshInterval);
           }
         });

          return {
            task,
            loading,
            saving,
            editMode,
            taskForm,
            fetchTask,
            saveTask,
            goBack,
            goToReport,
            formatTime,
            getStatusType,
            resetTask,
            resetting,
             startTask,
            unitDetailDialogVisible,
            currentUnit,
            showUnitDetail,
            showCurrentScriptLog,
            getUnitStatusType,
            logDetailDialogVisible,
            currentScript,
            currentScriptLog,
            showScriptLog,
            refreshScriptLog,
            copyLog,
            formattedScriptLog,
            formattedTaskOutput,
            getScriptStatusType
          };
      }
    });
    app.use(ElementPlus);
  app.mount('#app');
  </script>
<% end %>
