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

interface Log {
  id: number
  task_id: number
  camera_id: number
  check_time: string
  snapshot_path: string
  alarm_name: string
  alarm_content: string
  area: string
  is_alarm: boolean
}

const logs = ref<Log[]>([])
const onlyAlarm = ref(false)
const dialogVisible = ref(false)
const currentImage = ref('')
const selectedLogIds = ref<number[]>([])
const dateRange = ref<[Date, Date] | null>(null)

const fetchLogs = async () => {
  const res = await api.get('/logs', { params: { only_alarm: onlyAlarm.value } })
  logs.value = res.data
}

const handleExport = async () => {
  try {
    const params: any = {}
    if (dateRange.value) {
      params.start_time = dateRange.value[0].toISOString()
      params.end_time = dateRange.value[1].toISOString()
    }
    
    const res = await api.get('/logs/export', { 
      params,
      responseType: 'blob'
    })
    
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    link.setAttribute('download', `logs_${timestamp}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (e) {
    console.error(e)
    ElMessage.error('导出失败')
  }
}

const handleSelectionChange = (selection: Log[]) => {
  selectedLogIds.value = selection.map(log => log.id)
}

const handleBatchDelete = async () => {
  if (selectedLogIds.value.length === 0) {
    ElMessage.warning('请选择要删除的日志')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedLogIds.value.length} 条日志？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await api.delete('/logs/batch', { data: selectedLogIds.value })
      ElMessage.success('删除成功')
      fetchLogs()
      selectedLogIds.value = []
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const handleMisjudgment = async (log: Log) => {
  ElMessageBox.confirm('确认标记为误判并删除该记录？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await api.delete('/logs/batch', { data: [log.id] })
      ElMessage.success('已标记为误判并删除')
      fetchLogs()
    } catch (e) {
      ElMessage.error('操作失败')
    }
  })
}

const showImage = (path: string) => {
  currentImage.value = path
  dialogVisible.value = true
}

onMounted(fetchLogs)
</script>

<template>
  <div class="logs-view">
    <div class="toolbar">
      <el-checkbox v-model="onlyAlarm" @change="fetchLogs" label="仅显示异常" style="margin-right: 20px;" />
      
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        style="margin-right: 10px;"
      />
      
      <el-button type="success" @click="handleExport">导出 Excel</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedLogIds.length === 0">批量删除</el-button>
      <el-button @click="fetchLogs" icon="Refresh" circle style="margin-left: 10px;" />
    </div>
    
    <el-table :data="logs" style="width: 100%" height="80vh" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="check_time" label="时间" width="180">
        <template #default="scope">
           {{ new Date(scope.row.check_time).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="camera_id" label="摄像头ID" width="80" />
      <el-table-column prop="alarm_name" label="告警名称" width="150" />
      <el-table-column prop="alarm_content" label="详情内容" />
      <el-table-column prop="area" label="区域" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
           <el-tag :type="scope.row.is_alarm ? 'danger' : 'success'">
             {{ scope.row.is_alarm ? '异常' : '正常' }}
           </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="showImage(scope.row.snapshot_path)">查看</el-button>
          <el-button 
             v-if="scope.row.is_alarm" 
             type="danger" 
             plain
             size="small" 
             @click="handleMisjudgment(scope.row)"
           >
             误判
           </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="报警截图" width="80%">
      <img :src="currentImage" style="width: 100%;" />
    </el-dialog>
  </div>
</template>

<style scoped>
.toolbar {
  padding: 20px 0;
  display: flex;
  align-items: center;
}
</style>