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

import { computed } from 'vue';

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

import dayjs from 'dayjs';

import {
  getCommonGetSelectList,
  postAggregationIoTplatformGetIoTplatformAccountInfoAsync,
  postAggregationIoTplatformGetIoTplatformProductInfoAsync,
  postDeviceThingModelManagementFindByPlatformProductIdAsync,
  postFirmwareInfoFindByDeviceProductIdAsync,
} from '#/api-client';
import { $t } from '#/locales';

// EMQX 平台使用 OneNET 的账号和产品体系，查询账号/产品时需映射为 OneNET 平台类型
const ONENET_PLATFORM_TYPE = 2;
const EMQX_PLATFORM_TYPE = 3;

function getAccountQueryPlatformType(platform: any): number {
  const num =
    typeof platform === 'string' ? Number.parseInt(platform) : platform;
  if (num === EMQX_PLATFORM_TYPE) return ONENET_PLATFORM_TYPE;
  return num;
}

export const querySchema = computed(() => [
  {
    component: 'Input',
    fieldName: 'deviceAddress',
    label: $t('abp.deviceInfos.deviceAddress'),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
      afterFetch: (res: any) => {
        console.log('产品选择器API调用 - 平台类型:', res);

        // 确保返回的是数组格式
        if (Array.isArray(res)) {
          return res;
        }
        // 如果是包装在 items 中的，提取出来
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        // 如果是包装在 data 中的，提取出来
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        // 如果都不是，返回空数组
        return [];
      },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('common.BelongingProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') + $t('common.BelongingProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'deviceOnlineStatus',
    label: '在线状态',
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'DeviceOnlineStatus',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder: '请选择在线状态',
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'lifeInfo',
    label: '生命周期',
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'DeviceLifeTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder: '请选择生命周期',
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
  },
  {
    component: 'Select',
    fieldName: 'isPlatformPushSuccess',
    label: '同步状态',
    componentProps: {
      options: [
        { label: '全部', value: undefined },
        { label: '已同步', value: true },
        { label: '未同步', value: false },
      ],
      allowClear: true,
      placeholder: '请选择同步状态',
    },
  },
]);

export const tableSchema: any = computed((): VxeGridProps['columns'] => [
  { title: $t('common.seq'), type: 'seq', width: 50 },
  { title: '', type: 'checkbox', width: 50 },
  {
    field: 'ioTPlatformName',
    title: $t('common.BelongingIoTPlatform'),
    minWidth: '150',
    slots: { default: 'ioTPlatformName' },
  },
  {
    field: 'accountPhoneNumber',
    title: $t('common.BelongingAccountName'),
    minWidth: '150',
  },
  {
    field: 'ioTPlatformProductName',
    title: $t('common.BelongingProductName'),
    minWidth: '150',
  },
  {
    field: 'deviceTypeName',
    title: $t('abp.deviceInfos.deviceType'),
    minWidth: '150',
  },
  {
    field: 'encryptionTypeName',
    title: $t('abp.deviceInfos.encryptionType'),
    minWidth: '150',
    slots: { default: 'encryptionTypeName' },
  },
  {
    field: 'deviceName',
    title: $t('abp.deviceInfos.deviceName'),
    minWidth: '150',
  },
  {
    field: 'deviceAddress',
    title: $t('abp.deviceInfos.deviceAddress'),
    minWidth: '150',
  },
  {
    field: 'ioTPlatformDeviceOpenInfo',
    title: $t('abp.deviceInfos.ioTPlatformDeviceOpenInfo'),
    minWidth: '180',
  },
  {
    field: 'deviceOnlineStatusName',
    title: $t('abp.deviceInfos.DeviceOnlineStatus'),
    minWidth: '150',
    slots: { default: 'deviceOnlineStatusName' },
  },
  {
    field: 'lifeInfoName',
    title: $t('abp.deviceInfos.lifeInfoName'),
    minWidth: '120',
    slots: { default: 'lifeInfoName' },
  },
  {
    field: 'lastOnlineTime',
    title: $t('abp.deviceInfos.LastOnlineTime'),
    minWidth: '150',
    formatter: ({ cellValue }) => {
      return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '';
    },
  },
  {
    field: 'lastOfflineTime',
    title: $t('abp.deviceInfos.LastOfflineTime'),
    minWidth: '150',
    formatter: ({ cellValue }) => {
      return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '';
    },
  },
  {
    field: 'isNeedConfigDeviceModel',
    title: $t('abp.deviceInfos.isNeedConfigDeviceModel'),
    minWidth: '150',
    formatter: ({ cellValue }) => {
      return cellValue ? '是' : '否';
    },
  },
  {
    field: 'deviceThingModelName',
    title: $t('abp.deviceInfos.deviceThingModelName'),
    minWidth: '150',
  },
  {
    field: 'readingModeName',
    title: $t('abp.deviceInfos.readingMode'),
    minWidth: '150',
    slots: { default: 'readingMode' },
  },
  {
    field: 'platformPassword',
    title: $t('abp.deviceInfos.platformPassword'),
    minWidth: '150',
  },
  {
    field: 'firmwareVersion',
    title: $t('abp.deviceInfos.firmwareVersion'),
    minWidth: '150',
  },
  {
    field: 'ioTPlatformResponse',
    title: $t('abp.deviceInfos.ioTPlatformResponse'),
    minWidth: '150',
  },
  {
    title: $t('common.action'),
    field: 'action',
    fixed: 'right',
    width: '260',
    slots: { default: 'action' },
  },
]);

export const addDeviceFormSchema: any = computed(() => [
  {
    component: 'Input',
    fieldName: 'deviceAddress',
    label: $t('abp.deviceInfos.deviceAddress'),
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('abp.deviceInfos.deviceAddress')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'deviceType',
    label: $t('abp.deviceInfos.deviceType'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'DeviceTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder: $t('common.pleaseSelect') + $t('abp.deviceInfos.deviceType'),
      afterFetch: (res: any) => {
        // 确保返回的是数组格式
        if (Array.isArray(res)) {
          return res;
        }
        // 如果是包装在 items 中的，提取出来
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        // 如果是包装在 data 中的，提取出来
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        // 如果都不是，返回空数组
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.deviceType')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'EncryptionType',
    label: $t('abp.deviceInfos.encryptionType'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'DeviceAuthenticationModeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.encryptionType'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.encryptionType')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        // 确保返回的是数组格式
        if (Array.isArray(res)) {
          return res;
        }
        // 如果是包装在 items 中的，提取出来
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        // 如果是包装在 data 中的，提取出来
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        // 如果都不是，返回空数组
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformAccountId',
    label: $t('abp.deviceInfos.ioTPlatformAccountName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      rules(values: any) {
        if (values.ioTPlatform) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformAccountInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'ioTPlatformPhoneNumber',
        valueField: 'ioTPlatformAccountId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformAccountName'),
        afterFetch: (res: any) => {
          let items: any[] = [];
          if (Array.isArray(res)) {
            items = res;
          } else if (res && Array.isArray(res.items)) {
            items = res.items;
          } else if (res && Array.isArray(res.data)) {
            items = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            items = res.data.items;
          }
          // 将 ioTPlatformAccount 映射到 ioTPlatformAccountId，以便表单字段名保持一致
          return items.map((item: any) => ({
            ...item,
            ioTPlatformAccountId: item.ioTPlatformAccount,
            label: item.ioTPlatformPhoneNumber || item.ioTPlatformAccount || '',
          }));
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.deviceInfos.ioTPlatformProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform && !!values.ioTPlatformAccountId;
      },
      rules(values: any) {
        if (values.ioTPlatform && values.ioTPlatformAccountId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform', 'ioTPlatformAccountId'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;
      const accountId = formValues?.ioTPlatformAccountId;

      return {
        api:
          platform && accountId
            ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
            : null,
        params:
          platform && accountId
            ? {
                body: {
                  ioTPlatformType: getAccountQueryPlatformType(platform),
                  ioTPlatformAccount: accountId,
                },
              }
            : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
    rules: z.string().optional(),
  },
]);

// 设备绑定设备端物模型表单
export const bindDeviceThingModelFormSchema: any = computed(() => [
  {
    component: 'Input',
    fieldName: '_ioTPlatformProductId',
    label: '',
    componentProps: {
      type: 'hidden',
    },
  },
  {
    component: 'Switch',
    fieldName: 'isNeedConfigDeviceModel',
    label: '是否需要配置设备模型',
    defaultValue: false,
    componentProps: {
      style: { width: 'auto' },
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'deviceThingModelDataId',
    label: '设备物模型',
    // 仅在需要配置设备模型时显示
    dependencies: {
      show(values: any) {
        const shouldShow = !!values.isNeedConfigDeviceModel;
        console.log('设备物模型下拉框显示检查:', {
          isNeedConfigDeviceModel: values.isNeedConfigDeviceModel,
          shouldShow,
          _ioTPlatformProductId: values._ioTPlatformProductId,
        });
        return shouldShow;
      },
      triggerFields: ['isNeedConfigDeviceModel', '_ioTPlatformProductId'],
    },
    // 选择设备端物模型
    componentProps: (formValues: any) => {
      const productId =
        formValues?._ioTPlatformProductId || formValues?.ioTPlatformProductId;

      console.log('设备物模型下拉框 componentProps 被调用:', {
        formValues,
        productId,
        isNeedConfigDeviceModel: formValues?.isNeedConfigDeviceModel,
      });

      const config = {
        api: productId
          ? postDeviceThingModelManagementFindByPlatformProductIdAsync
          : null,
        params: productId
          ? {
              query: {
                id: String(productId),
              },
            }
          : {},
        // 设备端物模型信息里的显示字段
        labelField: 'deviceModelName',
        valueField: 'id',
        optionsPropName: 'options',
        immediate: !!productId,
        allowClear: true,
        placeholder: '请选择设备端物模型',
        afterFetch: (res: any) => {
          console.log('设备物模型下拉框 afterFetch 被调用，响应:', res);
          // 确保返回数组
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };

      console.log('设备物模型下拉框配置:', config);
      return config;
    },
    // 规则在提交中按开关手动校验，这里设为可选
    rules: z.string().optional(),
  },
]);

export const editDeviceFormSchemaEdit: any = computed(() => [
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      afterFetch: (res: any) => {
        // 确保返回的是数组格式
        if (Array.isArray(res)) {
          return res;
        }
        // 如果是包装在 items 中的，提取出来
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        // 如果是包装在 data 中的，提取出来
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        // 如果都不是，返回空数组
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformAccountId',
    label: $t('abp.deviceInfos.ioTPlatformAccountName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      rules(values: any) {
        if (values.ioTPlatform) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformAccountInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'ioTPlatformPhoneNumber',
        valueField: 'ioTPlatformAccountId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformAccountName'),
        afterFetch: (res: any) => {
          let items: any[] = [];
          if (Array.isArray(res)) {
            items = res;
          } else if (res && Array.isArray(res.items)) {
            items = res.items;
          } else if (res && Array.isArray(res.data)) {
            items = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            items = res.data.items;
          }
          // 将 ioTPlatformAccount 映射到 ioTPlatformAccountId，以便表单字段名保持一致
          return items.map((item: any) => ({
            ...item,
            ioTPlatformAccountId: item.ioTPlatformAccount,
            label: item.ioTPlatformPhoneNumber || item.ioTPlatformAccount || '',
          }));
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.deviceInfos.ioTPlatformProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform && !!values.ioTPlatformAccountId;
      },
      rules(values: any) {
        if (values.ioTPlatform && values.ioTPlatformAccountId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform', 'ioTPlatformAccountId'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;
      const accountId = formValues?.ioTPlatformAccountId;

      return {
        api:
          platform && accountId
            ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
            : null,
        params:
          platform && accountId
            ? {
                body: {
                  ioTPlatformType: getAccountQueryPlatformType(platform),
                  ioTPlatformAccount: accountId,
                },
              }
            : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'Input',
    fieldName: 'deviceAddress',
    label: $t('abp.deviceInfos.deviceAddress'),
    disabled: true,
  },
]);

export const commandFormSchema: any = computed(() => [
  // 指令表单不再使用schema字段，改为在模板中动态渲染
]);

// 设备升级表单
export const deviceUpgradeFormSchema: any = computed(() => [
  {
    component: 'Input',
    fieldName: 'deviceAddress',
    label: '设备地址',
    componentProps: {
      disabled: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'deviceName',
    label: '设备名称',
    componentProps: {
      disabled: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'currentVersion',
    label: '当前版本',
    componentProps: {
      disabled: true,
    },
  },
  {
    component: 'Input',
    fieldName: 'ioTPlatform',
    label: '',
    componentProps: {
      type: 'hidden',
    },
  },
  {
    component: 'Input',
    fieldName: 'ioTPlatformProductId',
    label: '',
    componentProps: {
      type: 'hidden',
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'targetVersionId',
    label: '目标版本',
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatformProductId;
      },
      rules(values: any) {
        if (values.ioTPlatformProductId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatformProductId'],
    },
    componentProps: (formValues: any) => {
      const productId = formValues?.ioTPlatformProductId;

      return {
        api: productId ? postFirmwareInfoFindByDeviceProductIdAsync : null,
        params: productId
          ? {
              query: {
                id: String(productId),
              },
            }
          : {},
        labelField: 'firmwareVersion',
        valueField: 'id',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder: '请选择目标版本',
        afterFetch: (res: any) => {
          // 过滤出已启用的固件版本
          let firmwareList: any[] = [];
          if (Array.isArray(res)) {
            firmwareList = res;
          } else if (res && Array.isArray(res.items)) {
            firmwareList = res.items;
          } else if (res && Array.isArray(res.data)) {
            firmwareList = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            firmwareList = res.data.items;
          }
          // 只返回已启用的固件版本
          return firmwareList.filter((item: any) => item.isEnable === true);
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'Textarea',
    fieldName: 'upgradeDescription',
    label: '升级说明',
    componentProps: {
      rows: 4,
      placeholder: '请输入升级说明（可选）',
      maxLength: 500,
      showCount: true,
    },
  },
]);

export const batchAddDeviceFormSchema: any = computed(() => [
  {
    component: 'Textarea',
    fieldName: 'addressList',
    label: $t('abp.deviceInfos.deviceAddress'),
    componentProps: {
      rows: 4,
      placeholder: `${
        $t('common.pleaseInput') + $t('abp.deviceInfos.deviceAddress')
      }，每行一个设备地址`,
      showCount: false,
      // 按上限 1000 行 × 每行 32 字符（地址 + 换行）预留：原 10000 只能容纳约 769 行 12 位地址，
      // 会在输入框层面静默截断，导致粘贴 1000 个地址只剩 770 行
      maxLength: 32_000,
      style: {
        resize: 'vertical',
        minHeight: '32px',
        maxHeight: '200px',
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('abp.deviceInfos.deviceAddress')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'EncryptionType',
    label: $t('abp.deviceInfos.encryptionType'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'DeviceAuthenticationModeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.encryptionType'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.encryptionType')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        // 确保返回的是数组格式
        if (Array.isArray(res)) {
          return res;
        }
        // 如果是包装在 items 中的，提取出来
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        // 如果是包装在 data 中的，提取出来
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        // 如果都不是，返回空数组
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformAccountId',
    label: $t('abp.deviceInfos.ioTPlatformAccountName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      rules(values: any) {
        if (values.ioTPlatform) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformAccountInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'ioTPlatformPhoneNumber',
        valueField: 'ioTPlatformAccountId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformAccountName'),
        afterFetch: (res: any) => {
          let items: any[] = [];
          if (Array.isArray(res)) {
            items = res;
          } else if (res && Array.isArray(res.items)) {
            items = res.items;
          } else if (res && Array.isArray(res.data)) {
            items = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            items = res.data.items;
          }
          // 将 ioTPlatformAccount 映射到 ioTPlatformAccountId，以便表单字段名保持一致
          return items.map((item: any) => ({
            ...item,
            ioTPlatformAccountId: item.ioTPlatformAccount,
            label: item.ioTPlatformPhoneNumber || item.ioTPlatformAccount || '',
          }));
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.deviceInfos.ioTPlatformProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform && !!values.ioTPlatformAccountId;
      },
      rules(values: any) {
        if (values.ioTPlatform && values.ioTPlatformAccountId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform', 'ioTPlatformAccountId'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;
      const accountId = formValues?.ioTPlatformAccountId;

      return {
        api:
          platform && accountId
            ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
            : null,
        params:
          platform && accountId
            ? {
                body: {
                  ioTPlatformType: getAccountQueryPlatformType(platform),
                  ioTPlatformAccount: accountId,
                },
              }
            : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
    rules: z.string().optional(),
  },
]);

// 批量删除设备表单（地址 + 平台 + 账号 + 产品；账号仅用于联动查产品，提交时只取平台/产品/地址）
export const batchDeleteDeviceFormSchema: any = computed(() => [
  {
    component: 'Textarea',
    fieldName: 'addressList',
    label: $t('abp.deviceInfos.deviceAddress'),
    componentProps: {
      rows: 4,
      placeholder: `${
        $t('common.pleaseInput') + $t('abp.deviceInfos.deviceAddress')
      }，每行一个设备地址`,
      showCount: false,
      // 与批量添加一致：按上限 1000 行 × 每行 32 字符预留，避免 12 位地址粘贴 1000 个被截断到约 770 行
      maxLength: 32_000,
      style: {
        resize: 'vertical',
        minHeight: '32px',
        maxHeight: '200px',
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseInput')}${$t('abp.deviceInfos.deviceAddress')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformAccountId',
    label: $t('abp.deviceInfos.ioTPlatformAccountName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      rules(values: any) {
        if (values.ioTPlatform) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformAccountInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'ioTPlatformPhoneNumber',
        valueField: 'ioTPlatformAccountId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformAccountName'),
        afterFetch: (res: any) => {
          let items: any[] = [];
          if (Array.isArray(res)) {
            items = res;
          } else if (res && Array.isArray(res.items)) {
            items = res.items;
          } else if (res && Array.isArray(res.data)) {
            items = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            items = res.data.items;
          }
          return items.map((item: any) => ({
            ...item,
            ioTPlatformAccountId: item.ioTPlatformAccount,
            label: item.ioTPlatformPhoneNumber || item.ioTPlatformAccount || '',
          }));
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.deviceInfos.ioTPlatformProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform && !!values.ioTPlatformAccountId;
      },
      rules(values: any) {
        if (values.ioTPlatform && values.ioTPlatformAccountId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform', 'ioTPlatformAccountId'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;
      const accountId = formValues?.ioTPlatformAccountId;

      return {
        api:
          platform && accountId
            ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
            : null,
        params:
          platform && accountId
            ? {
                body: {
                  ioTPlatformType: getAccountQueryPlatformType(platform),
                  ioTPlatformAccount: accountId,
                },
              }
            : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
    rules: z.string().optional(),
  },
]);

// 批量设备升级表单
export const batchUpgradeDeviceFormSchema: any = computed(() => [
  {
    component: 'Textarea',
    fieldName: 'addressList',
    label: '设备地址列表',
    componentProps: {
      rows: 4,
      placeholder: '请输入设备地址，每行一个设备地址',
      showCount: false,
      maxLength: 10_000,
      style: {
        resize: 'vertical',
        minHeight: '32px',
        maxHeight: '200px',
      },
    },
    rules: z.string().min(1, {
      message: '请输入设备地址',
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatform',
    label: $t('abp.deviceInfos.ioTPlatform'),
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'IoTPlatformTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'key',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') + $t('abp.deviceInfos.ioTPlatform'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
    rules: z.string().min(1, {
      message: `${$t('common.pleaseSelect')}${$t('abp.deviceInfos.ioTPlatform')}`,
    }),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformAccountId',
    label: $t('abp.deviceInfos.ioTPlatformAccountName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform;
      },
      rules(values: any) {
        if (values.ioTPlatform) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;

      return {
        api: platform
          ? postAggregationIoTplatformGetIoTplatformAccountInfoAsync
          : null,
        params: platform
          ? {
              body: {
                ioTPlatformType: getAccountQueryPlatformType(platform),
              },
            }
          : {},
        labelField: 'ioTPlatformPhoneNumber',
        valueField: 'ioTPlatformAccountId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformAccountName'),
        afterFetch: (res: any) => {
          let items: any[] = [];
          if (Array.isArray(res)) {
            items = res;
          } else if (res && Array.isArray(res.items)) {
            items = res.items;
          } else if (res && Array.isArray(res.data)) {
            items = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            items = res.data.items;
          }
          return items.map((item: any) => ({
            ...item,
            ioTPlatformAccountId: item.ioTPlatformAccount,
            label: item.ioTPlatformPhoneNumber || item.ioTPlatformAccount || '',
          }));
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'ioTPlatformProductId',
    label: $t('abp.deviceInfos.ioTPlatformProductName'),
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatform && !!values.ioTPlatformAccountId;
      },
      rules(values: any) {
        if (values.ioTPlatform && values.ioTPlatformAccountId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatform', 'ioTPlatformAccountId'],
    },
    componentProps: (formValues: any) => {
      const platform = formValues?.ioTPlatform;
      const accountId = formValues?.ioTPlatformAccountId;

      return {
        api:
          platform && accountId
            ? postAggregationIoTplatformGetIoTplatformProductInfoAsync
            : null,
        params:
          platform && accountId
            ? {
                body: {
                  ioTPlatformType: getAccountQueryPlatformType(platform),
                  ioTPlatformAccount: accountId,
                },
              }
            : {},
        labelField: 'productName',
        valueField: 'ioTPlatformProductId',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder:
          $t('common.pleaseSelect') +
          $t('abp.deviceInfos.ioTPlatformProductName'),
        afterFetch: (res: any) => {
          if (Array.isArray(res)) {
            return res;
          }
          if (res && Array.isArray(res.items)) {
            return res.items;
          }
          if (res && Array.isArray(res.data)) {
            return res.data;
          }
          if (res && res.data && Array.isArray(res.data.items)) {
            return res.data.items;
          }
          return [];
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'ApiSelect',
    fieldName: 'targetVersionId',
    label: '目标版本',
    dependencies: {
      show(values: any) {
        return !!values.ioTPlatformProductId;
      },
      rules(values: any) {
        if (values.ioTPlatformProductId) {
          return 'required';
        }
        return null;
      },
      triggerFields: ['ioTPlatformProductId'],
    },
    componentProps: (formValues: any) => {
      const productId = formValues?.ioTPlatformProductId;

      return {
        api: productId ? postFirmwareInfoFindByDeviceProductIdAsync : null,
        params: productId
          ? {
              query: {
                id: String(productId),
              },
            }
          : {},
        labelField: 'firmwareVersion',
        valueField: 'id',
        optionsPropName: 'options',
        immediate: false,
        allowClear: true,
        placeholder: '请选择目标版本',
        afterFetch: (res: any) => {
          let firmwareList: any[] = [];
          if (Array.isArray(res)) {
            firmwareList = res;
          } else if (res && Array.isArray(res.items)) {
            firmwareList = res.items;
          } else if (res && Array.isArray(res.data)) {
            firmwareList = res.data;
          } else if (res && res.data && Array.isArray(res.data.items)) {
            firmwareList = res.data.items;
          }
          return firmwareList.filter((item: any) => item.isEnable === true);
        },
      };
    },
    rules: z.string().optional(),
  },
  {
    component: 'Textarea',
    fieldName: 'upgradeDescription',
    label: '升级说明',
    componentProps: {
      rows: 4,
      placeholder: '请输入升级说明（可选）',
      maxLength: 500,
      showCount: true,
    },
  },
]);
