<script setup lang="ts">
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { useRoute } from 'vue-router';
import { nextTick, watch, ref, computed } from 'vue';

import { Page } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { postTreeModelDeviceDataInfoPage } from '#/api-client';

import { querySchema, tableSchema } from './schema';
import { generateDynamicColumns } from './dynamicColumns';
import { handleStandardIoTDBData, validateAndCleanData } from './example';

defineOptions({
  name: 'DeviceData',
});

const route = useRoute();
const { DeviceType, DeviceId, FocusAddress } = route.query;

// 动态列定义
const dynamicColumns = ref<any[]>([]);

// 固定列定义（始终显示）
const fixedColumns = computed(() => [
  { title: '序号', type: 'seq', width: 50 },
  // 可以在这里添加其他固定列
]);

// 合并固定列和动态列
const allColumns = computed(() => [
  ...fixedColumns.value,
  ...dynamicColumns.value,
]);

const formOptions: VbenFormProps = {
  schema: querySchema.value,
  initialValues: {
    FocusAddress: FocusAddress as string,
  },
  // 禁用表单值变化时自动提交，使用自定义处理函数
  submitOnChange: false,
  // 添加表单值变化的处理函数
  handleValuesChange: async (values, changedFields) => {
    // 当系统类型发生变化时，刷新表格数据
    if (changedFields.includes('SystemName')) {
      console.log('SystemName changed, values:', values);
      console.log('Changed fields:', changedFields);
      
      // 使用 setTimeout 确保表单值已经完全更新
      setTimeout(async () => {
        const latestValues = await gridApi.formApi.getValues();
        console.log('Latest values after timeout:', latestValues);
        gridApi.reload(latestValues);
      }, 0);
    }
  },
};
const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: allColumns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  toolbarConfig: {
    custom: true,
    search: true, 
  },
  customConfig: {
    storage: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const { data } = await postTreeModelDeviceDataInfoPage({
          body: {
            ...formValues,
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            DeviceType,
            DeviceId,
            FocusAddress,
          },
        });
        
        // 处理数据并动态生成列定义
        if (data?.items && data.items.length > 0) {
          // 验证和清理数据
          const cleanedData = validateAndCleanData(data.items);
          
          // 动态生成列定义
          dynamicColumns.value = generateDynamicColumns(cleanedData);
          
          // 返回处理后的数据
          return {
            ...data,
            items: cleanedData,
          };
        }
        
        return data;
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
</script>

<template>
  <Page auto-content-height>
    <Grid />
  </Page>
</template>
