<template>
  <div class="overview-page" v-loading="loading">
    <section class="page-head">
      <div><span class="eyebrow">TODAY'S WARNING DESK</span><h1>今日预警概况</h1><p>数据更新：{{ stats.generatedAt || '正在加载' }}</p></div>
      <el-button type="primary" :loading="loading" @click="loadData"><el-icon><Refresh /></el-icon>刷新数据</el-button>
    </section>
    <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon closable class="error-alert" @close="errorMessage = ''" />
    <div class="metric-grid">
      <button class="metric-card danger" :class="{ active: activeTab === 'unresolved' }" type="button" @click="selectTab('unresolved')"><span class="metric-label">仍未解除</span><strong>{{ unresolvedCount }}</strong><small>截至当前仍需关注的预警</small></button>
      <button class="metric-card success" :class="{ active: activeTab === 'resolved' }" type="button" @click="selectTab('resolved')"><span class="metric-label">今日已解除</span><strong>{{ resolvedCount }}</strong><small>今日完成闭环的预警数量</small></button>
      <button class="metric-card primary" :class="{ active: activeTab === 'all' }" type="button" @click="selectTab('all')"><span class="metric-label">今日预警总量</span><strong>{{ totalCount }}</strong><small>今天发布的全部非草稿预警</small></button>
    </div>
    <el-card shadow="never" class="table-card">
      <template #header><div class="card-title"><div><span>{{ tabTitle }}</span><em>{{ total }} 条</em></div><div class="filters"><el-select v-model="warningType" clearable placeholder="全部类型" @change="resetPage"><el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select><el-select v-model="warningLevel" clearable placeholder="全部级别" @change="resetPage"><el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select><el-input v-model="keyword" clearable placeholder="搜索名称、专项或位置" class="search-input" @keyup.enter="resetPage" @clear="resetPage"><template #prefix><el-icon><Search /></el-icon></template></el-input><el-button type="primary" @click="resetPage">查询</el-button></div></div></template>
      <el-table v-loading="tableLoading" :data="rows" stripe highlight-current-row empty-text="暂无符合条件的预警" @row-click="openDetail">
        <el-table-column label="预警事项" min-width="190" show-overflow-tooltip><template #default="{ row }">{{ row.warningName || row.warning_name || '未命名预警' }}</template></el-table-column>
        <el-table-column label="预警类型" width="120"><template #default="{ row }">{{ warningTypeText(row) }}</template></el-table-column>
        <el-table-column label="预警专项" min-width="150" show-overflow-tooltip><template #default="{ row }">{{ row.warningSpecial || row.warning_special || '未设置' }}</template></el-table-column>
        <el-table-column label="位置" min-width="170" show-overflow-tooltip><template #default="{ row }">{{ row.location || '未设置' }}</template></el-table-column>
        <el-table-column label="发布时间" min-width="165"><template #default="{ row }">{{ formatDashboardTime(row.publishTime || row.publish_time || row.createTime) }}</template></el-table-column>
        <el-table-column label="状态" width="105" align="center"><template #default="{ row }"><el-tag :type="warningStatusTag(row)">{{ warningStatusText(row) }}</el-tag></template></el-table-column>
        <el-table-column label="操作" width="90" fixed="right" align="center"><template #default="{ row }"><el-button link type="primary" @click.stop="openDetail(row)">查看详情</el-button></template></el-table-column>
      </el-table>
      <el-pagination v-if="total" v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagination" @current-change="loadPage" @size-change="handleSizeChange" />
    </el-card>
    <WarningDetailDrawer v-model="detailVisible" :row="selectedRow" />
  </div>
</template>

<script setup name="WarningTodayOverview">
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue'
import { getWarningTodayOverview, pageWarningTodayOverview } from '@/api/warning/dashboard'
import { warningTypeLabels } from '../lstatistics/statisticsShared'
import WarningDetailDrawer from './WarningDetailDrawer.vue'
import { dashboardData, formatDashboardTime, pageRecords, pageTotal, warningStatusTag, warningStatusText, warningTypeText } from './dashboardShared'

