<template>
  <div class="convert-logs">
    <!-- Filter Bar -->
    <a-card class="filter-card" size="small">
      <a-row :gutter="16" align="middle">
        <a-col :span="5">
          <a-select
            v-model:value="filters.status"
            placeholder="按状态筛选"
            allow-clear
            style="width: 100%"
            @change="handleFilter"
          >
            <a-select-option value="success">成功</a-select-option>
            <a-select-option value="failed">失败</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
          <a-range-picker
            v-model:value="filters.dateRange"
            :placeholder="['开始日期', '结束日期']"
            style="width: 100%"
            @change="handleFilter"
          />
        </a-col>
        <a-col :span="3">
          <a-button @click="resetFilters">重置</a-button>
        </a-col>
        <a-col :flex="1" style="text-align: right">
          <a-button :loading="loading" @click="loadLogs(1, pagination.pageSize)">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <!-- Statistics Summary -->
    <a-row :gutter="16" class="stat-row">
      <a-col :span="6">
        <a-card size="small">
          <a-statistic title="总转换次数" :value="stats.total" :loading="loading">
            <template #prefix><SwapOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic title="成功" :value="stats.success" :loading="loading" :value-style="{ color: '#52c41a' }">
            <template #prefix><CheckCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic title="失败" :value="stats.failed" :loading="loading" :value-style="{ color: '#ff4d4f' }">
            <template #prefix><CloseCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic title="平均耗时" :value="stats.avgDuration" :loading="loading" suffix="ms">
            <template #prefix><ClockCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- Logs Table -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="logs"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        size="small"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'originalFilename'">
            <a-tooltip :title="record.originalFilename">
              <span>{{ record.originalFilename || '—' }}</span>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'formatConversion'">
            <a-tag color="blue">{{ (record.originalFormat || '?').toUpperCase() }}</a-tag>
            <span style="margin: 0 4px">→</span>
            <a-tag color="green">{{ (record.targetFormat || '?').toUpperCase() }}</a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-tooltip v-if="record.errorMessage" :title="record.errorMessage" placement="topLeft">
              <a-tag :color="record.status === 'success' ? 'green' : 'red'" style="cursor: help">
                {{ record.status === 'success' ? '成功' : '失败' }}
              </a-tag>
            </a-tooltip>
            <a-tag v-else :color="record.status === 'success' ? 'green' : 'red'">
              {{ record.status === 'success' ? '成功' : '失败' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'sizes'">
            <span>{{ formatSize(record.originalSize) }}</span>
            <span style="margin: 0 4px; color: #999">→</span>
            <span>{{ formatSize(record.outputSize) }}</span>
          </template>
          <template v-if="column.key === 'durationMs'">
            {{ record.durationMs != null ? `${record.durationMs} ms` : '—' }}
          </template>
          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { Dayjs } from 'dayjs'
import {
  ReloadOutlined,
  SwapOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import request from '@/api/request'
import type { ConvertLogRecord, TablePaginationParams } from '@/types/admin'
// 使用共享的日期格式化工具函数
// Use shared date formatting utility
import { formatDate } from '@/utils/format'

// ── State ──────────────────────────────────────────────────────────────────

const loading = ref(false)

const filters = reactive<{
  status: string | undefined
  dateRange: [Dayjs, Dayjs] | null
}>({
  status: undefined,
  dateRange: null,
})

const stats = reactive({
  total: 0,
  success: 0,
  failed: 0,
  avgDuration: 0,
})

const logs = ref<ConvertLogRecord[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
})

// ── Table columns ──────────────────────────────────────────────────────────

const columns = [
  { title: '文件名', dataIndex: 'originalFilename', key: 'originalFilename', ellipsis: true },
  { title: '格式转换', key: 'formatConversion', width: 180 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  { title: '文件大小', key: 'sizes', width: 160 },
  { title: '耗时', dataIndex: 'durationMs', key: 'durationMs', width: 100 },
  { title: '转换时间', dataIndex: 'createdAt', key: 'createdAt', width: 170 },
]

// ── Helpers ────────────────────────────────────────────────────────────────

function formatSize(bytes: number | null): string {
  if (bytes == null || bytes === 0) return '—'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

// ── Data loading ───────────────────────────────────────────────────────────

async function loadLogs(page = 1, pageSize = 20) {
  loading.value = true
  try {
    const params: Record<string, string | number> = {
      page,  // Java API uses 1-based page (internally converts to 0-based)
      size: pageSize,
    }
    if (filters.status) {
      params.status = filters.status
    }
    if (filters.dateRange && filters.dateRange[0] && filters.dateRange[1]) {
      params.startDate = filters.dateRange[0].format('YYYY-MM-DD HH:mm:ss')
      params.endDate = filters.dateRange[1].format('YYYY-MM-DD') + ' 23:59:59'
    }

    const res = await request.get('/api/converter/convert/logs', { params })
    const data = res.data

    logs.value = data.records || []
    pagination.total = data.total || 0
    pagination.current = page

    // Compute simple stats from current page
    computeStats(logs.value, data.total)
  } catch (err) {
    message.error('加载转换记录失败')
    logs.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 已知限制：成功/失败数和平均耗时仅基于当前页数据计算，非全量统计。
 * 总数 (total) 取自后端分页返回值。如后端提供聚合统计接口，应优先使用。
 * Known limitation: success/failed counts and avg duration are computed from
 * the current page only, not the full dataset. Total comes from backend pagination.
 */
function computeStats(records: ConvertLogRecord[], total: number) {
  const success = records.filter((r) => r.status === 'success').length
  const failed = records.filter((r) => r.status === 'failed').length
  const durations = records
    .filter((r) => r.durationMs != null)
    .map((r) => r.durationMs as number)

  stats.total = total
  stats.success = success
  stats.failed = failed
  stats.avgDuration = durations.length > 0
    ? Math.round(durations.reduce((a: number, b: number) => a + b, 0) / durations.length)
    : 0
}

function handleTableChange(pag: TablePaginationParams) {
  loadLogs(pag.current, pag.pageSize)
}

function handleFilter() {
  loadLogs(1, pagination.pageSize)
}

function resetFilters() {
  filters.status = undefined
  filters.dateRange = null
  loadLogs(1, pagination.pageSize)
}

// ── Lifecycle ──────────────────────────────────────────────────────────────

onMounted(() => {
  loadLogs(1, pagination.pageSize)
})
</script>

<style scoped lang="less">
.convert-logs {
  padding: 24px;

  .filter-card {
    margin-bottom: 16px;
  }

  .stat-row {
    margin-bottom: 16px;
  }

  .table-card {
    margin-top: 0;
  }
}
</style>
