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

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

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

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

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

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

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

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

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

// 格式化日期函数
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 '';
};
const formOptions: VbenFormProps = {
  schema: querySchema.value,
};

const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: tableSchema.value,
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 20, 100],
    layouts: [
      'PrevPage',
      'JumpNumber',
      'NextPage',
      'FullJump',
      'Sizes',
      'Total',
    ],
  },
  toolbarConfig: {
    custom: true,
  },
  customConfig: {
    storage: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        // 获取选中的设备信息
        let deviceId = '';
        let systemName = '';
        const deviceType = formValues?.DeviceType || '';
        const finalFocusAddress = formValues.FocusAddress || '';
        if (deviceSelectRef.value) {
          const deviceInfo = deviceSelectRef.value.getSelectedDeviceInfo();
          if (deviceInfo) {
            finalFocusAddress = deviceInfo.focusAddress || '';
            systemName = deviceInfo.systemName || '';
            // 设备类型为10时取focusId，其他情况取meterId
            deviceId =
              Number(deviceType) === 10
                ? deviceInfo.focusId || ''
                : deviceInfo.meterId || '';
          }
        }
        // 构建查询参数
        const queryParams: any = {
          pageIndex: page.currentPage,
          pageSize: page.pageSize,
          SearchKeyword: formValues?.SearchKeyword || '',
          DeviceType: deviceType,
          IoTDataType: formValues?.IoTDataType || '',
          DeviceId: deviceId,
          SystemName: systemName || formValues?.SystemName || '',
          StartCreationTime: formatDate(formValues?.StartCreationTime),
          EndCreationTime: formatDate(formValues?.EndCreationTime),
          FocusAddress: finalFocusAddress,
        };
        if (DeviceType) queryParams.DeviceType = DeviceType;
        if (DeviceId) queryParams.DeviceId = DeviceId;
        const { data } = await postCTWingLogInfoPage({
          body: queryParams,
        });
        const result = {
          items: data.items || [],
          totalCount: data.totalCount || (data.items ? data.items.length : 0),
        };
        return result;
      },
    },
  },
};

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

// 监听分页器状态变化
watch(
  () => gridApi?.pagerApi?.pageSize,
  (newSize, oldSize) => {
    if (newSize !== oldSize && oldSize) {
      // 重置到第一页
      gridApi.pagerApi.currentPage = 1;
      // 触发数据重新加载
      gridApi.reload();
    }
  },
);

// 监听当前页变化
watch(
  () => gridApi?.pagerApi?.currentPage,
  (newPage, oldPage) => {
    if (newPage !== oldPage && oldPage) {
      // 触发数据重新加载
      gridApi.reload();
    }
  },
);

// 监听DeviceId变化，自动刷新表格
watch(
  () => gridApi?.getFormModel?.()?.DeviceId,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      gridApi.reload();
    }
  },
);
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #DeviceId="{ model, field }">
        <DeviceSelect ref="deviceSelectRef" v-model:value="model[field]"
          :placeholder="$t('common.pleaseSelect') + $t('abp.log.deviceInfo')" allow-clear />
      </template>
    </Grid>
  </Page>
</template>
