<template>
  <div class="bjtx-page">
    <!-- 顶部栏 -->
    <div class="top-bar">
      <div class="top-left">
        <h2 class="page-title">实时报警提醒</h2>
        <span class="current-time">{{ currentTime }}</span>
      </div>
      <div class="top-right">
        <div class="alarm-stats">
          <span class="stat-item">今日报警 <em class="stat-num">{{ alarmList.length }}</em> 条</span>
          <span class="stat-divider">/</span>
          <span class="stat-item">未处理 <em class="stat-num warn">{{ unHandledCount }}</em> 条</span>
        </div>
        <div class="sound-toggle" :class="{ active: soundOn }" @click="soundOn = !soundOn">
          <el-icon :size="20"><component :is="soundOn ? 'Bell' : 'Mute'" /></el-icon>
        </div>
      </div>
    </div>

    <!-- 滚动报警列表 -->
    <div class="alarm-scroll-wrapper" ref="scrollWrapper">
      <div class="alarm-scroll-inner" :style="{ transform: `translateY(${scrollOffset}px)` }">
        <div
          v-for="item in alarmList"
          :key="item.id"
          class="alarm-card"
          :class="'level-' + item.alarmLevelText"
        >
          <div class="card-left">
            <span class="level-icon" :class="'icon-' + item.alarmLevelText">
              {{ item.alarmLevelText === '最高' ? '!!' : item.alarmLevelText === '高' ? '!' : 'i' }}
            </span>
          </div>
          <div class="card-body">
            <div class="card-row row-1">
              <span class="alarm-time">{{ item.alarmTime || '-' }}</span>
              <span class="alarm-level-tag" :class="'tag-' + item.alarmLevelText">{{ item.alarmLevelText }}</span>
            </div>
            <div class="card-row row-2">
              <span class="device-name">{{ item.deviceName || '-' }}</span>
              <span class="device-code">{{ item.deviceCode || '' }}</span>
            </div>
            <div class="card-row row-3">
              <span class="alarm-metric">预警类型: {{ item.warningType || '-' }} | 实际值: {{ item.actualValue ?? '-' }}</span>
            </div>
            <div class="card-row row-4">
              <el-icon :size="14"><Location /></el-icon>
              <span class="alarm-location">设备类型: {{ item.deviceType || '-' }} | 状态: {{ item.alarmStatus === 0 ? '未处理' : '已处理' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Bjtx">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Bell, Mute, Location } from '@element-plus/icons-vue'
import { getAlarmDataPage } from '@/api/drainage'
import useUserStore from '@/store/modules/user'

// ==================== 用户信息 ====================
const userStore = useUserStore()
const isAdmin = computed(() => userStore.roles && userStore.roles.includes('admin'))

// ==================== 时钟 ====================
const currentTime = ref('')
let clockTimer = null

function updateClock() {
  const now = new Date()
  const y = now.getFullYear()
  const M = String(now.getMonth() + 1).padStart(2, '0')
  const d = String(now.getDate()).padStart(2, '0')
  const h = String(now.getHours()).padStart(2, '0')
  const m = String(now.getMinutes()).padStart(2, '0')
  const s = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${y}-${M}-${d} ${h}:${m}:${s}`
}

// ==================== 声音开关 ====================
const soundOn = ref(true)

// ==================== 等级映射 ====================
const alarmLevelMap = { 1: '最高', 2: '高', 3: '中', 4: '低' }

// ==================== 报警数据 ====================
const alarmList = ref([])

async function loadAlarms() {
  try {
    const res = await getAlarmDataPage(1, 200, { equipmentType: 'drainage' })
    const pageData = res.code !== undefined ? res.data : res
    const records = pageData.records || pageData.rows || []

    alarmList.value = records.map(row => ({
      ...row,
      alarmLevelText: alarmLevelMap[row.alarmLevel] || '-'
    }))
  } catch (error) {
    console.error('加载报警数据失败', error)
  }
}

const unHandledCount = computed(() => alarmList.value.filter(a => a.alarmStatus === 0).length)

// ==================== 自动滚动 ====================
const scrollWrapper = ref(null)
const scrollOffset = ref(0)
let scrollTimer = null
let pollTimer = null
const CARD_HEIGHT = 128 // 卡片高度 + 间距
let scrollPaused = false

function startScroll() {
  scrollTimer = setInterval(() => {
    if (scrollPaused || alarmList.value.length === 0) return
    scrollOffset.value -= 1
    // 每滚动一个卡片高度，将第一条数据移到末尾
    if (Math.abs(scrollOffset.value) >= CARD_HEIGHT) {
      const first = alarmList.value.shift()
      if (first) alarmList.value.push(first)
      scrollOffset.value = 0
    }
  }, 30)
}

// ==================== 生命周期 ====================
onMounted(() => {
  updateClock()
  clockTimer = setInterval(updateClock, 1000)
  loadAlarms()
  startScroll()
  // 30秒轮询刷新
  pollTimer = setInterval(loadAlarms, 30000)

  // 鼠标悬停暂停滚动
  const wrapper = scrollWrapper.value
  if (wrapper) {
    wrapper.addEventListener('mouseenter', () => { scrollPaused = true })
    wrapper.addEventListener('mouseleave', () => { scrollPaused = false })
  }
})

onUnmounted(() => {
  if (clockTimer) clearInterval(clockTimer)
  if (scrollTimer) clearInterval(scrollTimer)
  if (pollTimer) clearInterval(pollTimer)
})
</script>

<style scoped>
.bjtx-page {
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 84px);
  background: linear-gradient(180deg, #0a1628 0%, #0d2137 50%, #0a1628 100%);
  display: flex;
  flex-direction: column;
  color: #e0e6ed;
  overflow: hidden;
}

/* 顶部栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 28px;
  background: rgba(10, 30, 60, 0.85);
  border-bottom: 1px solid rgba(64, 158, 255, 0.25);
  flex-shrink: 0;
}

.top-left {
  display: flex;
  align-items: baseline;
  gap: 18px;
}

.page-title {
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 2px;
  margin: 0;
  background: linear-gradient(90deg, #409eff, #67c8ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.current-time {
  font-size: 14px;
  color: #8bb8e8;
  font-family: 'Courier New', monospace;
}

.top-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.alarm-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #a0c4e8;
}

.stat-num {
  font-style: normal;
  font-weight: 700;
  font-size: 18px;
  color: #409eff;
}

.stat-num.warn {
  color: #e6a23c;
}

.stat-divider {
  color: #3a5a7a;
}

.sound-toggle {
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(64, 158, 255, 0.3);
  color: #606266;
  transition: all 0.3s;
}

.sound-toggle.active {
  color: #409eff;
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.12);
}

/* 滚动列表 */
.alarm-scroll-wrapper {
  flex: 1;
  overflow: hidden;
  padding: 16px 28px;
}

.alarm-scroll-inner {
  transition: none;
}

/* 报警卡片 */
.alarm-card {
  display: flex;
  align-items: stretch;
  background: rgba(12, 30, 55, 0.85);
  border: 1px solid rgba(64, 158, 255, 0.15);
  border-radius: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  transition: border-color 0.3s;
  height: 118px;
}

.alarm-card:hover {
  border-color: rgba(64, 158, 255, 0.45);
}

.alarm-card.level-最高 {
  border-left: 4px solid #f56c6c;
}

.alarm-card.level-高 {
  border-left: 4px solid #e6a23c;
}

.alarm-card.level-中 {
  border-left: 4px solid #409eff;
}

.alarm-card.level-低 {
  border-left: 4px solid #67c238;
}

.card-left {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  flex-shrink: 0;
}

.level-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 800;
  color: #fff;
}

.level-icon.icon-最高 {
  background: radial-gradient(circle, #f56c6c, #c45656);
  box-shadow: 0 0 12px rgba(245, 108, 108, 0.5);
  animation: pulse-red 1.5s infinite;
}

.level-icon.icon-高 {
  background: radial-gradient(circle, #e6a23c, #c88630);
  box-shadow: 0 0 10px rgba(230, 162, 60, 0.4);
}

.level-icon.icon-中 {
  background: radial-gradient(circle, #409eff, #2d7dd2);
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.level-icon.icon-低 {
  background: radial-gradient(circle, #67c238, #4e9a2e);
  box-shadow: 0 0 8px rgba(103, 194, 56, 0.3);
}

@keyframes pulse-red {
  0%, 100% { box-shadow: 0 0 12px rgba(245, 108, 108, 0.5); }
  50% { box-shadow: 0 0 24px rgba(245, 108, 108, 0.8); }
}

.card-body {
  flex: 1;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 6px;
}

.card-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.row-1 {
  justify-content: space-between;
}

.alarm-time {
  font-size: 12px;
  color: #6a8da8;
  font-family: 'Courier New', monospace;
}

.alarm-level-tag {
  font-size: 11px;
  padding: 1px 10px;
  border-radius: 10px;
  font-weight: 600;
}

.tag-最高 {
  background: rgba(245, 108, 108, 0.18);
  color: #f56c6c;
  border: 1px solid rgba(245, 108, 108, 0.4);
}

.tag-高 {
  background: rgba(230, 162, 60, 0.18);
  color: #e6a23c;
  border: 1px solid rgba(230, 162, 60, 0.4);
}

.tag-中 {
  background: rgba(64, 158, 255, 0.18);
  color: #409eff;
  border: 1px solid rgba(64, 158, 255, 0.4);
}

.tag-低 {
  background: rgba(103, 194, 56, 0.18);
  color: #67c238;
  border: 1px solid rgba(103, 194, 56, 0.4);
}

.device-name {
  font-size: 15px;
  font-weight: 600;
  color: #dce8f0;
}

.device-code {
  font-size: 12px;
  color: #6a8da8;
  margin-left: 8px;
}

.alarm-metric {
  font-size: 13px;
  color: #e6a23c;
  font-weight: 500;
}

.alarm-location {
  font-size: 12px;
  color: #6a8da8;
}
</style>
