<script setup lang="ts">
import {ref} from 'vue'
import type {TableColumnsType} from 'ant-design-vue'
import {WifiOutlined} from '@ant-design/icons-vue'
import {useI18n} from "vue-i18n";
import { useRouter } from 'vue-router';
defineOptions({
  name: 'access'
});
const { t } = useI18n();
const router = useRouter();

const handleBack = () => {
  router.push('/userInfo/usercard');
};

// 设备列表数据
const deviceList = ref<{
  deviceName: string;
  macAddress: string;
  speed: string;
  id: number;
}[]>([]);
const loading = ref(false);

const columns: TableColumnsType = [
  {
    title: t('page.access.devicename'),
    dataIndex: 'deviceName',
    key: 'deviceName',
    width: '30%'
  },
  {
    title: t('page.access.mac'),
    dataIndex: 'macAddress',
    key: 'macAddress',
    width: '40%'
  },
  {
    title: t('page.access.speed'),
    dataIndex: 'speed',
    key: 'speed',
    width: '30%',
    align: 'right'
  }
];
// 格式化速度函数
function formatSpeed(bytesPerSecond: number): string {
  // 处理 0 值、undefined 或 null 的情况
  if (!bytesPerSecond || bytesPerSecond === 0) {
    return '0 B/s';
  }

  if (bytesPerSecond < 1024) {
    return `${Number(bytesPerSecond.toFixed(2))} B/s`;
  } else if (bytesPerSecond < 1024 * 1024) {
    return `${Number((bytesPerSecond / 1024).toFixed(2))} KB/s`;
  } else if (bytesPerSecond < 1024 * 1024 * 1024) {
    return `${Number((bytesPerSecond / (1024 * 1024)).toFixed(2))} MB/s`;
  } else {
    return `${Number((bytesPerSecond / (1024 * 1024 * 1024)).toFixed(2))} GB/s`;
  }
}

// 获取设备列表数据
async function getDeviceList() {
  loading.value = true;
  try {
    const { data, error } = await fetchCurrentDevices();
    if (!error && data) {
      // 将API返回的数据映射到表格所需的格式
      deviceList.value = data.rows.map(item => ({
        id: item.id,
        deviceName: item.clientName,
        macAddress: item.clientMac,
        speed: formatSpeed(item.activity) // 如果需要显示设备类型作为速度
      }));
    }
  } catch (err) {
    console.error('Failed to fetch device list:', err);
  } finally {
    loading.value = false;
  }
}

// 刷新设备列表
async function handleRefresh() {
  await getDeviceList();
}

// 组件挂载时获取数据
onMounted(() => {
  getDeviceList();
});


</script>

<template>
  <div class="device-list-container">
    <a-card :bordered="false">
      <template #title>
        <div class="card-title">
          <WifiOutlined/>
          <span>{{ t('page.access.currentdevice') }}</span>
        </div>
      </template>

      <template #extra>
        <a-button @click="handleBack">
          {{ t('page.login.common.back') }}
        </a-button>
        <a-button type="primary" :loading="loading" @click="handleRefresh">
          <template #icon>
            <span class="i-carbon:refresh"></span>
          </template>
          {{ t('page.access.refresh') }}
        </a-button>
      </template>

      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="deviceList"
        :pagination="{
          total: deviceList.length,
          pageSize: 10,
          showSizeChanger: false,
          showTotal: (total) => `共 ${total} 条`
        }"
      >
      </a-table>
    </a-card>
  </div>
</template>

<style scoped>
.device-list-container {
  padding: 8px;
  background-color: #f5f5f7;
  min-height: 100vh;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 12px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-wrapper) {
  width: 100%;
}

:deep(.ant-table) {
  width: 100%;
}

@media screen and (min-width: 768px) {
  .device-list-container {
    padding: 16px;
  }
}
</style>
