<template>
  <div class="real-time-status">
    <a-row :gutter="[24, 24]">
      <!-- 顶部概览 -->
      <a-col :span="24">
        <a-card>
          <div class="overview-bar">
            <div class="overview-item">
              <span class="overview-label">串口状态</span>
              <a-tag :color="dataStore.serialConnected ? 'green' : 'red'">
                {{ dataStore.serialConnected ? '已连接' : '未连接' }}
              </a-tag>
            </div>
            <div class="overview-item">
              <span class="overview-label">终端数量</span>
              <a-tag color="blue">{{ terminalCount }} 个</a-tag>
            </div>
            <div class="overview-item">
              <a-button type="primary" size="small" @click="discoverTerminals" :loading="discovering">
                发现终端
              </a-button>
            </div>
            <div class="overview-item" v-if="lastUpdate">
              <span class="overview-label">更新</span>
              <span class="overview-value">{{ lastUpdate }}</span>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 终端列表 -->
      <a-col :xs="24" :lg="8">
        <a-card title="已发现终端">
          <a-empty v-if="!dataStore.serialConnected" description="串口未连接" />
          <a-empty v-else-if="terminals.length === 0" description="暂无终端" />
          <a-list v-else size="small" :data-source="terminals">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>
                    <span>地址 {{ item.address }}</span>
                  </template>
                  <template #description>
                    <code class="uid-text">{{ item.uid_readable || item.uid }}</code>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>

      <!-- 24 LED 面板 -->
      <a-col :xs="24" :lg="16">
        <a-card title="24 路 LED 状态">
          <div v-if="!dataStore.serialConnected" class="disconnected-overlay">
            <a-alert message="串口未连接，无法获取 LED 状态" type="warning" show-icon />
          </div>
          <div class="led-grid">
            <div
              v-for="led in 24"
              :key="led"
              class="led-cell"
              :title="`LED ${led}: ${ledStatusText[ledStates[led] || 0]}`"
            >
              <div class="led-indicator" :style="{ backgroundColor: ledColors[ledStates[led] || 0] }">
                <span class="led-number">{{ led }}</span>
              </div>
            </div>
          </div>
          <!-- 图例 -->
          <div class="led-legend">
            <div class="legend-item"><span class="dot" :style="{ background: ledColors[0] }"></span> 关闭</div>
            <div class="legend-item"><span class="dot" :style="{ background: ledColors[1] }"></span> 红色闪烁</div>
            <div class="legend-item"><span class="dot" :style="{ background: ledColors[2] }"></span> 绿色闪烁</div>
            <div class="legend-item"><span class="dot" :style="{ background: ledColors[3] }"></span> 蓝色闪烁</div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 串口数据 -->
    <a-row :gutter="[24, 24]" style="margin-top: 24px">
      <a-col :span="24">
        <SerialDataDisplay />
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import apiService from '../api/apiService'
import { useDataStore } from '../stores/dataStore'
import SerialDataDisplay from '../components/SerialDataDisplay.vue'

const dataStore = useDataStore()

const terminals = ref([])
const discovering = ref(false)
const lastUpdate = ref('')
const ledStates = ref({})
const ledColors = {
  0: '#d9d9d9',
  1: '#ff4d4f',
  2: '#52c41a',
  3: '#1890ff'
}
const ledStatusText = {
  0: '关闭',
  1: '红色闪烁',
  2: '绿色闪烁',
  3: '蓝色闪烁'
}

let pollTimer = null

const terminalCount = computed(() => terminals.value.length)

async function discoverTerminals() {
  discovering.value = true
  try {
    const res = await apiService.modbus.broadcastQuery({ timeout: 3 })
    if (res.data.success && res.data.responses) {
      terminals.value = res.data.responses.map((r, i) => ({
        uid: r.uid,
        uid_readable: r.uid_readable,
        address: i + 1
      }))
    }
  } catch (e) {
    console.error('discover error:', e)
  } finally {
    discovering.value = false
    lastUpdate.value = new Date().toLocaleTimeString()
  }
}

async function loadStoredDevices() {
  try {
    const res = await apiService.modbus.getStoredDevices()
    if (res.data.success && res.data.devices) {
      const entries = Object.entries(res.data.devices)
      terminals.value = entries.map(([uid, addr]) => ({
        uid,
        uid_readable: uid.match(/.{1,2}/g)?.join(':') || uid,
        address: addr
      }))
    }
  } catch (e) {
    console.error('load stored devices error:', e)
  }
}

async function pollLedStatus() {
  try {
    const res = await apiService.modbus.getLedStatus()
    if (res.data.success && res.data.leds) {
      ledStates.value = { ...res.data.leds }
    }
  } catch (e) {
    // ignore polling errors
  }
}

onMounted(async () => {
  if (dataStore.serialConnected) {
    await loadStoredDevices()
  }
  await pollLedStatus()
  pollTimer = setInterval(pollLedStatus, 3000)
  if (dataStore.serialConnected) {
    setInterval(loadStoredDevices, 5000)
  }
})

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

<style scoped>
.overview-bar {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}
.overview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.overview-label {
  font-size: 14px;
  color: #666;
}
.overview-value {
  font-size: 14px;
  color: #333;
}
.uid-text {
  font-size: 12px;
  word-break: break-all;
}
.disconnected-overlay {
  margin-bottom: 16px;
}
.led-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 12px;
}
@media (max-width: 768px) {
  .led-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }
}
@media (max-width: 480px) {
  .led-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 6px;
  }
}
.led-cell {
  display: flex;
  justify-content: center;
}
.led-indicator {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  cursor: default;
}
.led-indicator:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}
.led-number {
  font-size: 18px;
  font-weight: 700;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
}
.led-legend {
  display: flex;
  gap: 20px;
  margin-top: 16px;
  flex-wrap: wrap;
}
.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #666;
}
.dot {
  display: inline-block;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
}
</style>
