<template>
  <div class="stats-table">
    <el-table
      v-bind="$attrs"
      :data="data"
      border
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column
        align="center"
        label="序号"
        width="60"
      >
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        label="项目名"
        align="center"
        width="150px"
        prop="project"
      >
        <template #default="scope">
          {{ scope.row.project || '-' }}
        </template>
      </el-table-column>

      <el-table-column
        label="Spider"
        align="center"
        prop="spider"
      >
        <template #default="scope">
          {{ scope.row.spider }}
        </template>
      </el-table-column>

      <el-table-column
        label="收集数量"
        align="center"
        width="80px"
        prop="item_scraped_count"
      >
        <template #default="scope">
          {{ scope.row.item_scraped_count }}
        </template>
      </el-table-column>

      <el-table-column
        label="丢弃数量"
        align="center"
        width="80px"
        prop="item_dropped_count"
      >
        <template #default="scope">
          {{ scope.row.item_dropped_count }}
        </template>
      </el-table-column>

      <el-table-column
        label="错误日志"
        align="center"
        width="110px"
        prop="log_error_count"
        sortable="custom"
      >
        <template #default="scope">
          {{ scope.row.log_error_count }}
        </template>
      </el-table-column>

      <el-table-column
        label="持续时间"
        align="right"
        width="110px"
        prop="duration"
        sortable="custom"
      >
        <template #default="scope">
          {{ scope.row.duration_str }}
        </template>
      </el-table-column>

      <el-table-column
        label="开始时间"
        align="center"
        width="170px"
        prop="start_time"
      >
        <template #default="scope">
          {{ scope.row.start_time }}
        </template>
      </el-table-column>

      <el-table-column
        label="结束时间"
        align="center"
        width="170px"
        prop="finish_time"
      >
        <template #default="scope">
          {{ scope.row.finish_time }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="180px"
      >
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="viewDetail(scope.row)"
          >
            详情
          </el-button>
          
          <el-button
            type="danger"
            size="small"
            @click="confirmRemove(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      
      <el-table-column
        label="运行日志"
        align="center"
        width="80px"
      >
        <template #default="scope">
          <router-link
            :to="{
              name: 'SpiderLogs',
              query: {
                scrapydServerId: scope.row.scrapyd_server_id,
                project: scope.row.project,
                spider: scope.row.spider,
                job: scope.row.spider_job_id
              }
            }"
            target="_blank"
          >
            <el-icon><Document /></el-icon> 日志
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="统计详情"
      width="70%"
    >
      <div v-if="currentDetail" class="stats-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名">{{ currentDetail.project }}</el-descriptions-item>
          <el-descriptions-item label="爬虫名">{{ currentDetail.spider }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentDetail.start_time }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentDetail.finish_time }}</el-descriptions-item>
          <el-descriptions-item label="收集数量">{{ currentDetail.item_scraped_count }}</el-descriptions-item>
          <el-descriptions-item label="丢弃数量">{{ currentDetail.item_dropped_count }}</el-descriptions-item>
          <el-descriptions-item label="持续时间">{{ currentDetail.duration_str }}</el-descriptions-item>
          <el-descriptions-item label="结束原因">{{ currentDetail.finish_reason || '-' }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section" v-if="currentDetail.stats">
          <h3>统计详情</h3>
          <el-table :data="statsTableData" border style="width: 100%">
            <el-table-column prop="key" label="指标名称" min-width="250px" />
            <el-table-column prop="value" label="值" min-width="100px" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, computed } from 'vue'
import { Document } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import * as statsApi from '@/api/stats'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['sort-change'])

const dialogVisible = ref(false)
const currentDetail = ref<Record<string, any> | null>(null)

// 统计数据表格展示
const statsTableData = computed(() => {
  if (!currentDetail.value || !currentDetail.value.stats) return []
  
  return Object.entries(currentDetail.value.stats)
    .filter(([key]) => key !== 'spider' && key !== 'project') // 过滤掉已显示在上方的字段
    .map(([key, value]) => ({
      key,
      value: String(value)
    }))
    .sort((a, b) => a.key.localeCompare(b.key))
})

// 查看详情
const viewDetail = async (row: Record<string, any>) => {
  try {
    const res = await statsApi.getStatsDetail({
      scrapydServerId: row.scrapyd_server_id,
      spider_job_id: row.spider_job_id
    })
    
    if (res.code === 0) {
      currentDetail.value = res.data
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取统计详情失败:', error)
  }
}

// 确认删除
const confirmRemove = (row: Record<string, any>) => {
  ElMessageBox.confirm('确认删除该统计记录?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await statsApi.removeStats({
          scrapydServerId: row.scrapyd_server_id,
          spider_job_id: row.spider_job_id
        })
        
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          emit('sort-change', { prop: '', order: '' }) // 触发刷新
        }
      } catch (error) {
        console.error('删除统计记录失败:', error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 排序变化
const handleSortChange = (val: { prop: string, order: string }) => {
  emit('sort-change', val)
}
</script>

<style lang="scss" scoped>
.stats-table {
  margin-bottom: 20px;
}

.stats-detail {
  .detail-section {
    margin-top: 20px;
    
    h3 {
      margin-bottom: 15px;
      font-weight: 500;
      font-size: 16px;
    }
  }
}
</style>
