<template>
  <div class="warning-page">
    <section class="hero-panel">
      <div>
        <div class="eyebrow">EARLY WARNING DIRECTORY</div>
        <h1>事项信息查询</h1>
        <p>面向城市生命线预警清单的组合检索与信息浏览，快速定位专项、等级和状态配置。</p>
      </div>
      <div class="hero-decoration">
        <el-icon><Search /></el-icon>
      </div>
    </section>

    <section class="metric-grid">
      <article v-for="item in metrics" :key="item.key" class="metric-card" :class="`metric-${item.key}`">
        <div class="metric-icon"><el-icon><component :is="item.icon" /></el-icon></div>
        <div>
          <span>{{ item.label }}</span>
          <strong>{{ item.value }}</strong>
        </div>
      </article>
    </section>

    <el-card class="filter-card" shadow="never">
      <el-form ref="queryRef" :model="query" :inline="true" label-position="top">
        <el-form-item label="事项编号">
          <el-input v-model="query.itemCode" placeholder="输入完整或部分编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="事项名称">
          <el-input v-model="query.itemName" placeholder="输入事项名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="预警专项">
          <el-input v-model="query.warningSpecial" placeholder="如：城市内涝" clearable />
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select v-model="query.warningType" placeholder="全部类型" clearable>
            <el-option v-for="item in warningTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别">
          <el-select v-model="query.warningLevel" placeholder="全部级别" clearable>
            <el-option v-for="item in warningLevels" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="事项状态">
          <el-select v-model="query.status" placeholder="全部状态" clearable>
            <el-option v-for="item in itemStatuses" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="filter-actions">
          <el-button type="primary" :icon="Search" @click="handleQuery">组合查询</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置条件</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-title-row">
          <div>
            <h2>预警事项清单</h2>
            <span>共检索到 {{ total }} 条事项信息</span>
          </div>
          <el-button :icon="RefreshRight" circle @click="loadData" />
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" class="warning-table" row-key="itemId">
        <el-table-column label="事项编号" prop="itemCode" min-width="210">
          <template #default="{ row }">
            <button class="code-link" @click="openDetail(row)">{{ row.itemCode }}</button>
          </template>
        </el-table-column>
        <el-table-column label="事项名称" prop="itemName" min-width="200" show-overflow-tooltip />
        <el-table-column label="预警专项" prop="warningSpecial" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">{{ row.warningSpecial || '通用专项' }}</template>
        </el-table-column>
        <el-table-column label="类型" prop="warningType" min-width="150">
          <template #default="{ row }">{{ typeLabel(row.warningType) }}</template>
        </el-table-column>
        <el-table-column label="级别" prop="warningLevel" width="130">
          <template #default="{ row }">
            <span class="level-pill" :style="{ '--level-color': levelMeta(row.warningLevel).color }">
              {{ levelMeta(row.warningLevel).shortLabel }}预警
            </span>
          </template>
        </el-table-column>
        <el-table-column label="所属行业" prop="industry" width="110">
          <template #default="{ row }">{{ row.industry || '-' }}</template>
        </el-table-column>
        <el-table-column label="时长" prop="duration" width="90">
          <template #default="{ row }">{{ row.duration ? `${row.duration}h` : '-' }}</template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="{ row }">
            <el-tag :type="statusMeta(row.status).type" effect="light">{{ statusMeta(row.status).label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" min-width="170">
          <template #default="{ row }">{{ row.updateTime || row.createTime || '-' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" :icon="View" @click="openDetail(row)">浏览</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="!loading && !tableData.length" description="没有找到符合条件的预警事项" />
      <pagination
        v-show="total > 0"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="total"
        @pagination="loadData"
      />
    </el-card>

    <el-drawer v-model="detailVisible" size="560px" class="detail-drawer" destroy-on-close>
      <template #header>
        <div class="drawer-heading">
          <span>事项信息浏览</span>
          <small>{{ detail.itemCode }}</small>
        </div>
      </template>
      <div v-loading="detailLoading" class="detail-body">
        <div class="detail-banner" :style="{ '--level-color': levelMeta(detail.warningLevel).color }">
          <div>
            <span>{{ typeLabel(detail.warningType) }}</span>
            <h3>{{ detail.itemName }}</h3>
          </div>
          <el-tag :type="statusMeta(detail.status).type">{{ statusMeta(detail.status).label }}</el-tag>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="事项编码" :span="2">{{ detail.itemCode }}</el-descriptions-item>
          <el-descriptions-item label="预警专项">{{ detail.warningSpecial || '-' }}</el-descriptions-item>
          <el-descriptions-item label="所属行业">{{ detail.industry || '-' }}</el-descriptions-item>
          <el-descriptions-item label="预警级别">{{ levelMeta(detail.warningLevel).label }}</el-descriptions-item>
          <el-descriptions-item label="预警时长">{{ detail.duration ? detail.duration + ' 小时' : '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detail.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
        <div class="section-heading">预警环节配置</div>
        <el-timeline v-if="detailLinks.length">
          <el-timeline-item
            v-for="(link, index) in detailLinks"
            :key="index"
            :timestamp="`${link.handler || '待配置'} · ${link.timeLimit || '-'} 分钟`"
            placement="top"
          >
            <div class="timeline-card">
              <strong>{{ link.name }}</strong>
              <p>{{ link.description || '暂无环节说明' }}</p>
            </div>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂未配置预警环节" :image-size="72" />
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button v-if="router.hasRoute('WarningItemDetail')" type="primary" @click="goFullDetail">进入完整详情</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="WarningItemQuery">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { CircleCheck, CircleClose, Collection, Refresh, RefreshRight, Search, View, Warning } from '@element-plus/icons-vue'
import { getDicts } from '@/api/system/dict/data'
import { getWarningItemDetail, listWarningItems } from '@/api/warning/list'
import {
  fallbackWarningTypes,
  itemStatuses,
  levelMeta,
  normalizeWarningTypeDict,
  optionLabel,
  parseLinkConfig,
  statusMeta,
  warningLevels
} from '../shared'

const router = useRouter()
const loading = ref(false)
const detailLoading = ref(false)
const detailVisible = ref(false)
const tableData = ref([])
const total = ref(0)
const warningTypes = ref(fallbackWarningTypes)
const detail = reactive({})
const counters = reactive({ total: 0, enabled: 0, disabled: 0, invalid: 0 })
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  itemCode: '',
  itemName: '',
  warningType: '',
  warningLevel: '',
  warningSpecial: '',
  status: ''
})

const metrics = computed(() => [
  { key: 'total', label: '事项总量', value: counters.total, icon: Collection },
  { key: 'enabled', label: '启用事项', value: counters.enabled, icon: CircleCheck },
  { key: 'disabled', label: '禁用事项', value: counters.disabled, icon: CircleClose },
  { key: 'invalid', label: '作废事项', value: counters.invalid, icon: Warning }
])
const detailLinks = computed(() => parseLinkConfig(detail.linkConfig))

function typeLabel(value) {
  return optionLabel(warningTypes.value, value)
}

async function loadTypes() {
  try {
    const res = await getDicts('warning_type')
    warningTypes.value = normalizeWarningTypeDict(res.data)
  } catch {
    warningTypes.value = fallbackWarningTypes
  }
}

async function loadMetrics() {
  try {
    const [all, enabled, disabled, invalid] = await Promise.all([
      listWarningItems({ pageNum: 1, pageSize: 1 }),
      listWarningItems({ pageNum: 1, pageSize: 1, status: 'ENABLED' }),
      listWarningItems({ pageNum: 1, pageSize: 1, status: 'DISABLED' }),
      listWarningItems({ pageNum: 1, pageSize: 1, status: 'INVALID' })
    ])
    counters.total = Number(all.data?.total || 0)
    counters.enabled = Number(enabled.data?.total || 0)
    counters.disabled = Number(disabled.data?.total || 0)
    counters.invalid = Number(invalid.data?.total || 0)
  } catch {
    Object.assign(counters, { total: 0, enabled: 0, disabled: 0, invalid: 0 })
  }
}

async function loadData() {
  loading.value = true
  try {
    const res = await listWarningItems(query)
    tableData.value = res.data?.records || []
    total.value = Number(res.data?.total || 0)
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  query.pageNum = 1
  loadData()
}

function handleReset() {
  Object.assign(query, {
    pageNum: 1,
    pageSize: 10,
    itemCode: '',
    itemName: '',
    warningType: '',
    warningLevel: '',
    warningSpecial: '',
    status: ''
  })
  loadData()
}

async function openDetail(row) {
  detailVisible.value = true
  detailLoading.value = true
  try {
    const res = await getWarningItemDetail(row.itemId)
    Object.keys(detail).forEach(key => delete detail[key])
    Object.assign(detail, res.data || row)
  } finally {
    detailLoading.value = false
  }
}

function goFullDetail() {
  detailVisible.value = false
  router.push({ name: 'WarningItemDetail', query: { code: detail.itemCode } })
}

onMounted(async () => {
  await loadTypes()
  await Promise.all([loadData(), loadMetrics()])
})
</script>

<style scoped lang="scss">
.warning-page {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background:
    radial-gradient(circle at 85% 0%, rgba(37, 99, 235, .09), transparent 25%),
    #f4f7fb;
}

.hero-panel {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
  padding: 28px 32px;
  color: #fff;
  border-radius: 18px;
  background: linear-gradient(120deg, #0f2f64 0%, #1552a1 54%, #1686b8 100%);
  box-shadow: 0 18px 45px rgba(20, 66, 130, .22);

  &::after {
    position: absolute;
    right: -50px;
    bottom: -100px;
    width: 260px;
    height: 260px;
    content: '';
    border: 42px solid rgba(255, 255, 255, .07);
    border-radius: 50%;
  }

  h1 { margin: 4px 0 8px; font-size: 28px; letter-spacing: 1px; }
  p { margin: 0; color: rgba(255, 255, 255, .76); }
}

.eyebrow { font-size: 11px; letter-spacing: 3px; color: #8fe2ff; }
.hero-decoration {
  z-index: 1;
  display: grid;
  width: 76px;
  height: 76px;
  font-size: 34px;
  border: 1px solid rgba(255, 255, 255, .25);
  border-radius: 22px;
  background: rgba(255, 255, 255, .12);
  place-items: center;
  backdrop-filter: blur(8px);
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
  margin: 18px 0;
}
.metric-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px;
  border: 1px solid #e7edf5;
  border-radius: 14px;
  background: rgba(255, 255, 255, .96);
  box-shadow: 0 8px 24px rgba(31, 56, 88, .06);

  span { display: block; margin-bottom: 5px; color: #718096; font-size: 13px; }
  strong { color: #172b4d; font-size: 26px; }
}
.metric-icon {
  display: grid;
  width: 46px;
  height: 46px;
  color: #2563eb;
  font-size: 22px;
  border-radius: 13px;
  background: #eaf1ff;
  place-items: center;
}
.metric-enabled .metric-icon { color: #059669; background: #e8f8f1; }
.metric-disabled .metric-icon { color: #64748b; background: #eef2f6; }
.metric-invalid .metric-icon { color: #dc2626; background: #fff0f0; }

.filter-card, .content-card {
  border: 1px solid #e5ebf3;
  border-radius: 16px;
}
.filter-card { margin-bottom: 16px; }
.filter-card :deep(.el-form) {
  display: grid;
  grid-template-columns: repeat(6, minmax(150px, 1fr));
  gap: 4px 14px;
}
.filter-card :deep(.el-form-item) { margin: 0; }
.filter-card :deep(.el-form-item__content),
.filter-card :deep(.el-select) { width: 100%; }
.filter-actions { align-self: end; }
.filter-actions :deep(.el-form-item__content) { flex-wrap: nowrap; }

.card-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  h2 { margin: 0 0 4px; color: #1e293b; font-size: 17px; }
  span { color: #94a3b8; font-size: 12px; }
}
.warning-table :deep(th.el-table__cell) {
  color: #475569;
  background: #f7f9fc;
}
.code-link {
  padding: 0;
  color: #1d5fd1;
  font: inherit;
  font-weight: 600;
  border: 0;
  background: transparent;
  cursor: pointer;
}
.level-pill {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 9px;
  color: color-mix(in srgb, var(--level-color) 78%, #1f2937);
  font-size: 12px;
  border: 1px solid color-mix(in srgb, var(--level-color) 30%, transparent);
  border-radius: 999px;
  background: color-mix(in srgb, var(--level-color) 10%, #fff);
  &::before { width: 7px; height: 7px; content: ''; border-radius: 50%; background: var(--level-color); }
}
.drawer-heading {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #172b4d;
  font-weight: 700;
  small { color: #8a98ac; font-weight: 400; }
}
.detail-body { padding: 0 4px 20px; }
.detail-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
  padding: 20px;
  border-left: 4px solid var(--level-color);
  border-radius: 12px;
  background: linear-gradient(110deg, color-mix(in srgb, var(--level-color) 10%, #fff), #f8fafc);
  span { color: #64748b; font-size: 12px; }
  h3 { margin: 5px 0 0; color: #1e293b; font-size: 20px; }
}
.section-heading { margin: 24px 0 14px; color: #1e293b; font-weight: 700; }
.timeline-card {
  padding: 12px 14px;
  border: 1px solid #e8edf4;
  border-radius: 10px;
  background: #fff;
  p { margin: 6px 0 0; color: #718096; line-height: 1.6; }
}

@media (max-width: 1200px) {
  .filter-card :deep(.el-form) { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 768px) {
  .warning-page { padding: 12px; }
  .metric-grid { grid-template-columns: repeat(2, 1fr); }
  .filter-card :deep(.el-form) { grid-template-columns: 1fr; }
  .hero-decoration { display: none; }
}
</style>
