<template>
  <div class="jumper-status">
    <a-row :gutter="[24, 24]">
      <!-- 顶部控制栏 -->
      <a-col :span="24">
        <a-card>
          <div class="control-bar">
            <div class="control-item">
              <span class="control-label">选择面板:</span>
              <a-select
                v-model:value="selectedPanel"
                style="width: 200px"
                placeholder="请选择面板"
                :options="panelOptions"
                @change="handlePanelChange"
              />
            </div>
            <div class="control-item">
              <a-button
                type="primary"
                @click="queryJumperStatus"
                :loading="loading"
                :disabled="!selectedPanel"
              >
                查询跳线器状态
              </a-button>
            </div>
            <div class="control-item">
              <a-button @click="refreshData" :loading="loading">
                刷新
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 跳线器状态显示 -->
      <a-col :span="24" v-if="jumperData">
        <a-card title="跳线器状态信息">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="面板地址">
              <a-tag color="blue">{{ jumperData.device_address }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="连接状态">
              <a-tag :color="jumperData.connected ? 'green' : 'default'">
                {{ jumperData.connected ? '已连接' : '未连接' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="跳线器ID(高16位)">
              <span class="register-value">{{ jumperData.jumper_id_high }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="跳线器ID(低16位)">
              <span class="register-value">{{ jumperData.jumper_id_low }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="跳线器ID(合并)" :span="2">
              <span class="register-value">{{ jumperData.jumper_id }}</span>
            </a-descriptions-item>
          </a-descriptions>

          <a-divider>原始寄存器数据</a-divider>
          <div class="registers-display">
            <a-tag
              v-for="(value, index) in jumperData.raw_registers"
              :key="index"
              class="register-tag"
            >
              R{{ index }}: 0x{{ toHex(value) }} ({{ value }})
            </a-tag>
          </div>
        </a-card>
      </a-col>

      <!-- 无数据提示 -->
      <a-col :span="24" v-else-if="!loading">
        <a-card>
          <a-empty description="请选择面板并查询跳线器状态">
            <template #image>
              <InboxOutlined style="font-size: 48px; color: #999" />
            </template>
          </a-empty>
        </a-card>
      </a-col>

      <!-- 历史查询记录 -->
      <a-col :span="24">
        <a-card title="查询历史">
          <a-table
            :columns="columns"
            :data-source="historyRecords"
            :pagination="{ pageSize: 10 }"
            row-key="timestamp"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'connected'">
                <a-tag :color="record.connected ? 'green' : 'default'">
                  {{ record.connected ? '已连接' : '未连接' }}
                </a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag :color="record.success ? 'green' : 'red'">
                  {{ record.success ? '成功' : '失败' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import apiService from '../api/apiService'

const loading = ref(false)
const selectedPanel = ref(null)
const panels = ref([])
const jumperData = ref(null)
const historyRecords = ref([])
const pollTimer = ref(null)

const panelOptions = computed(() => {
  return panels.value.map(p => ({
    label: `面板 ${p.panel_id} (地址: ${p.address})`,
    value: p.panel_id
  }))
})

const columns = [
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 180
  },
  {
    title: '面板ID',
    dataIndex: 'panel_id',
    key: 'panel_id',
    width: 100
  },
  {
    title: '设备地址',
    dataIndex: 'device_address',
    key: 'device_address',
    width: 100
  },
  {
    title: '连接状态',
    dataIndex: 'connected',
    key: 'connected',
    width: 100
  },
  {
    title: '跳线器ID',
    dataIndex: 'jumper_id',
    key: 'jumper_id',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  }
]

function toHex(value) {
  if (value === null || value === undefined) return '0'
  return (value >>> 0).toString(16).toUpperCase().padStart(4, '0')
}

async function loadPanels() {
  try {
    const res = await apiService.panel.getStatus()
    if (res.data.success) {
      panels.value = Object.values(res.data.panels || {})
    }
  } catch (e) {
    console.error('load panels error:', e)
  }
}

async function queryJumperStatus() {
  if (!selectedPanel.value) {
    message.warning('请选择面板')
    return
  }

  loading.value = true
  try {
    const command = {
      command: 'QUERY_JUMPER_STATUS',
      target: selectedPanel.value
    }
    const res = await apiService.dtu.sendControl(command)

    if (res.data.success && res.data.payload?.result) {
      jumperData.value = res.data.payload.result
      message.success('查询成功')

      // 添加到历史记录
      historyRecords.value.unshift({
        timestamp: new Date().toLocaleString(),
        panel_id: selectedPanel.value,
        device_address: jumperData.value.device_address,
        connected: jumperData.value.connected,
        jumper_id: jumperData.value.jumper_id,
        success: res.data.payload.success
      })

      // 限制历史记录数量
      if (historyRecords.value.length > 50) {
        historyRecords.value = historyRecords.value.slice(0, 50)
      }
    } else {
      message.error(res.data.payload?.result?.message || '查询失败')
    }
  } catch (e) {
    console.error('query jumper status error:', e)
    message.error('查询失败: ' + (e.response?.data?.message || e.message))
  } finally {
    loading.value = false
  }
}

function handlePanelChange(value) {
  selectedPanel.value = value
  jumperData.value = null
}

async function refreshData() {
  loading.value = true
  try {
    await loadPanels()
    if (selectedPanel.value) {
      await queryJumperStatus()
    }
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await loadPanels()
  if (panels.value.length > 0) {
    selectedPanel.value = panels.value[0].panel_id
  }
  pollTimer.value = setInterval(refreshData, 30000)
})

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

<style scoped>
.control-bar {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}
.control-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.control-label {
  font-size: 14px;
  color: #666;
}
.register-value {
  font-family: monospace;
  font-size: 14px;
  color: #1890ff;
}
.registers-display {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.register-tag {
  font-family: monospace;
  font-size: 12px;
}
</style>