<template>
  <MainLayout>
    <div class="executions">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>执行记录</span>
              <el-button 
                type="primary" 
                @click="handleRefresh"
                :loading="executionStore.loading"
              >
                刷新
              </el-button>
            </div>
          </template>
          
          <!-- 筛选和搜索栏 -->
          <div class="filter-bar">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索执行ID、工作流ID..."
                  clearable
                  @clear="handleSearch"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="filterStatus"
                  placeholder="状态筛选"
                  clearable
                  @change="handleFilter"
                >
                  <el-option label="全部" value="" />
                  <el-option label="等待中" value="pending" />
                  <el-option label="执行中" value="running" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="失败" value="failed" />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-col>
            </el-row>
          </div>
          
          <el-table 
            :data="executionStore.executions" 
            v-loading="executionStore.loading" 
            style="width: 100%"
            @row-click="handleRowClick"
          >
            <el-table-column prop="id" label="ID" width="200">
              <template #default="{ row }">
                <el-link type="primary" @click.stop="handleViewDetail(row)">
                  {{ row.id.substring(0, 8) }}...
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="workflow_id" label="工作流ID" width="200">
              <template #default="{ row }">
                <span v-if="row.workflow_id">{{ row.workflow_id.substring(0, 8) }}...</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="execution_time" label="执行时间" width="120">
              <template #default="{ row }">
                <span v-if="row.execution_time">
                  {{ formatTime(row.execution_time) }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  @click.stop="handleViewDetail(row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="executionStore.executions.length === 0 && !executionStore.loading" class="empty-state">
            <el-empty description="暂无执行记录" />
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="executionStore.executions.length > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useExecutionStore } from '@/stores/execution'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import MainLayout from '@/components/MainLayout.vue'

const router = useRouter()
const route = useRoute()
const executionStore = useExecutionStore()

const workflowId = route.query.workflow_id as string | undefined

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 筛选和搜索
const searchKeyword = ref('')
const filterStatus = ref('')

onMounted(async () => {
  await loadExecutions()
})

// 监听路由变化
watch(() => route.query.workflow_id, async (newWorkflowId) => {
  currentPage.value = 1
  await loadExecutions()
})

const loadExecutions = async () => {
  try {
    const result = await executionStore.fetchExecutions({
      workflowId: workflowId,
      status: filterStatus.value || undefined,
      search: searchKeyword.value || undefined,
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    })
    // 注意：后端没有返回总数，这里使用结果长度作为估算
    // 实际应该从后端返回total字段
    total.value = result.length >= pageSize.value ? (currentPage.value * pageSize.value + 1) : ((currentPage.value - 1) * pageSize.value + result.length)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '获取执行记录失败')
  }
}

const handleRefresh = () => {
  loadExecutions()
}

const handleBack = () => {
  router.push('/')
}

const handleRowClick = (row: any) => {
  router.push(`/executions/${row.id}`)
}

const handleViewDetail = (row: any) => {
  router.push(`/executions/${row.id}`)
}

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

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

const formatTime = (ms: number) => {
  if (ms < 1000) {
    return `${ms}ms`
  } else if (ms < 60000) {
    return `${(ms / 1000).toFixed(2)}s`
  } else {
    return `${(ms / 60000).toFixed(2)}min`
  }
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadExecutions()
}

// 筛选
const handleFilter = () => {
  currentPage.value = 1
  loadExecutions()
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  currentPage.value = 1
  loadExecutions()
}

// 分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadExecutions()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadExecutions()
}
</script>

<style scoped>
.executions {
  width: 100%;
  height: 100vh;
}

.el-header {
  background-color: #409eff;
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.el-main {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.empty-state {
  padding: 40px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
