<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(() => {
  const columns = [
    ...fixedColumns.value,
    ...dynamicColumns.value,
  ];
  console.log('当前所有列定义:', columns);
  return columns;
});

// 初始化默认列（防止表格空白）
const initDefaultColumns = () => {
  if (dynamicColumns.value.length === 0) {
    dynamicColumns.value = [
      { field: 'SystemName', title: '系统名称', minWidth: '150' },
      { field: 'DeviceType', title: '设备类型', minWidth: '150' },
      { field: 'DeviceId', title: '设备ID', minWidth: '150' },
    ];
  }
};

// 初始化默认列
initDefaultColumns();

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: {
    currentPage: 1,
    pageSize: 20,
  },
  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,
          },
        });
        
        console.log('API返回的原始数据:', data);
        
        // 简化处理逻辑，先确保基本功能正常
        if (data?.items && data.items.length > 0) {
          console.log('原始items数据:', data.items);
          
          // 直接使用原始数据，不进行复杂处理
          const items = data.items;
          
          // 动态生成列定义
          const generatedColumns = generateDynamicColumns(items);
          console.log('生成的列定义:', generatedColumns);
          
          // 更新动态列
          dynamicColumns.value = generatedColumns;
          
          // 强制更新列定义
          await nextTick();
          
          console.log('返回给表格的数据:', data);
          return data;
        }
        
        console.log('没有数据或数据为空');
        return data;
      },
    },
  },
};

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

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