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

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

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

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

import { querySchema, tableSchema } from './schema';

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

const route = useRoute();
const { DeviceAddress } = route.query;

// 是否正在初始化，用于防止重复查询
const isInitializing = ref(false);

// 添加设备选择器引用
const deviceSelectRef = ref();

// 添加选中的设备信息
const selectedDeviceInfo = ref<any>(null);

// 存储设备信息选项的完整数据
const deviceOptions = ref<any[]>();

// 获取设备信息的完整数据
const fetchDeviceOptions = async () => {
  try {
    const { data } = await postDeviceInfoPage({
      body: {
        pageIndex: 1,
        pageSize: 1000,
      },
    });

    if (data?.items) {
      deviceOptions.value = data.items;
    }
  } catch (error) {
    console.error('获取设备信息失败:', error);
  }
};

// 根据设备地址获取设备信息对象
const getDeviceInfoByAddress = (deviceAddress: string) => {
  if (!deviceAddress || !deviceOptions.value || deviceOptions.value.length === 0) {
    return null;
  }

  const device = deviceOptions.value.find((device) => device.deviceAddress === deviceAddress);
  return device;
};

// 格式化日期函数
const formatDate = (date: any) => {
  if (!date) return '';
  if (typeof date === 'string') return date;
  if (date.toISOString) return date.format('YYYY-MM-DD HH:mm:ss');
  return '';
};
// 从 DeviceSelect 组件获取设备信息
const getDeviceInfoFromRef = async () => {
  if (
    deviceSelectRef.value &&
    typeof deviceSelectRef.value.getSelectedDevice === 'function'
  ) {
    const deviceInfo = deviceSelectRef.value.getSelectedDevice();
    return deviceInfo;
  }
  return null;
};

const formOptions: VbenFormProps = {
  schema: querySchema.value,
  initialValues: {
    DeviceAddress: DeviceAddress as string,
  },
  // 禁用表单值变化时自动提交，使用自定义处理函数
  submitOnChange: false,
  // 添加表单值变化的处理函数
  handleValuesChange: async (values, changedFields) => {
    // 如果正在初始化，不触发查询
    if (isInitializing.value) {
      return;
    }

    // 当 DeviceAddress 发生变化时，更新 selectedDeviceInfo
    if (changedFields.includes('DeviceAddress')) {
      const deviceAddress = values.DeviceAddress;

      if (deviceAddress) {
        // 先尝试从 deviceOptions 中查找（备用方案）
        let device =
          deviceOptions.value.length > 0
            ? deviceOptions.value.find((d) => d.deviceAddress === deviceAddress)
            : null;

        // 如果没找到，尝试从 DeviceSelect 组件中获取
        if (!device && gridApi?.formApi) {
          try {
            // 获取 DeviceSelect 组件的实例
            const deviceSelectRef =
              gridApi.formApi.getFieldComponentRef('DeviceAddress');
            if (deviceSelectRef && deviceSelectRef.getSelectedDevice) {
              device = deviceSelectRef.getSelectedDevice();
            }
          } catch {
            // 静默处理错误
          }
        }

        if (device) {
          selectedDeviceInfo.value = device;
        } else {
          // 如果还是没找到，尝试延迟获取（组件可能还没完全更新）
          setTimeout(() => {
            try {
              const deviceSelectRef =
                gridApi.formApi.getFieldComponentRef('DeviceAddress');
              if (deviceSelectRef && deviceSelectRef.getSelectedDevice) {
                const delayedDevice = deviceSelectRef.getSelectedDevice();
                if (delayedDevice) {
                  selectedDeviceInfo.value = delayedDevice;
                }
              }
            } catch {
              // 静默处理错误
            }
          }, 100);
        }
      } else {
        selectedDeviceInfo.value = null;
      }
    }

    // 当任何相关字段发生变化时，刷新表格数据
    const relevantFields = new Set([
      'DeviceAddress',
      'EndCreationTime',
      'IoTDataType',
      'StartCreationTime',
    ]);
    const hasRelevantChange = changedFields.some((field) =>
      relevantFields.has(field),
    );

    if (hasRelevantChange) {
      // 使用 setTimeout 确保表单值已经完全更新
      setTimeout(async () => {
        const latestValues = await gridApi.formApi.getValues();
        gridApi.reload(latestValues);
      }, 0);
    }
  },
};

