<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { targetApi, reportApi } from '@/api/service-monitor'
import { useUserStore } from '@/stores/user'
import type { ReportSummary } from '@/types/service-monitor'

const router = useRouter()
const userStore = useUserStore()

const reports = ref<ReportSummary[]>([])
const targets = ref<{ id: string; name: string }[]>([])
const loading = ref(false)
const filterTargetId = ref('')
const selectedIds = ref<string[]>([])

const isAdmin = computed(() => userStore.isAdmin)

const filteredReports = computed(() => {
  if (!filterTargetId.value) return reports.value
  return reports.value.filter(r => r.target_id === filterTargetId.value)
})

// Load data
async function loadData() {
  loading.value = true
  try {
    const [reportsRes, targetsRes] = await Promise.all([
      reportApi.getReports(),
      targetApi.getTargets(),
    ])
    reports.value = reportsRes.reports || []
    targets.value = (targetsRes.targets || []).map(t => ({ id: t.id, name: t.name }))
  } catch (e) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// View report detail
function viewReport(reportId: string) {
  router.push({ name: 'MonitorReportDetail', params: { reportId } })
}

// Selection
function toggleSelectAll(checked: string | number | boolean) {
  if (checked) {
    selectedIds.value = filteredReports.value.map(r => r.id)
  } else {
    selectedIds.value = []
  }
}

function toggleSelect(id: string) {
  const idx = selectedIds.value.indexOf(id)
  if (idx >= 0) {
    selectedIds.value.splice(idx, 1)
  } else {
    selectedIds.value.push(id)
  }
}

function isSelected(id: string) {
  return selectedIds.value.includes(id)
}

const isAllSelected = computed(() => {
  return filteredReports.value.length > 0 && selectedIds.value.length === filteredReports.value.length
})

// Batch delete
async function batchDelete() {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的报告')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedIds.value.length} 份报告？此操作不可恢复。`,
      '确认删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const res = await reportApi.batchDeleteReports({ ids: selectedIds.value })
    ElMessage.success(`成功删除 ${res.deleted} 份报告`)
    selectedIds.value = []
    loadData()
  } catch {
    // 取消
  }
}

// Format time
function formatTime(timeStr: string | undefined) {
  if (!timeStr) return '-'
  return timeStr.slice(0, 16).replace('T', ' ')
}

// Suite label
function suiteLabel(suite: string) {
  return suite === 'quick' ? '快速' : '全量'
}

onMounted(loadData)
</script>

<template>
  <div class="page-reports">
    <div class="section-head">
      <h1 class="section-title">巡检报告</h1>
    </div>

    <!-- Filter bar -->
    <div class="filter-bar">
      <el-select
        v-model="filterTargetId"
        placeholder="全部目标"
        clearable
        style="width: 200px;"
      >
        <el-option
          v-for="t in targets"
          :key="t.id"
          :label="t.name"
          :value="t.id"
        />
      </el-select>
      <span class="report-count">共 {{ filteredReports.length }} 条报告</span>
    </div>

    <!-- Batch operations -->
    <div v-if="isAdmin && selectedIds.length > 0" class="batch-bar">
      <el-checkbox
        :model-value="isAllSelected"
        @change="toggleSelectAll"
      />
      <span class="batch-count">已选 {{ selectedIds.length }} 条</span>
      <el-button type="danger" size="small" @click="batchDelete">
        批量删除
      </el-button>
    </div>

    <!-- Report list -->
    <el-card v-loading="loading" class="table-card">
      <el-table
        v-if="filteredReports.length > 0"
        :data="filteredReports"
        style="width: 100%"
        @row-click="(row: ReportSummary) => viewReport(row.id)"
      >
        <el-table-column v-if="isAdmin" width="40">
          <template #default="{ row }">
            <el-checkbox
              :model-value="isSelected(row.id)"
              @change="toggleSelect(row.id)"
              @click.stop
            />
          </template>
        </el-table-column>
        <el-table-column prop="target_name" label="目标" min-width="150">
          <template #default="{ row }">
            <span class="name-cell">{{ row.target_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="套件" width="80">
          <template #default="{ row }">
            {{ suiteLabel(row.suite) }}
          </template>
        </el-table-column>
        <el-table-column label="结果" min-width="150">
          <template #default="{ row }">
            <span class="summary-badge ok">正常{{ row.summary?.正常 || 0 }}</span>
            <span class="summary-badge warn">警告{{ row.summary?.警告 || 0 }}</span>
            <span class="summary-badge crit">严重{{ row.summary?.严重 || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="160">
          <template #default="{ row }">
            <span class="time-cell">{{ formatTime(row.started_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click.stop="viewReport(row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无巡检报告" />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.page-reports {
  padding: 0 0 40px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: $gray-900;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.report-count {
  font-size: 13px;
  color: $gray-500;
  margin-left: auto;
}

.batch-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 18px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid $gray-200;
  margin-bottom: 12px;
}

.batch-count {
  font-size: 14px;
  color: $gray-700;
  font-weight: 600;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  :deep(.el-table__row) {
    cursor: pointer;
  }
}

.name-cell {
  font-weight: 600;
  color: $gray-900;
}

.summary-badge {
  font-size: 13px;
  margin-right: 8px;

  &.ok { color: $green; }
  &.warn { color: $yellow; }
  &.crit { color: $red; }
}

.time-cell {
  font-size: 13px;
  color: $gray-500;
}

@media screen and (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .report-count {
    margin-left: 0;
    text-align: right;
    font-size: 12px;
  }
}
</style>