<script setup lang="ts">
import type {
  CTWingLogItem,
  CTWingLogQueryParams,
  CTWingLogResponse,
} from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

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

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

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { client } from '#/api-client';
import { Icon } from '#/components/icon';
import { $t } from '#/locales';

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

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

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

// 详情对话框
const detailVisible = ref(false);
const detailData = ref<CTWingLogItem | null>(null);

// 自定义API调用函数，使用正确的接口地址
const callDeviceDataInfoPage = async (
  params: CTWingLogQueryParams,
): Promise<CTWingLogResponse> => {
  try {
    const { data } = await client.post<CTWingLogResponse>(
      '/TableModel/CTWingLogInfo',
      {
        body: params,
      },
    );
    return data;
  } catch (error) {
    console.error('API调用失败:', error);
    throw error;
  }
};

// 查看详情
const showDetail = (row: CTWingLogItem) => {
  detailData.value = row;
  detailVisible.value = true;
};

// 导出数据
const exportData = async () => {
  try {
    message.loading($t('common.exporting'));

    // 获取当前查询条件
    const formValues = await gridApi.formApi.getValues();

    const { data } = await client.post(
      '/TableModel/CTWingLogInfo/Export',
      {
        body: {
          ...formValues,
          DeviceType,
          DeviceId,
          FocusAddress,
        },
      },
      {
        responseType: 'blob',
      },
    );

    // 创建下载链接
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `CTWing日志_${new Date().toISOString().split('T')[0]}.xlsx`;
    document.body.append(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);

    message.success($t('common.exportSuccess'));
  } catch (error) {
    console.error('导出失败:', error);
    message.error($t('common.exportFailed'));
  }
};

const formOptions: VbenFormProps = {
  schema: querySchema.value,
  initialValues: {
    FocusAddress: FocusAddress as string,
    DeviceId: DeviceId as string,
    DeviceType: DeviceType as string,
  },
  submitOnChange: false,
};

const gridOptions: VxeGridProps<CTWingLogItem> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    ...tableSchema.value,
    {
      title: $t('common.action'),
      width: 120,
      fixed: 'right',
      slots: {
        default: ({ row }) => [
          h(
            'a-button',
            {
              type: 'link',
              size: 'small',
              onClick: () => showDetail(row),
            },
            $t('common.detail'),
          ),
        ],
      },
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    currentPage: 1,
    pageSize: 20,
  },
  toolbarConfig: {
    custom: true,
    search: true,
  },
  customConfig: {
    storage: true,
  },
  showOverflow: true,
  showHeaderOverflow: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        try {
          // 使用自定义API调用函数
          const data = await callDeviceDataInfoPage({
            ...formValues,
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            DeviceType,
            DeviceId,
            FocusAddress,
          });

          // 确保返回的数据包含totalCount字段
          const result = {
            items: data.items || [],
            totalCount: data.totalCount || (data.items ? data.items.length : 0),
          };

          return result;
        } catch (error) {
          console.error('获取数据失败:', error);
          message.error($t('common.getDataFailed'));
          return {
            items: [],
            totalCount: 0,
          };
        }
      },
    },
  },
};

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

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <a-button type="primary" @click="exportData">
          <template #icon>
            <Icon icon="ant-design:download-outlined" />
          </template>
          {{ $t('common.export') }}
        </a-button>
      </template>
    </Grid>

    <!-- 详情对话框 -->
    <a-modal
      v-model:open="detailVisible"
      :title="$t('common.detail')"
      width="800px"
      :footer="null"
    >
      <div v-if="detailData" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item :label="$t('abp.IoTDBBase.SystemName')">
            {{ detailData.systemName }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.ProjectId')">
            {{ detailData.projectId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.IoTDataType')">
            {{ detailData.dataType }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.DeviceType')">
            {{ detailData.deviceType }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.DeviceId')">
            {{ detailData.deviceId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.Timestamps')">
            {{
              detailData.timestamps
                ? new Date(detailData.timestamps).toLocaleString()
                : ''
            }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.IoTDBBase.DevicePath')">
            {{ detailData.devicePath }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.PlatformTenantId')">
            {{ detailData.platformTenantId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.ProductId')">
            {{ detailData.productId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.ServiceId')">
            {{ detailData.serviceId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.PlatformDeviceId')">
            {{ detailData.platformDeviceId }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.MessageType')">
            {{ detailData.messageType }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.Protocol')">
            {{ detailData.protocol }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.FocusAddress')">
            {{ detailData.focusAddress }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.MeterAddress')">
            {{ detailData.meterAddress }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.ReceivedTime')">
            {{
              detailData.receivedTime
                ? new Date(detailData.receivedTime).toLocaleString()
                : ''
            }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.IMSI')">
            {{ detailData.imsi }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('abp.CTWingLog.IMEI')">
            {{ detailData.imei }}
          </a-descriptions-item>
          <a-descriptions-item
            :label="$t('abp.CTWingLog.RawMessage')"
            :span="2"
          >
            <div class="message-content">{{ detailData.rawMessage }}</div>
          </a-descriptions-item>
          <a-descriptions-item
            :label="$t('abp.CTWingLog.ReceivedPayload')"
            :span="2"
          >
            <div class="message-content">{{ detailData.receivedPayload }}</div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </Page>
</template>

<style scoped>
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.message-content {
  max-height: 200px;
  padding: 8px;
  overflow-y: auto;
  font-family: monospace;
  font-size: 12px;
  word-break: break-all;
  white-space: pre-wrap;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</style>
