<template>
  <div class="led-debug">
    <a-row :gutter="[24, 24]">
      <a-col :xs="24" :lg="10">
        <a-card title="LED 控制面板">
          <a-form layout="vertical">
            <a-form-item label="选择终端">
              <a-select
                v-model:value="selectedDevice"
                placeholder="请选择终端"
                style="width: 100%"
              >
                <a-select-option
                  v-for="t in terminals"
                  :key="t.address"
                  :value="t.address"
                >
                  地址 {{ t.address }} ({{ t.uid_readable || t.uid }})
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="选择 LED">
              <a-select
                v-model:value="selectedLed"
                style="width: 100%"
              >
                <a-select-option :value="0">全部 24 灯</a-select-option>
                <a-select-option v-for="n in 24" :key="n" :value="n">LED {{ n }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="操作">
              <a-space wrap>
                <a-button
                  danger
                  type="primary"
                  :disabled="!canControl"
                  :loading="loading === 1"
                  @click="setColor(1)"
                >
                  🔴 红灯闪烁
                </a-button>
                <a-button
                  :disabled="!canControl"
                  :loading="loading === 2"
                  style="background:#52c41a;border-color:#52c41a;color:#fff"
                  @click="setColor(2)"
                >
                  🟢 绿灯闪烁
                </a-button>
                <a-button
                  type="primary"
                  :disabled="!canControl"
                  :loading="loading === 3"
                  @click="setColor(3)"
                >
                  🔵 蓝灯闪烁
                </a-button>
                <a-button
                  :disabled="!canControl"
                  :loading="loading === 0"
                  @click="setColor(0)"
                >
                  ⚫ 关闭
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>

          <a-alert
            v-if="feedbackMsg"
            :type="feedbackType"
            :message="feedbackMsg"
            show-icon
            closable
            style="margin-top: 12px"
            @close="feedbackMsg = ''"
          />
        </a-card>

        <a-card title="读卡号" style="margin-top: 16px">
          <a-form layout="vertical">
            <a-form-item label="选择天线 (1-24)">
              <a-space>
                <a-input-number v-model:value="cardAntenna" :min="1" :max="24" style="width: 120px" />
                <a-button type="primary" @click="readCardNumber" :loading="readingCard" :disabled="!canControl">
                  读取卡号
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>

          <div v-if="cardResult" class="card-result">
            <a-descriptions bordered size="small" :column="1">
              <a-descriptions-item label="天线位置">{{ cardResult.antenna }}</a-descriptions-item>
              <a-descriptions-item label="卡号 (HEX)">{{ cardResult.card_number_hex }}</a-descriptions-item>
              <a-descriptions-item label="卡号 (DEC)">{{ cardResult.card_number }}</a-descriptions-item>
              <a-descriptions-item label="卡号 (UID)">{{ cardResult.uid }}</a-descriptions-item>
              <a-descriptions-item label="卡号字符串">{{ cardResult.card_number_str }}</a-descriptions-item>
              <a-descriptions-item label="原始数据">{{ cardResult.raw_data }}</a-descriptions-item>
            </a-descriptions>
          </div>
          <a-empty v-else-if="!readingCard" description="点击「读取卡号」查看结果" />
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="14">
        <a-card title="24 路 LED 实时状态">
          <a-alert
            v-if="!dataStore.serialConnected"
            message="串口未连接"
            type="warning"
            show-icon
            style="margin-bottom: 16px"
          />
          <div class="led-grid">
            <div
              v-for="n in 24"
              :key="n"
              class="led-cell"
              :class="{ active: selectedLed === n || selectedLed === 0 }"
              @click="selectedLed = n; cardAntenna = n"
            >
              <div
                class="led-dot"
                :style="{ background: ledColors[ledStates[n] ?? 0] }"
                :title="`LED ${n}: ${statusText[ledStates[n] ?? 0]}`"
              >
                <span class="led-label">{{ n }}</span>
              </div>
            </div>
          </div>
          <div class="legend">
            <span v-for="(c, i) in ['关闭','红色闪烁','绿色闪烁','蓝色闪烁']" :key="i" class="legend-item">
              <span class="legend-dot" :style="{ background: ledColors[i] }"></span> {{ c }}
            </span>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

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

const dataStore = useDataStore()

const selectedDevice = ref(undefined)
const selectedLed = ref(1)
const terminals = ref([])
const loading = ref(-1)
const discovering = ref(false)
const feedbackMsg = ref('')
const feedbackType = ref('success')
const ledStates = ref({})
const cardAntenna = ref(1)
const readingCard = ref(false)
const cardResult = ref(null)
let pollTimer = null

const ledColors = { 0: '#d9d9d9', 1: '#ff4d4f', 2: '#52c41a', 3: '#1890ff' }
const statusText = { 0: '关闭', 1: '红色闪烁', 2: '绿色闪烁', 3: '蓝色闪烁' }
const colorNames = { 0: '关闭', 1: '红灯闪烁', 2: '绿灯闪烁', 3: '蓝灯闪烁' }

const canControl = computed(() => terminals.value.length > 0)

async function setColor(color) {
  loading.value = color
  feedbackMsg.value = ''
  const params = { device_address: selectedDevice.value, color }
  try {
    let res
    if (selectedLed.value === 0) {
      res = await apiService.modbus.setAllLeds(params)
    } else {
      res = await apiService.modbus.setRgbLed({ ...params, led_number: selectedLed.value })
    }
    if (res.data.success) {
      const target = selectedLed.value === 0 ? '全部灯' : `LED ${selectedLed.value}`
      feedbackMsg.value = `${target} → ${colorNames[color]}`
      feedbackType.value = 'success'
      // update local state
      if (selectedLed.value === 0) {
        for (let i = 1; i <= 24; i++) ledStates.value[i] = color
      } else {
        ledStates.value[selectedLed.value] = color
      }
      // force reactivity
      ledStates.value = { ...ledStates.value }
    } else {
      feedbackMsg.value = res.data.message || '失败'
      feedbackType.value = 'error'
    }
  } catch (e) {
    feedbackMsg.value = '错误: ' + (e.response?.data?.message || e.message)
    feedbackType.value = 'error'
  } finally {
    loading.value = -1
    setTimeout(() => { feedbackMsg.value = '' }, 3000)
  }
}

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
      }))
      if (terminals.value.length) selectedDevice.value = terminals.value[0].address
    }
  } finally {
    discovering.value = false
  }
}

