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

import { computed, h } from 'vue';

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

import { postCtWingAccountListAsync } from '#/api-client';
import { $t } from '#/locales';

export const querySchema = computed(() => [
  {
    component: 'Input',
    fieldName: 'productName',
    label: $t('abp.CTWingManagement.ProductName'),
  },
]);

export const tableSchema: any = computed((): VxeGridProps['columns'] => [
  { title: $t('common.seq'), type: 'seq', width: 50 },
  {
    field: 'ctWingAccountName',
    title: $t('common.BelongingAccountName'),
    minWidth: '150',
  },
  {
    field: 'ioTPlatformProductId',
    title: $t('abp.CTWingManagement.CTWingProductId'),
    minWidth: '150',
  },
  {
    field: 'productName',
    title: $t('abp.CTWingManagement.ProductName'),
    minWidth: '150',
  },
  {
    field: 'masterKey',
    title: $t('abp.CTWingManagement.MasterKey'),
    minWidth: '150',
  },
  {
    field: 'featureAccesskey',
    title: $t('abp.CTWingManagement.FeatureAccesskey'),
    minWidth: '150',
  },
  {
    field: 'communicationAddress',
    title: $t('abp.CTWingManagement.CommunicationAddress'),
    minWidth: '150',
  },
  {
    field: 'thingModelFileName',
    title: $t('abp.CTWingManagement.ThingModelFileName'),
    minWidth: '150',
    slots: { default: 'thingModelFileName' },
  },
  {
    field: 'creationTime',
    title: $t('abp.CTWingManagement.CreationTime'),
    minWidth: '150',
    formatter: ({ cellValue }: any) => {
      if (!cellValue) return '-';
      const date = new Date(cellValue);
      if (isNaN(date.getTime())) return '-';
      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replaceAll('/', '-');
    },
  },
  {
    field: 'lastModificationTime',
    title: $t('abp.CTWingManagement.LastModificationTime'),
    minWidth: '150',
    formatter: ({ cellValue }: any) => {
      if (!cellValue) return '-';
      const date = new Date(cellValue);
      if (isNaN(date.getTime())) return '-';
      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replaceAll('/', '-');
    },
  },
  {
    field: 'isEnabled',
    title: $t('common.isEnable'),
    minWidth: '150',
    slots: { default: 'isEnable' },
  },
  {
    title: $t('common.action'),
    field: 'action',
    fixed: 'right',
    width: '200',
    slots: { default: 'action' },
  },
]);

// 全局变量存储选择的文件
export let selectedFile: File | null = null;

// 文件选择回调函数
let _onFileSelected: ((file: File) => void) | null = null;

export function setFileSelectedCallback(callback: (file: File) => void) {
  _onFileSelected = callback;
}

