<template>
  <div class="page-container">
    <div class="page-toolbar">
      <el-select v-model="filterDevice" placeholder="筛选设备" clearable style="width:220px;margin-right:12px" @change="fetchEvents">
        <el-option v-for="d in deviceList" :key="d.device_uid" :label="d.hostname" :value="d.device_uid" />
      </el-select>
      <el-button @click="fetchEvents">刷新</el-button>
    </div>
    <div class="csm-card">
      <el-table :data="events" v-loading="loading" style="width:100%">
        <el-table-column prop="device_uid" label="设备" min-width="120">
          <template #default="{ row }"><span class="mono-text">{{ row.device_uid?.substring(0, 8) }}...</span></template>
        </el-table-column>
        <el-table-column prop="document_name" label="文档名称" min-width="200">
          <template #default="{ row }">{{ row.document_name || '-' }}</template>
        </el-table-column>
        <el-table-column prop="printer_name" label="打印机" width="160">
          <template #default="{ row }">{{ row.printer_name || '-' }}</template>
        </el-table-column>
        <el-table-column prop="pages" label="页数" width="80" />
        <el-table-column prop="copies" label="份数" width="80" />
        <el-table-column prop="user_name" label="用户" width="120">
          <template #default="{ row }">{{ row.user_name || '-' }}</template>
        </el-table-column>
        <el-table-column prop="file_size_bytes" label="文件大小" width="110">
          <template #default="{ row }">{{ row.file_size_bytes ? (row.file_size_bytes / 1024).toFixed(1) + ' KB' : '-' }}</template>
        </el-table-column>
        <el-table-column prop="timestamp" label="时间" width="180" />
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '@/lib/api'

const events = ref<any[]>([])
const loading = ref(false)
const filterDevice = ref('')
const deviceList = ref<any[]>([])

async function fetchDevices() {
  try {
    const data = await api.get<any>('/api/devices')
    deviceList.value = data.devices || []
  } catch (e) { console.error('Failed to load device list', e); ElMessage.warning('加载设备列表失败') }
}

async function fetchEvents() {
  loading.value = true
  try {
    const query = filterDevice.value ? `?device_uid=${filterDevice.value}` : ''
    const data = await api.get<any>(`/api/plugins/print-audit/events${query}`)
    events.value = data.events || []
  } catch (e) { console.error('Failed to load print audit events', e); ElMessage.warning('加载打印审计记录失败') } finally { loading.value = false }
}

onMounted(() => { fetchDevices(); fetchEvents() })
</script>
