<template>
  <div class="page-container">
    <el-card shadow="hover">
      <div class="toolbar">
        <div>
          <h2 class="page-title">连接请求</h2>
          <span class="text-muted">
            主控端发起、等待被控端确认的连接请求（共 {{ connections.length }} 条）
          </span>
        </div>
        <div class="toolbar-actions">
          <el-switch v-model="autoRefresh" active-text="自动刷新" />
          <el-button :icon="'Refresh'" :loading="loading" @click="load">刷新</el-button>
        </div>
      </div>

      <el-empty v-if="!connections.length" description="当前没有待确认的连接请求" />

      <el-table v-else :data="connections" stripe>
        <el-table-column label="主控端 (From)" prop="fromDeviceId" min-width="200" />
        <el-table-column label="被控端 (To)" prop="toDeviceId" min-width="200" />
        <el-table-column label="发起时间" min-width="180">
          <template #default="{ row }">{{ fmtTime(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="已等待" width="140">
          <template #default="{ row }">{{ (row.elapsedMs / 1000).toFixed(1) }} 秒</template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default>
            <el-tag type="warning" effect="dark">待确认</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { getConnections } from '@/api/admin';
import type { PendingConnection } from '@/api/admin';

const connections = ref<PendingConnection[]>([]);
const loading = ref(false);
const autoRefresh = ref(true);
let timer: number | undefined;

async function load() {
  loading.value = true;
  try {
    connections.value = await getConnections();
  } finally {
    loading.value = false;
  }
}

function startTimer() {
  if (timer) clearInterval(timer);
  if (autoRefresh.value) timer = window.setInterval(load, 3000);
}

watch(autoRefresh, startTimer);

function fmtTime(ts: number) {
  return new Date(ts).toLocaleString('zh-CN');
}

onMounted(() => {
  load();
  startTimer();
});
onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped>
.page-title {
  margin: 0 0 4px;
  font-size: 20px;
}
.toolbar {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;
}
.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style>
