<template>
  <a-card style="height: 100%;margin-top: 13px;">
    <BasicTable @register="registerTable" @selection-change="handleRowSelection" />
  </a-card>
</template>

<script lang="ts" setup>
  import { ref, watch, onMounted,onUnmounted } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { queryForCurUser, queryAllMetric } from '../MetricMonitorSet.api';
  import { MetricColumns, searchStandSchema2 } from '../MetricMonitorSet.data';
  import { useRouter } from 'vue-router';

  const props = defineProps({
    mtrcCtp: {
      type: Number,
      default: null,
    },
  });

  const emit = defineEmits(['onClickRow1']);
  const router = useRouter();
  const targetId = ref(router.currentRoute.value.query.targetId as string);
  const selectedRowKeys = ref<string[]>([]);

  // 缓存API调用函数
  const getApi = () => props.mtrcCtp === 1 ? queryForCurUser : queryAllMetric;

  // 表格配置
  const [registerTable, { getSelectRows, setSelectedRowKeys, setProps }] = useTable({
    title: '',
    size: 'big',
    api: getApi(),
    columns: MetricColumns,
    showTableSetting: false,
    pagination: true,
    canResize: true,
    useSearchForm: true,
    immediate: true, // 改为手动触发，避免重复请求
    bordered: true,
    showIndexColumn: false,
    scroll: {
      y: 'calc(100vh - 200px)'
    },
    defSort: {
      column: 'mtrcNo',
      order: 'asc',
    },
    rowSelection: {
      type: 'radio',
      width: 20,
      title: '选择',
    },
    handleSearchInfoFn: (info) => info,
    formConfig: {
      labelWidth: 80,
      schemas: searchStandSchema2,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
    },
    beforeFetch: (params) => {
      params.mtrcCtp = props.mtrcCtp;
      if (targetId.value) {
        params.id = targetId.value;
      }
      return params;
    },
    afterFetch: () => {
      if (targetId.value) {
        setSelectedRowKeys([targetId.value]);
      }
    },
  });

  // 监听mtrcCtp变化，更新API
  watch(() => props.mtrcCtp, (newVal) => {
    setProps({ api: getApi() });
  });

  // 初始化加载
  onMounted(() => {
    // 延迟加载数据，避免组件挂载时的性能峰值
    setTimeout(() => {
      setProps({ immediate: true });
    }, 100);
  });

  // 行选择处理 - 防抖处理
  let selectionTimer: number | null = null;
  function handleRowSelection() {
    if (selectionTimer) {
      clearTimeout(selectionTimer);
    }
    
    selectionTimer = setTimeout(() => {
      const rowAry = getSelectRows();
      if (rowAry.length > 0) {
        emit('onClickRow1', rowAry[0]);
      }
      selectionTimer = null;
    }, 50) as unknown as number;
  }

  // 组件卸载时清理定时器
  onUnmounted(() => {
    if (selectionTimer) {
      clearTimeout(selectionTimer);
    }
  });
</script>

<style scoped>
.pb-10 {
  padding-bottom: 10px;
}
</style>