export const addProductFormSchema: any = computed(() => [
  {
    component: 'ApiSelect',
    fieldName: 'ctWingAccountId',
    label: $t('abp.CTWingManagement.AccountName'),
    componentProps: {
      api: postCtWingAccountListAsync,
      params: {
        body: {
          pageIndex: 1,
          pageSize: 1000,
        },
      },
      labelField: 'accountName',
      valueField: 'ctWingAccountId',
      immediate: true,
      afterFetch: (res: any) => {
        // 如果是 Axios 响应对象，提取 data
        if (res && res.data) {
          const data = res.data;

          // 确保返回的是数组格式
          if (Array.isArray(data)) {
            return data;
          }
          // 如果是包装在 items 中的，提取出来
          if (data && Array.isArray(data.items)) {
            return data.items;
          }
          // 如果是包装在 data 中的，提取出来
          if (data && Array.isArray(data.data)) {
            return data.data;
          }
        }

        // 如果都不是，返回空数组
        return [];
      },
      placeholder: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.AccountName')}`,
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.AccountName')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.CTWingManagement.CTWingProductId'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CTWingProductId')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'productAccesskey',
    label: $t('abp.CTWingManagement.MasterKey'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.MasterKey')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'communicationAddress',
    label: $t('abp.CTWingManagement.CommunicationAddress'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CommunicationAddress')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'communicationAddressTLS',
    label: $t('abp.CTWingManagement.CommunicationAddressTLS'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CommunicationAddressTLS')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'thingModelFileName',
    label: $t('abp.CTWingManagement.ThingModelFileName'),
    componentProps: {
      placeholder: '请选择文件',
      readonly: true,
      addonAfter: h(
        'button',
        {
          type: 'button',
          style:
            'border: none; background: #1890ff; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer;',
          onClick: () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json,.xlsx,.xls';
            input.addEventListener('change', (e: any) => {
              const file = e.target.files[0];
              if (file) {
                // 只显示文件名，不上传
                const currentInput = document.querySelector(
                  'input[placeholder="请选择文件"]',
                ) as HTMLInputElement;
                if (currentInput) {
                  currentInput.value = file.name;
                  // 触发change事件
                  currentInput.dispatchEvent(
                    new Event('input', { bubbles: true }),
                  );
                  currentInput.dispatchEvent(
                    new Event('change', { bubbles: true }),
                  );

                  // 存储文件对象到全局变量，用于后续上传
                  selectedFile = file;
                  // 调用回调函数
                  if (_onFileSelected) {
                    _onFileSelected(file);
                  }
                }
                console.log(
                  '文件已选择:',
                  file.name,
                  '大小:',
                  file.size,
                  '字节',
                );
              }
            });
            input.click();
          },
        },
        '选择文件',
      ),
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.ThingModelFileName')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'thingModelFileId',
    label: '',
    componentProps: {
      type: 'hidden',
    },
  },
]);

export const editProductFormSchemaEdit: any = computed(() => [
  {
    component: 'ApiSelect',
    fieldName: 'ctWingAccountId',
    label: $t('abp.CTWingManagement.AccountName'),
    componentProps: {
      api: postCtWingAccountListAsync,
      params: {
        body: {
          pageIndex: 1,
          pageSize: 1000,
        },
      },
      labelField: 'accountName',
      valueField: 'ctWingAccountId',
      immediate: true,
      disabled: true, // 编辑时禁用
      afterFetch: (res: any) => {
        // 如果是 Axios 响应对象，提取 data
        if (res && res.data) {
          const data = res.data;

          // 确保返回的是数组格式
          if (Array.isArray(data)) {
            return data;
          }
          // 如果是包装在 items 中的，提取出来
          if (data && Array.isArray(data.items)) {
            return data.items;
          }
          // 如果是包装在 data 中的，提取出来
          if (data && Array.isArray(data.data)) {
            return data.data;
          }
        }

        // 如果都不是，返回空数组
        return [];
      },
      placeholder: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.AccountName')}`,
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.AccountName')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.CTWingManagement.CTWingProductId'),
    disabled: true,
    componentProps: {
      readonly: true, // 编辑时只读
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CTWingProductId')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'productAccesskey',
    label: $t('abp.CTWingManagement.MasterKey'),
    disabled: true,
    componentProps: {
      readonly: true, // 编辑时只读
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.MasterKey')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'communicationAddress',
    label: $t('abp.CTWingManagement.CommunicationAddress'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CommunicationAddress')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'communicationAddressTLS',
    label: $t('abp.CTWingManagement.CommunicationAddressTLS'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('common.info')}${$t('abp.CTWingManagement.CommunicationAddressTLS')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'thingModelFileName',
    label: $t('abp.CTWingManagement.ThingModelFileName'),
    componentProps: {
      placeholder: '请选择文件',
      readonly: true,
      addonAfter: h(
        'button',
        {
          type: 'button',
          style:
            'border: none; background: #1890ff; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer;',
          onClick: () => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json,.xlsx,.xls';
            input.addEventListener('change', (e: any) => {
              const file = e.target.files[0];
              if (file) {
                // 只显示文件名，不上传
                const currentInput = document.querySelector(
                  'input[placeholder="请选择文件"]',
                ) as HTMLInputElement;
                if (currentInput) {
                  currentInput.value = file.name;
                  // 触发change事件
                  currentInput.dispatchEvent(
                    new Event('input', { bubbles: true }),
                  );
                  currentInput.dispatchEvent(
                    new Event('change', { bubbles: true }),
                  );

                  // 存储文件对象到全局变量，用于后续上传
                  selectedFile = file;
                  // 调用回调函数
                  if (_onFileSelected) {
                    _onFileSelected(file);
                  }
                }
                console.log(
                  '文件已选择:',
                  file.name,
                  '大小:',
                  file.size,
                  '字节',
                );
              }
            });
            input.click();
          },
        },
        '选择文件',
      ),
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.CTWingManagement.ThingModelFileName')}`,
    }),
  },
  {
    component: 'Input',
    fieldName: 'thingModelFileId',
    label: '',
    componentProps: {
      type: 'hidden',
    },
  },
]);
