<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <TerminalSearch
        v-model:model="searchParams"
        :loading="loading"
        @reset="handleReset"
        @search="handleSearch"
      />
      <ACard
        :title="t('page.terminal.title')"
        :bordered="false"
        :body-style="{ flex: 1, overflow: 'hidden' }"
        class="flex-col-stretch sm:flex-1-hidden card-wrapper"
      >
        <template #extra>
          <TableHeaderOperation
            v-model:columns="columnChecks"
            :loading="loading"
            :not-show-add="true"
            :show-delete="false"
            @refresh="getData"
          />
        </template>

        <ATable
          ref="wrapperEl"
          :columns="columns"
          :data-source="data"
          :loading="loading"
          row-key="id"
          size="small"
          :pagination="{
            ...mobilePagination,
            total: mobilePagination.total,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            showTotal: (total: number) => `${t('page.terminal.total')} ${total} `
          }"
          :scroll="scrollConfig"
          class="h-full"
          @change="(pagination) => {
            searchParams.pageNum = pagination.current;
            searchParams.pageSize = pagination.pageSize;
            getData();
          }"
        />
      </ACard>
    </div>
  </SimpleScrollbar>
</template>

<script setup lang="ts">
import { useTable } from '@/hooks/common/table';
import { SimpleScrollbar } from '~/packages/materials/src';
import { computed, shallowRef, watch } from 'vue';
import { useElementSize } from '@vueuse/core';
import { fetchTerminalList } from '@/service/api/auth';
import { Card as ACard, Table as ATable, Tag as ATag } from 'ant-design-vue';
import TerminalSearch from './modules/terminal-search.vue';
import { formatStorage } from '@/utils/units';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const wrapperEl = shallowRef<HTMLElement | null>(null);
const { height: wrapperElHeight } = useElementSize(wrapperEl);

const scrollConfig = computed(() => ({
  y: wrapperElHeight.value - 72,
  x: 800
}));

const getAuthStatusText = (status: number) => {
  switch (status) {
    case 1:
      return t('page.terminal.pending');
    case 2:
      return t('page.terminal.authorized');
    default:
      return t('page.terminal.unknow');
  }
};

const getAuthStatusColor = (status: number) => {
  switch (status) {
    case 1:
      return 'warning';
    case 2:
      return 'success';
    default:
      return 'default';
  }
};

const formatDetailedTime = (seconds: number): string => {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  const parts = [];
  if (days > 0) parts.push(`${days}${t('page.terminal.day')}`);
  if (hours > 0) parts.push(`${hours}${t('page.terminal.hour')}`);
  if (minutes > 0) parts.push(`${minutes}${t('page.terminal.min')}`);
  if (remainingSeconds > 0 || parts.length === 0) parts.push(`${remainingSeconds}${t('page.terminal.second')}`);

  return parts.join('');
};

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  mobilePagination,
  searchParams,
} = useTable({
  apiFn: async (params: Api.Device.TerminalDeviceParams) => {
    try {
      const response = await fetchTerminalList(params);
      const rows = response.data || [];
      const total = Array.isArray(response.data) ? response.data.length : 0;
      return {
        data: {
          rows,
          total
        }
      };
    } catch (error) {
      return {
        data: {
          rows: [],
          total: 0
        },
        error
      };
    }
  },
  immediate: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    clientName: '',
    clientDeviceType: '',
    clientMac: ''
  } as Api.Device.TerminalDeviceParams,
  rowKey: 'id',
  pagination: true,
  columns: (): AntDesign.TableColumn<Api.Device.TerminalDevice>[] => [
    {
      key: 'name',
      dataIndex: 'name',
      title: t('page.terminal.name'),
      align: 'center',
      width: 150
    },
    {
      key: 'ip',
      dataIndex: 'ip',
      title: t('page.terminal.ip'),
      align: 'center',
      width: 150
    },
    {
      key: 'authStatus',
      dataIndex: 'authStatus',
      title: t('page.terminal.status'),
      align: 'center',
      width: 120,
      customRender: ({ text }) => h(ATag, {
        color: getAuthStatusColor(text)
      }, () => getAuthStatusText(text))
    },
    {
      key: 'ssid',
      dataIndex: 'ssid',
      title: t('page.terminal.ssid'),
      align: 'center',
      width: 120
    },
    {
      key: 'apName',
      dataIndex: 'apName',
      title: t('page.terminal.apname'),
      align: 'center',
      width: 120
    },
    {
      key: 'mac',
      dataIndex: 'mac',
      title: t('page.terminal.mac'),
      align: 'center',
      width: 150
    },
    {
      key: 'activity',
      dataIndex: 'activity',
      title: t('page.terminal.activity'),
      align: 'center',
      width: 120,
      customRender: ({ text }) => {
        const { value, unit } = formatStorage(text);
        return `${value.toFixed(2)} ${unit}/s`;
      }
    },
    {
      key: 'trafficDown',
      dataIndex: 'trafficDown',
      title: t('page.terminal.down'),
      align: 'center',
      width: 120,
      customRender: ({ text }) => {
        const { value, unit } = formatStorage(text);
        return `${value.toFixed(2)} ${unit}`;
      }
    },
    {
      key: 'trafficUp',
      dataIndex: 'trafficUp',
      title: t('page.terminal.up'),
      align: 'center',
      width: 120,
      customRender: ({ text }) => {
        const { value, unit } = formatStorage(text);
        return `${value.toFixed(2)} ${unit}`;
      }
    },
    {
      key: 'uptime',
      dataIndex: 'uptime',
      title: t('page.terminal.uptime'),
      align: 'center',
      width: 150,
      customRender: ({ text }) => formatDetailedTime(text)
    }
  ]
});

// 监听搜索参数变化并打印日志
watch(
  () => searchParams,
  (newParams) => {
    console.log('Search params changed:', JSON.stringify(newParams, null, 2));
  },
  { deep: true, immediate: true }
);

// 添加搜索处理函数
const handleSearch = () => {
  getData();
};

// 修改重置处理函数
const handleReset = () => {
  // 保存当前的 pageSize
  const currentPageSize = searchParams.pageSize;

  // 重置搜索参数
  searchParams.clientName = '';
  searchParams.clientDeviceType = '';
  searchParams.clientMac = '';
  searchParams.pageNum = 1;
  searchParams.pageSize = currentPageSize;

  // 重新获取数据
  getData();
};
</script>

<style scoped>
.h-full {
  height: 100%;
}

.card-wrapper {
  margin-top: 16px;
}
</style>
