<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Check, CircleCheck } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/userStore'
import { useIotMonitoringStore } from '../stores/iotMonitoringStore'
import { formatDateTime } from '../utils/dateTimeFormatter'
import SidebarMenu from '../components/SidebarMenu.vue'
import BreadcrumbNav from '../components/BreadcrumbNav.vue'
import HudPageHero from '../components/shell/HudPageHero.vue'

const router = useRouter()
const { userInfo, getUserInfo } = useUserStore()
const iot = useIotMonitoringStore()

const tableData = ref([])
const detailVisible = ref(false)
const currentAlert = ref(null)
const searchForm = ref({ keyword: '', status: '', level: '', sensor_id: null })

const levelLabel = { info: '提示', warning: '预警', critical: '严重' }
const levelType = { info: 'info', warning: 'warning', critical: 'danger' }
const statusLabel = { open: '待处理', acknowledged: '已确认', resolved: '已关闭' }
const statusType = { open: 'danger', acknowledged: 'warning', resolved: 'success' }

const refreshList = () => {
  tableData.value = iot.listAlerts(searchForm.value)
}

const resetSearch = () => {
  searchForm.value = { keyword: '', status: '', level: '', sensor_id: null }
  refreshList()
}

const showDetail = (row) => {
  currentAlert.value = row
  detailVisible.value = true
}

const handleAck = (row) => {
  const { ok, message } = iot.acknowledgeAlert(row.alert_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('预警已确认')
  refreshList()
  if (detailVisible.value && currentAlert.value?.alert_id === row.alert_id) {
    currentAlert.value = iot.listAlerts().find((a) => a.alert_id === row.alert_id)
  }
}

const handleResolve = (row) => {
  const { ok, message } = iot.resolveAlert(row.alert_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('预警已关闭')
  refreshList()
  detailVisible.value = false
}

const fmtTime = (v) => (v ? formatDateTime(v) : '—')

onMounted(() => {
  getUserInfo().then(() => {
    if (!userInfo.value) router.push('/login')
    else refreshList()
  })
})
</script>

<template>
  <div class="iot-page shell-layout-root">
    <div class="main-container">
      <div class="sidebar"><SidebarMenu /></div>
      <div class="content-area">
        <BreadcrumbNav />
        <HudPageHero
          title="预警管理"
          description="汇聚传感器离线、阈值越限、采集失败等事件；支持确认、关闭与关联设备追溯。"
        />

        <el-row :gutter="12" class="stat-row">
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num stat-warn">{{ iot.openAlertCount }}</div>
              <div class="stat-label">待处理</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num">
                {{ tableData.filter((a) => a.status === 'acknowledged').length }}
              </div>
              <div class="stat-label">已确认</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num stat-success">
                {{ tableData.filter((a) => a.status === 'resolved').length }}
              </div>
              <div class="stat-label">已关闭</div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>预警列表</h2>
              <el-button @click="refreshList"><el-icon><Refresh /></el-icon> 刷新</el-button>
            </div>
          </template>

          <el-form :model="searchForm" inline class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="标题/内容/传感器" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="级别">
              <el-select v-model="searchForm.level" placeholder="全部" clearable style="width: 110px">
                <el-option v-for="(label, key) in levelLabel" :key="key" :label="label" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 110px">
                <el-option v-for="(label, key) in statusLabel" :key="key" :label="label" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="传感器">
              <el-select v-model="searchForm.sensor_id" placeholder="全部" clearable style="width: 180px">
                <el-option
                  v-for="s in iot.sensors.value"
                  :key="s.sensor_id"
                  :label="s.name"
                  :value="s.sensor_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="refreshList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="tableData" style="width: 100%" @row-click="showDetail">
            <el-table-column prop="alert_id" label="ID" width="60" />
            <el-table-column label="级别" width="80">
              <template #default="{ row }">
                <el-tag :type="levelType[row.level]" size="small">{{ levelLabel[row.level] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="标题" min-width="140" show-overflow-tooltip />
            <el-table-column prop="sensor_name" label="关联传感器" width="130" show-overflow-tooltip />
            <el-table-column prop="message" label="详情" min-width="200" show-overflow-tooltip />
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="statusType[row.status]" size="small">{{ statusLabel[row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="触发值" width="90">
              <template #default="{ row }">{{ row.trigger_value ?? '—' }}</template>
            </el-table-column>
            <el-table-column label="创建时间" width="165">
              <template #default="{ row }">{{ fmtTime(row.created_at) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right" @click.stop>
              <template #default="{ row }">
                <el-button link type="primary" @click.stop="showDetail(row)">详情</el-button>
                <el-button
                  v-if="row.status === 'open'"
                  link
                  type="warning"
                  @click.stop="handleAck(row)"
                >
                  <el-icon><Check /></el-icon> 确认
                </el-button>
                <el-button
                  v-if="row.status !== 'resolved'"
                  link
                  type="success"
                  @click.stop="handleResolve(row)"
                >
                  <el-icon><CircleCheck /></el-icon> 关闭
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="detailVisible" title="预警详情" width="520px">
      <template v-if="currentAlert">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="级别">
            <el-tag :type="levelType[currentAlert.level]">{{ levelLabel[currentAlert.level] }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标题">{{ currentAlert.title }}</el-descriptions-item>
          <el-descriptions-item label="传感器">
            {{ currentAlert.sensor_code }} · {{ currentAlert.sensor_name }}
          </el-descriptions-item>
          <el-descriptions-item label="说明">{{ currentAlert.message }}</el-descriptions-item>
          <el-descriptions-item label="触发值 / 阈值">
            {{ currentAlert.trigger_value ?? '—' }} / {{ currentAlert.threshold_value ?? '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType[currentAlert.status]">{{ statusLabel[currentAlert.status] }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建">{{ fmtTime(currentAlert.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="确认">{{ fmtTime(currentAlert.acknowledged_at) }}</el-descriptions-item>
          <el-descriptions-item label="关闭">{{ fmtTime(currentAlert.resolved_at) }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          v-if="currentAlert?.status === 'open'"
          type="warning"
          @click="handleAck(currentAlert)"
        >
          确认
        </el-button>
        <el-button
          v-if="currentAlert?.status !== 'resolved'"
          type="success"
          @click="handleResolve(currentAlert)"
        >
          关闭预警
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
.iot-page :deep(.el-table__row) {
  cursor: pointer;
}
</style>
