<template>
  <div class="history-manager">
    <el-card class="history-control-card">
      <template #header>
        <div class="card-header">
          <h3>历史记录管理</h3>
          <div class="control-buttons">
            <el-button @click="refreshHistory">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="primary" @click="exportHistory">
              <el-icon><Download /></el-icon>
              导出历史
            </el-button>
          </div>
        </div>
      </template>
      
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="算法">
          <el-select 
            v-model="filters.algorithmId" 
            placeholder="选择算法" 
            clearable
            @change="applyFilters"
          >
            <el-option 
              v-for="algorithm in availableAlgorithms" 
              :key="algorithm.id" 
              :label="algorithm.name" 
              :value="algorithm.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select 
            v-model="filters.status" 
            placeholder="选择状态" 
            clearable
            @change="applyFilters"
          >
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
            <el-option label="待处理" value="pending" />
            <el-option label="运行中" value="running" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filters.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="applyFilters"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ stats.totalCalls }}</div>
            <div class="stat-label">总调用次数</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ stats.successRate }}%</div>
            <div class="stat-label">成功率</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ stats.avgResponseTime }}s</div>
            <div class="stat-label">平均响应时间</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ stats.todayCalls }}</div>
            <div class="stat-label">今日调用</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 历史记录表格 -->
    <el-card class="history-table-card">
      <template #header>
        <div class="table-header">
          <h4>调用历史</h4>
          <div class="table-controls">
            <el-checkbox v-model="showDetails" @change="toggleDetails">显示详情</el-checkbox>
            <el-button 
              type="primary" 
              :disabled="selectedRows.length === 0" 
              @click="compareSelected"
            >
              对比选中项
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="historyData"
        @selection-change="handleSelectionChange"
        row-key="id"
        :default-expand-all="showDetails"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="调用ID" width="200" show-overflow-tooltip />
        <el-table-column prop="algorithm_name" label="算法名称" width="150" show-overflow-tooltip />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="response_time" label="响应时间(s)" width="120" sortable>
          <template #default="{ row }">
            {{ row.response_time ? row.response_time.toFixed(3) : 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="调用时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetails(row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="rerunCall(row)">重新运行</el-button>
          </template>
        </el-table-column>
        
        <!-- 详情展开行 -->
        <el-table-column v-if="showDetails" type="expand" width="1">
          <template #default="{ row }">
            <div class="expand-details">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="输入数据">
                  <pre class="data-preview">{{ JSON.stringify(row.input_data, null, 2) }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="输出数据">
                  <pre class="data-preview">{{ JSON.stringify(row.output_data, null, 2) }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="参数">
                  <pre class="data-preview">{{ JSON.stringify(row.params, null, 2) }}</pre>
                </el-descriptions-item>
                <el-descriptions-item label="错误信息" v-if="row.error_message">
                  <span class="error-text">{{ row.error_message }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="调用详情"
      width="80%"
      top="5vh"
    >
      <div v-if="selectedRow" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="调用ID">{{ selectedRow.id }}</el-descriptions-item>
          <el-descriptions-item label="算法名称">{{ selectedRow.algorithm_name }}</el-descriptions-item>
          <el-descriptions-item label="算法ID">{{ selectedRow.algorithm_id }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ selectedRow.version }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedRow.status)">{{ selectedRow.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="响应时间">
            {{ selectedRow.response_time ? selectedRow.response_time.toFixed(3) + 's' : 'N/A' }}
          </el-descriptions-item>
          <el-descriptions-item label="调用时间">{{ formatDate(selectedRow.created_at) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">输入数据</el-divider>
        <json-editor :value="selectedRow.input_data" :height="200" :readonly="true" />
        
        <el-divider content-position="left">输出数据</el-divider>
        <json-editor :value="selectedRow.output_data" :height="300" :readonly="true" />
        
        <el-divider content-position="left">参数</el-divider>
        <json-editor :value="selectedRow.params" :height="150" :readonly="true" />
        
        <el-divider content-position="left">错误信息</el-divider>
        <el-alert
          v-if="selectedRow.error_message"
          :title="selectedRow.error_message"
          type="error"
          show-icon
        />
        <el-alert v-else title="无错误信息" type="success" show-icon />
      </div>
    </el-dialog>
    
    <!-- 对比对话框 -->
    <el-dialog
      v-model="compareDialogVisible"
      title="结果对比"
      width="90%"
      top="5vh"
    >
      <div v-if="comparisonData.length > 0" class="comparison-content">
        <el-table :data="comparisonData" style="width: 100%">
          <el-table-column prop="algorithm_name" label="算法名称" width="150" />
          <el-table-column prop="version" label="版本" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="response_time" label="响应时间(s)" width="120">
            <template #default="{ row }">
              {{ row.response_time ? row.response_time.toFixed(3) : 'N/A' }}
            </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="viewCompareDetails(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-divider content-position="left">对比结果可视化</el-divider>
        <result-visualization 
          :result-data="combinedComparisonData"
          :enable-comparison="true"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import JsonEditor from '../common/JsonEditor.vue'
import ResultVisualization from './ResultVisualization.vue'
import { useAlgorithmStore } from '../../stores/algorithm'
import { useUserStore } from '../../stores/user'

// 定义props
interface Props {
  userId?: string
}

const props = withDefaults(defineProps<Props>(), {
  userId: ''
})

// 状态
const algorithmStore = useAlgorithmStore()
const userStore = useUserStore()
const historyData = ref<any[]>([])
const availableAlgorithms = ref<any[]>([])
const selectedRow = ref<any>(null)
const selectedRows = ref<any[]>([])
const detailDialogVisible = ref(false)
const compareDialogVisible = ref(false)
const comparisonData = ref<any[]>([])
const showDetails = ref(false)

// 过滤器
const filters = reactive({
  algorithmId: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 统计信息
const stats = reactive({
  totalCalls: 0,
  successRate: 0,
  avgResponseTime: 0,
  todayCalls: 0
})

// 计算属性
const combinedComparisonData = computed(() => {
  // 将多个结果合并为一个可用于可视化的数据结构
  return {
    results: comparisonData.value.map((item, index) => ({
      id: item.id,
      algorithm: item.algorithm_name,
      version: item.version,
      status: item.status,
      response_time: item.response_time,
      created_at: item.created_at
    }))
  }
})

// 方法
const loadHistory = async () => {
  try {
    // 加载算法列表
    await algorithmStore.fetchAlgorithms()
    availableAlgorithms.value = algorithmStore.algorithms
    
    // 加载历史记录
    await loadCallHistory()
    
    // 加载统计信息
    await loadStatistics()
  } catch (error) {
    console.error('Failed to load history:', error)
    ElMessage.error('加载历史记录失败')
  }
}

const loadCallHistory = async () => {
  try {
    // 模拟API调用 - 在实际应用中，这里会调用后端API
    // 获取当前用户ID
    const userId = props.userId || userStore.user?.id
    
    // 构造查询参数
    const params: any = {
      user_id: userId,
      skip: (pagination.currentPage - 1) * pagination.pageSize,
      limit: pagination.pageSize
    }
    
    if (filters.algorithmId) {
      params.algorithm_id = filters.algorithmId
    }
    
    if (filters.status) {
      params.status = filters.status
    }
    
    // 模拟加载数据
    historyData.value = [
      {
        id: 'call-001',
        algorithm_id: 'alg-001',
        algorithm_name: '图像分类算法',
        version: 'v1.0',
        status: 'success',
        response_time: 1.234,
        created_at: '2023-12-01T10:30:00Z',
        input_data: { image_url: 'https://example.com/image.jpg' },
        output_data: { predictions: [{ class: 'cat', confidence: 0.95 }] },
        params: { threshold: 0.5 }
      },
      {
        id: 'call-002',
        algorithm_id: 'alg-002',
        algorithm_name: '文本情感分析',
        version: 'v2.1',
        status: 'success',
        response_time: 0.789,
        created_at: '2023-12-01T11:15:00Z',
        input_data: { text: '今天天气很好' },
        output_data: { sentiment: 'positive', score: 0.89 },
        params: { model: 'bert-base' }
      },
      {
        id: 'call-003',
        algorithm_id: 'alg-001',
        algorithm_name: '图像分类算法',
        version: 'v1.0',
        status: 'failed',
        response_time: null,
        created_at: '2023-12-01T12:00:00Z',
        input_data: { image_url: 'https://example.com/bad_image.jpg' },
        output_data: {},
        params: { threshold: 0.9 },
        error_message: '模型推理失败'
      }
    ]
    
    pagination.total = historyData.value.length
  } catch (error) {
    console.error('Failed to load call history:', error)
    ElMessage.error('加载调用历史失败')
  }
}

const loadStatistics = async () => {
  try {
    // 模拟加载统计数据
    stats.totalCalls = 156
    stats.successRate = 92.3
    stats.avgResponseTime = 1.45
    stats.todayCalls = 12
  } catch (error) {
    console.error('Failed to load statistics:', error)
    ElMessage.error('加载统计信息失败')
  }
}

const refreshHistory = async () => {
  await loadHistory()
  ElMessage.success('历史记录已刷新')
}

const exportHistory = async () => {
  try {
    // 模拟导出功能
    ElMessage.success('历史记录导出功能已启动')
  } catch (error) {
    console.error('Failed to export history:', error)
    ElMessage.error('导出历史记录失败')
  }
}

const applyFilters = async () => {
  await loadCallHistory()
}

const resetFilters = () => {
  filters.algorithmId = ''
  filters.status = ''
  filters.dateRange = []
  pagination.currentPage = 1
  loadCallHistory()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const viewDetails = (row: any) => {
  selectedRow.value = row
  detailDialogVisible.value = true
}

const viewCompareDetails = (row: any) => {
  selectedRow.value = row
  detailDialogVisible.value = true
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'success': return 'success'
    case 'failed': return 'danger'
    case 'pending': return 'warning'
    case 'running': return 'info'
    default: return 'info'
  }
}

const formatDate = (dateString: string) => {
  if (!dateString) return 'N/A'
  return new Date(dateString).toLocaleString()
}

const toggleDetails = () => {
  // 切换详情显示状态
}

const compareSelected = async () => {
  if (selectedRows.value.length < 2) {
    ElMessage.warning('请至少选择两个调用记录进行对比')
    return
  }
  
  try {
    // 模拟获取对比数据
    const callIds = selectedRows.value.map((row: any) => row.id)
    comparisonData.value = [...selectedRows.value]
    compareDialogVisible.value = true
  } catch (error) {
    console.error('Failed to get comparison data:', error)
    ElMessage.error('获取对比数据失败')
  }
}

const rerunCall = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新运行调用 "${row.id}" 吗？`,
      '重新运行',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟重新运行调用
    ElMessage.success('重新运行请求已提交')
  } catch {
    // 用户取消操作
  }
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadCallHistory()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadCallHistory()
}

// 初始化
onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.history-manager {
  width: 100%;
}

.history-control-card {
  margin-bottom: 20px;
}

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

.control-buttons {
  display: flex;
  gap: 10px;
}

.filter-form {
  margin-top: 15px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.history-table-card {
  margin-top: 20px;
}

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

.table-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.expand-details {
  padding: 20px;
}

.data-preview {
  max-height: 200px;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
}

.error-text {
  color: #F56C6C;
  font-weight: bold;
}

.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.comparison-content {
  max-height: 70vh;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

:deep(.el-table__expanded-cell) {
  padding: 20px;
}
</style>
</template>
</file_path>