const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: tableSchema.value,
  height: 'auto',
  keepSource: true,
  pager: true,
  pagerConfig: {
    currentPage: 1,
    pageSize: 20,
  },
  toolbarConfig: {
    custom: true,
  },
  customConfig: {
    storage: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        // 总是从表单API获取最新的表单值，确保分页时参数完整
        const currentFormValues = gridApi?.formApi ? await gridApi.formApi.getValues() : {};

        // 如果表单中没有DeviceAddress，但有路由参数，使用路由参数
        if (!currentFormValues.DeviceAddress && DeviceAddress) {
          currentFormValues.DeviceAddress = DeviceAddress as string;
        }

        // 获取选中的设备信息
        let deviceAddress = currentFormValues.DeviceAddress || '';

        // 优先使用选中的设备信息
        const deviceInfo =
          selectedDeviceInfo.value ||
          (deviceAddress && deviceOptions.value.length > 0
            ? getDeviceInfoByAddress(deviceAddress)
            : null);

        if (deviceInfo) {
          deviceAddress = deviceInfo.deviceAddress || deviceAddress;
        }

        // 构建查询参数
        const queryParams = {
          pageIndex: page.currentPage,
          pageSize: page.pageSize,
          SearchKeyword: currentFormValues.SearchKeyword || '',
          IoTDataType: currentFormValues.IoTDataType || '',
          DeviceAddress: deviceAddress, // 使用设备地址
          StartCreationTime: formatDate(currentFormValues.StartCreationTime),
          EndCreationTime: formatDate(currentFormValues.EndCreationTime),
        };

        const { data } = await postTableModelOneNetLogInfo({
          body: queryParams,
        });
        const result = {
          items: data.items || [],
          totalCount: data.totalCount || (data.items ? data.items.length : 0),
        };
        return result;
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

// 初始化函数
const initializeGrid = async () => {
  try {
    // 设置初始化标志
    isInitializing.value = true;

    // 获取设备信息数据
    await fetchDeviceOptions();

    // 如果有路由参数，自动触发查询
    if (DeviceAddress) {
      // 延迟一下确保表格已完全初始化
      setTimeout(async () => {
        if (gridApi && gridApi.formApi) {
          // 确保表单值正确设置
          const currentValues = await gridApi.formApi.getValues();
          if (!currentValues.DeviceAddress && DeviceAddress) {
            await gridApi.formApi.setValues({
              ...currentValues,
              DeviceAddress: DeviceAddress as string,
            });
          }
          // 延迟清除初始化标志，确保只触发一次查询
          setTimeout(() => {
            isInitializing.value = false;
            gridApi.reload();
          }, 200);
        } else {
          isInitializing.value = false;
        }
      }, 300);
    } else {
      // 如果没有路由参数，直接清除初始化标志
      isInitializing.value = false;
    }
  } catch (error) {
    console.error('初始化表格失败:', error);
    isInitializing.value = false;
  }
};

// 监听分页器状态变化
watch(
  () => gridApi?.pagerApi?.pageSize,
  async (newSize, oldSize) => {
    if (newSize !== oldSize && oldSize && !isInitializing.value) {
      // 重置到第一页
      gridApi.pagerApi.currentPage = 1;
      // 获取最新表单值并触发数据重新加载
      const latestValues = await gridApi.formApi.getValues();
      gridApi.reload(latestValues);
    }
  },
);

// 监听当前页变化
watch(
  () => gridApi?.pagerApi?.currentPage,
  async (newPage, oldPage) => {
    if (newPage !== oldPage && oldPage && !isInitializing.value) {
      // 获取最新表单值并触发数据重新加载
      const latestValues = await gridApi.formApi.getValues();
      gridApi.reload(latestValues);
    }
  },
);

// 页面初始化时，延迟初始化表格
onMounted(async () => {
  // 延迟初始化，确保VXE表格组件已完全挂载
  setTimeout(async () => {
    await initializeGrid();
  }, 100);
});
</script>

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