<!--
  页面名称：Logs.vue
  页面描述：操作日志页面，展示系统执行记录
  路径：/system/logs

  @author czj
  @date 2026-07-29
-->

<template>
  <div class="operation-logs-page">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-select
        v-model="filterStatus"
        placeholder="状态筛选"
        style="width: 150px"
        clearable
        @change="loadLogs"
      >
        <el-option label="全部" value="" />
        <el-option label="已完成" value="completed" />
        <el-option label="运行中" value="running" />
        <el-option label="待执行" value="pending" />
        <el-option label="已取消" value="cancelled" />
      </el-select>
      <el-button :icon="Refresh" @click="loadLogs" :loading="loading">
        刷新
      </el-button>
    </div>

    <!-- 日志列表 -->
    <el-card shadow="never">
      <el-table
        :data="logs"
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="执行名称" prop="name" min-width="200" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small" effect="dark">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总用例" width="80" align="center" prop="total_cases" />
        <el-table-column label="通过" width="80" align="center">
          <template #default="{ row }">
            <span class="text-passed">{{ row.passed ?? 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失败" width="80" align="center">
          <template #default="{ row }">
            <span class="text-failed">{{ row.failed ?? 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通过率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getPassRateClass(row)">
              {{ formatPassRate(row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="耗时" width="100" align="center">
          <template #default="{ row }">
            {{ row.duration != null ? `${Number(row.duration).toFixed(1)}s` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-bar">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="loadLogs"
          @current-change="loadLogs"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 操作日志页面
 *
 * 展示系统执行记录列表，复用 /api/executions 接口。
 */

import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { executionApi } from '@/api/executions'

const loading = ref(false)
const logs = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const filterStatus = ref('')

async function loadLogs() {
  loading.value = true
  try {
    const params: Record<string, any> = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
    }
    if (filterStatus.value) {
      params.status = filterStatus.value
    }
    const result = await executionApi.list(params)
    logs.value = result.items || []
    total.value = result.total || 0
  } catch (e: any) {
    ElMessage.error(e?.message || '获取操作日志失败')
  } finally {
    loading.value = false
  }
}

function getStatusType(status: string): string {
  const map: Record<string, string> = {
    completed: 'success',
    running: 'primary',
    pending: 'info',
    cancelled: 'warning',
    failed: 'danger',
  }
  return map[status] || 'info'
}

function getStatusText(status: string): string {
  const map: Record<string, string> = {
    completed: '已完成',
    running: '运行中',
    pending: '待执行',
    cancelled: '已取消',
    failed: '失败',
  }
  return map[status] || status
}

function formatPassRate(row: any): string {
  if (row.pass_rate != null) return `${row.pass_rate}%`
  if (row.total_cases > 0) {
    const rate = Math.round(((row.passed || 0) / row.total_cases) * 1000) / 10
    return `${rate}%`
  }
  return '-'
}

function getPassRateClass(row: any): string {
  const rate = row.pass_rate != null
    ? row.pass_rate
    : (row.total_cases > 0 ? ((row.passed || 0) / row.total_cases) * 100 : -1)
  if (rate < 0) return ''
  if (rate >= 90) return 'text-passed'
  if (rate >= 70) return 'text-warning'
  return 'text-failed'
}

function formatTime(time: string | null | undefined): string {
  if (!time) return '-'
  try {
    const d = new Date(time)
    if (isNaN(d.getTime())) return time
    const pad = (n: number) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return time
  }
}

onMounted(() => {
  loadLogs()
})
</script>

<style scoped>
.operation-logs-page {
  max-width: 1400px;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.pagination-bar {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.text-passed {
  color: #67c23a;
  font-weight: 600;
}

.text-failed {
  color: #f56c6c;
  font-weight: 600;
}

.text-warning {
  color: #e6a23c;
  font-weight: 600;
}
</style>