const loading = ref(false); const tableLoading = ref(false); const errorMessage = ref(''); const activeTab = ref('unresolved'); const keyword = ref(''); const warningType = ref(''); const warningLevel = ref(''); const pageNum = ref(1); const pageSize = ref(10); const detailVisible = ref(false); const selectedRow = ref(null); const rows = ref([]); const total = ref(0)
const stats = ref({ todayTotal: 0, unresolvedCount: 0, resolvedCount: 0 })
const unresolvedCount = computed(() => Number(stats.value.unresolvedCount || 0))
const resolvedCount = computed(() => Number(stats.value.resolvedCount || 0))
const totalCount = computed(() => Number(stats.value.todayTotal || 0))
const typeOptions = Object.entries(warningTypeLabels).filter(([value]) => ['WATER_PIPE', 'SEWER_PIPE', 'GAS_PIPE', 'MANHOLE'].includes(value)).map(([value, label]) => ({ value, label }))
const levelOptions = [{ value: '1', label: '蓝色（IV级）' }, { value: '2', label: '黄色（III级）' }, { value: '3', label: '橙色（II级）' }, { value: '4', label: '红色（I级）' }]
const tabTitle = computed(() => ({ unresolved: '仍未解除预警', resolved: '今日已解除预警', all: '今日全部预警' }[activeTab.value]))
function resetPage() { pageNum.value = 1; loadPage() }
function handleSizeChange() { pageNum.value = 1; loadPage() }
function selectTab(tab) { if (activeTab.value !== tab) { activeTab.value = tab; resetPage() } else { resetPage() } }
function openDetail(row) { selectedRow.value = row; detailVisible.value = true }
async function loadPage() { tableLoading.value = true; errorMessage.value = ''; try { const response = await pageWarningTodayOverview({ category: activeTab.value, pageNum: pageNum.value, pageSize: pageSize.value, warningType: warningType.value || undefined, warningLevel: warningLevel.value || undefined, keyword: keyword.value.trim() || undefined }); rows.value = pageRecords(response); total.value = pageTotal(response) } catch (error) { rows.value = []; total.value = 0; errorMessage.value = error?.message || '今日预警明细加载失败'; ElMessage.error(errorMessage.value) } finally { tableLoading.value = false } }
async function loadData() { loading.value = true; errorMessage.value = ''; try { stats.value = { ...stats.value, ...dashboardData(await getWarningTodayOverview(), {}) }; await loadPage() } catch (error) { errorMessage.value = error?.message || '今日预警概况加载失败，请稍后重试'; ElMessage.error(errorMessage.value) } finally { loading.value = false } }
onMounted(loadData)
</script>

<style scoped lang="scss">
.overview-page{min-height:calc(100vh - 84px);padding:22px;background:#f4f7fb;color:#172b4d}.page-head{display:flex;justify-content:space-between;align-items:flex-end;gap:18px;margin-bottom:20px}.eyebrow{color:#dc2626;font-size:11px;font-weight:700;letter-spacing:2px}.page-head h1{margin:6px 0 4px;font-size:26px;line-height:1.25}.page-head p{margin:0;color:#718096}.error-alert{margin-bottom:16px}.metric-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-bottom:18px}.metric-card{min-height:138px;padding:20px 22px;border:1px solid #e6ebf2;border-radius:8px;background:#fff;color:#172b4d;text-align:left;cursor:pointer;transition:.2s}.metric-card:hover,.metric-card.active{border-color:#2563eb;box-shadow:0 8px 22px rgba(37,99,235,.12);transform:translateY(-1px)}.metric-card.danger{border-top:3px solid #dc2626}.metric-card.success{border-top:3px solid #059669}.metric-card.primary{border-top:3px solid #2563eb}.metric-label{display:block;color:#718096;font-size:14px}.metric-card strong{display:block;margin:9px 0 7px;font-size:35px;line-height:1}.metric-card small{color:#94a3b8;font-size:12px}.table-card{border-radius:8px}.card-title{display:flex;justify-content:space-between;align-items:center;gap:16px;font-weight:650}.card-title>div:first-child{display:flex;align-items:baseline;gap:10px}.card-title em{color:#94a3b8;font-size:12px;font-style:normal;font-weight:400}.filters{display:flex;align-items:center;gap:8px}.filters .el-select{width:150px}.search-input{width:230px}.pagination{justify-content:flex-end;margin-top:16px}@media(max-width:980px){.card-title{align-items:flex-start;flex-direction:column}.filters{width:100%;flex-wrap:wrap}}@media(max-width:760px){.page-head{align-items:flex-start;flex-direction:column}.metric-grid{grid-template-columns:1fr}.filters .el-select,.search-input{width:100%}}
</style>