async function loadTerminals() {
  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
      }))
      if (terminals.value.length) {
        selectedDevice.value = terminals.value[0].address
      }
    }
  } catch (e) { console.error(e) }
}

async function readCardNumber() {
  readingCard.value = true
  cardResult.value = null
  try {
    const res = await apiService.modbus.readAntenna({
      device_address: selectedDevice.value,
      antenna: cardAntenna.value
    })
    if (res.data.success && res.data.data) {
      cardResult.value = res.data.data
    } else {
      feedbackMsg.value = '读卡失败: ' + (res.data.message || '未知错误')
      feedbackType.value = 'error'
    }
  } catch (e) {
    feedbackMsg.value = '读卡错误: ' + (e.response?.data?.message || e.message)
    feedbackType.value = 'error'
  } finally {
    readingCard.value = false
    setTimeout(() => { if (!cardResult.value) feedbackMsg.value = '' }, 3000)
  }
}

async function refreshStatus() {
  try {
    const ledRes = await apiService.modbus.getLedStatus()
    if (ledRes.data.success && ledRes.data.leds) ledStates.value = { ...ledRes.data.leds }
  } catch (e) { /* ignore */ }
}

onMounted(() => {
  loadTerminals()
  refreshStatus()
  pollTimer = setInterval(refreshStatus, 3000)
})

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

<style scoped>
.led-debug {
  width: 100%;
}
.led-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 12px;
}
@media (max-width: 768px) {
  .led-grid { grid-template-columns: repeat(4, 1fr); }
}
@media (max-width: 480px) {
  .led-grid { grid-template-columns: repeat(2, 1fr); }
}
.led-cell {
  display: flex;
  justify-content: center;
  cursor: pointer;
  padding: 4px;
  border-radius: 12px;
  transition: box-shadow 0.2s;
}
.led-cell.active {
  box-shadow: 0 0 0 3px #1890ff;
}
.led-dot {
  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 0.3s;
}
.led-dot:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.led-label {
  font-size: 18px;
  font-weight: 700;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.legend {
  display: flex;
  gap: 20px;
  margin-top: 16px;
  flex-wrap: wrap;
  font-size: 13px;
  color: #666;
}
.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
}
.legend-dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 1px solid rgba(0,0,0,0.1);
}
</style>
