<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <DeviceSearch
        v-model:model="searchParams"
        :loading="loading"
        @reset="handleReset"
        @search="handleSearch"
      />
      <ACard
        :title="t('page.apdevice.aptitle')"
        :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.apdevice.total')} ${total} `
          }"
          :scroll="scrollConfig"
          class="h-full"
          @change="(pagination) => {
            searchParams.pageNum = pagination.current;
            searchParams.pageSize = pagination.pageSize;
            getData();
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <ATag :color="record.status === 1 ? 'success' : 'error'">
                {{ record.status === 1 ? t('page.apdevice.online') : t('page.apdevice.outline') }}
              </ATag>
            </template>
          </template>
        </ATable>
      </ACard>
    </div>
  </SimpleScrollbar>
</template>

<script setup lang="ts">
import { useTable } from '@/hooks/common/table';
import { SimpleScrollbar } from '~/packages/materials/src';
import { computed, shallowRef } from 'vue';
import { useElementSize } from '@vueuse/core';
import { fetchApDeviceList } from '@/service/api/auth';
import { Card as ACard, Table as ATable, Tag as ATag } from 'ant-design-vue';
import DeviceSearch from './modules/device-search.vue';
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 {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  mobilePagination,
  searchParams,
} = useTable({
  apiFn: async (params: Api.Device.ApDeviceParams) => {
    try {
      console.log('Fetching with params:', JSON.stringify(params, null, 2));
      const response = await fetchApDeviceList(params);
      console.log('API Response:', response);
      return {
        data: {
          rows: response.data || [],
          total: Array.isArray(response.data) ? response.data.length : 0
        }
      };
    } catch (error) {
      console.error('API Error:', error);
      return {
        data: {
          rows: [],
          total: 0
        },
        error
      };
    }
  },
  immediate: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    name: '',
    mac: ''
  } as Api.Device.ApDeviceParams,
  rowKey: 'id',
  pagination: true,
  columns: (): AntDesign.TableColumn<Api.Device.ApDevice>[] => [
    {
      key: 'name',
      dataIndex: 'name',
      title: t('page.apdevice.apname'),
      align: 'center',
      width: 150
    },
    {
      key: 'ip',
      dataIndex: 'ip',
      title: t('page.apdevice.ip'),
      align: 'center',
      width: 150
    },
    {
      key: 'mac',
      dataIndex: 'mac',
      title: t('page.apdevice.mac'),
      align: 'center',
      width: 180
    },
    {
      key: 'model',
      dataIndex: 'model',
      title: t('page.apdevice.model'),
      align: 'center',
      width: 150
    },
    {
      key: 'uptime',
      dataIndex: 'uptime',
      title: t('page.apdevice.uptime'),
      align: 'center',
      width: 180
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: t('page.apdevice.status'),
      align: 'center',
      width: 100
    }
  ]
});

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

// 添加搜索处理函数
const handleSearch = () => {
  console.log('Searching with params:', JSON.stringify(searchParams, null, 2));
  getData();
};

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

  // 重置搜索参数
  searchParams.name = '';
  searchParams.mac = '';
  searchParams.pageNum = 1;
  searchParams.pageSize = currentPageSize;

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

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

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