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

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

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

import { Button, Input, Select, message as Message, Tag } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getCommonGetSelectList,
  postAggregationIoTplatformUpdateIoTplatformProductThingModelInfoAsync,
  postIoTplatformThingModelInfoCreateIoTplatformThingModelCommand,
  postIoTplatformThingModelInfoCopyAnotherThingModelAsync,
  postIoTplatformThingModelInfoCopyStandardThingModel,
  postIoTplatformThingModelInfoCreateAsync,
  postIoTplatformThingModelInfoDeleteAsync,
  postIoTplatformThingModelInfoExportPlatformThingModel,
  postIoTplatformThingModelInfoGetIoTplatformThingModelService,
  postIoTplatformThingModelInfoImportPlatformThingModel,
  postIoTplatformThingModelInfoPageAsync,
  postIoTplatformThingModelInfoUpdateAsync,
} from '#/api-client';
import { TableAction } from '#/components/table-action';
import { $t } from '#/locales';

import {
  copyStandardThingModelFormSchema,
  copyThingModelFormSchema,
  getAddThingModelFormSchema,
  getEditThingModelFormSchema,
  querySchema,
  tableSchema,
} from './schema';

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

const route = useRoute();

// 从路由参数获取产品信息
const productId = ref<string>((route.query.productId as string) || '');
const productName = ref<string>((route.query.productName as string) || '');
const ioTPlatform = ref<string>((route.query.ioTPlatform as string) || '2');

// 标识符类型选项映射
const identifierTypeMap = ref<Record<number | string, string>>({});

// 获取标识符类型选项
const loadIdentifierTypeOptions = async () => {
  try {
    const res = await getCommonGetSelectList({
      query: {
        typeName: 'ThingModelIdentifierTypeEnum',
      },
    });
    const items = Array.isArray(res.data)
      ? res.data
      : Array.isArray(res.data?.items)
        ? res.data.items
        : Array.isArray(res.data?.data)
          ? res.data.data
          : [];
    const map: Record<number | string, string> = {};
    items.forEach((item: any) => {
      if (item.key !== undefined && item.value) {
        map[item.key] = item.value;
      }
    });
    identifierTypeMap.value = map;
  } catch (error) {
    console.error('获取标识符类型选项失败:', error);
    // 使用默认映射
    identifierTypeMap.value = {
      1: '数据标识符',
      2: '属性标识符',
    };
  }
};

const formOptions: VbenFormProps = {
  schema: querySchema.value,
  initialValues: {
    ioTPlatform: route.query.ioTPlatform
      ? String(route.query.ioTPlatform)
      : undefined,
    ioTPlatformProductId: route.query.productId
      ? String(route.query.productId)
      : undefined,
  },
  submitOnChange: false,
  handleValuesChange: async (values, changedFields) => {
    // 当平台类型变化时，清空产品ID
    if (changedFields.includes('ioTPlatform') && values.ioTPlatform) {
      ioTPlatform.value = String(values.ioTPlatform);
      // 清空产品ID，因为平台变化了
      if (gridApi?.formApi) {
        await gridApi.formApi.setValues({
          ioTPlatformProductId: undefined,
        });
      }
      productId.value = '';
      productName.value = '';
    }

    // 当产品ID变化时，更新响应式变量并重新加载数据
    if (changedFields.includes('ioTPlatformProductId')) {
      if (values.ioTPlatformProductId) {
        productId.value = String(values.ioTPlatformProductId);
        // 产品名称可以从 ApiSelect 的选项中获取，不需要额外请求
        // 如果需要产品名称，可以通过表单字段的选项来获取
      } else {
        productId.value = '';
        productName.value = '';
      }

      // 延迟重新加载数据，确保表单值已更新
      await nextTick();
      setTimeout(async () => {
        if (gridApi && gridApi.reload) {
          try {
            // 确保使用最新的表单值进行查询
            await gridApi.reload();
          } catch (error) {
            console.error('重新加载数据时出错:', error);
          }
        }
      }, 100);
    }
  },
};

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

        // 优先使用从表单API获取的值（最新的），如果没有则使用传入的formValues
        const finalFormValues = { ...formValues, ...currentFormValues };

        const currentPlatform = finalFormValues?.ioTPlatform;
        const currentProductId = finalFormValues?.ioTPlatformProductId;

        // 即使没有产品ID或平台，也触发查询（让后端处理参数验证）
        try {
          // 构建查询参数
          const queryParams: any = {
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
          };

          // 添加搜索关键词
          if (finalFormValues?.SearchKeyWords) {
            queryParams.searchKeyWords = finalFormValues.SearchKeyWords;
          }

          // 添加平台参数（必须）
          if (currentPlatform) {
            queryParams.ioTPlatform = Number.parseInt(
              String(currentPlatform),
            ) as 1 | 2;
          }

          // 添加产品ID参数（必须）
          if (currentProductId) {
            queryParams.ioTPlatformProductId = String(currentProductId);
          }

          // 添加访问模式参数
          if (finalFormValues?.accessMode) {
            queryParams.accessMode = finalFormValues.accessMode;
          }

          // 添加标识符类型参数
          if (
            finalFormValues?.identifierType !== undefined &&
            finalFormValues?.identifierType !== null
          ) {
            queryParams.identifierType = Number.parseInt(
              String(finalFormValues.identifierType),
            ) as 1 | 2;
          }

          const { data } = await postIoTplatformThingModelInfoPageAsync({
            body: queryParams,
          });
          // 更新数据状态，检查是否有数据
          hasData.value = data?.items && data.items.length > 0;
          return data || { items: [], totalCount: 0 };
        } catch (error) {
          console.error('查询物模型信息失败:', error);
          hasData.value = false;
          return {
            items: [],
            totalCount: 0,
          };
        }
      },
    },
  },
};

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

const editRow: Record<string, any> = ref({});

// 跟踪数据状态，用于控制按钮显示
const hasData = ref(true);
// 模型刷新按钮 loading 状态
const thingModelRefreshLoading = ref(false);
// 导出/导入按钮 loading 状态
const exportLoading = ref(false);
const importLoading = ref(false);
// 导入文件选择框引用（隐藏 input）
const importFileInputRef = ref<HTMLInputElement | null>(null);

const [ThingModelModal, thingModelModalApi] = useVbenModal({
  draggable: true,
  footer: true,
  showCancelButton: true,
  showConfirmButton: true,
  onConfirm: submit,
  onBeforeClose: () => {
    return true;
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      // 打开弹窗时，设置平台和产品ID到表单中（用于下拉框依赖）
      await nextTick();
      const formApi = editRow.value.id ? editFormApi : addFormApi;
      const isEdit = !!editRow.value.id;

      // 编辑时从选中对象获取，新增时从搜索表单获取
      let platformValue: 1 | 2;
      let productIdValue: string;
      let filedTypeValue: string | undefined;

      if (isEdit) {
        // 编辑时从 editRow.value 获取
        platformValue = editRow.value.ioTPlatform
          ? ((typeof editRow.value.ioTPlatform === 'string'
            ? Number.parseInt(editRow.value.ioTPlatform)
            : editRow.value.ioTPlatform) as 1 | 2)
          : (Number.parseInt(ioTPlatform.value) as 1 | 2);
        productIdValue = editRow.value.ioTPlatformProductId || productId.value;
        filedTypeValue = editRow.value.filedType;
      } else {
        // 新增时从搜索表单获取最新的值
        const formValues = gridApi?.formApi
          ? await gridApi.formApi.getValues()
          : {};
        platformValue = formValues.ioTPlatform
          ? ((typeof formValues.ioTPlatform === 'string'
            ? Number.parseInt(formValues.ioTPlatform)
            : formValues.ioTPlatform) as 1 | 2)
          : (Number.parseInt(ioTPlatform.value) as 1 | 2);
        productIdValue = formValues.ioTPlatformProductId || productId.value;

        // 同步更新响应式变量
        if (formValues.ioTPlatform) {
          ioTPlatform.value = String(formValues.ioTPlatform);
        }
        if (formValues.ioTPlatformProductId) {
          productId.value = String(formValues.ioTPlatformProductId);
        }
      }

      console.log('设置表单值:', {
        isEdit,
        platformValue,
        productIdValue,
        filedTypeValue,
        editRowValue: isEdit ? editRow.value : null,
      });

      await formApi.setValues({
        ...(isEdit ? editRow.value : {}),
        ...(isEdit && {
          standardFieldFieldExtension: formatFieldExtensionForForm(
            editRow.value.standardFieldFieldExtension,
          ),
          ioTPlatformRawFieldExtension: formatFieldExtensionForForm(
            editRow.value.ioTPlatformRawFieldExtension,
          ),
        }),
        _ioTPlatform: platformValue,
        _ioTPlatformProductId: productIdValue,
        // 确保 identifierType 转换为字符串格式，以便与下拉框的 key 匹配
        ...(isEdit &&
        editRow.value.identifierType !== undefined &&
        editRow.value.identifierType !== null && {
          identifierType: String(editRow.value.identifierType),
        }),
      });

      // 手动触发平台物模型编码字段的重新加载
      setTimeout(async () => {
        // 如果是新增，尝试从表单值中获取 filedType（可能用户已经选择了）
        if (!isEdit) {
          const currentFormValues = await formApi.getValues();
          filedTypeValue = currentFormValues.filedType || filedTypeValue;
        }
        const fieldRef = formApi.getFieldComponentRef(
          'ioTPlatformRawFieldName',
        );
        if (fieldRef && typeof fieldRef.updateParam === 'function') {
          fieldRef.updateParam({
            body: {
              ioTPlatformType: platformValue,
              ioTPlatformProductId: productIdValue,
              ...(filedTypeValue ? { filedType: String(filedTypeValue) } : {}),
            },
          });
        }
      }, 100);
    }
  },
  onCancel: () => {
    thingModelModalApi.close();
  },
});

const [CopyModal, copyModalApi] = useVbenModal({
  draggable: true,
  footer: true,
  showCancelButton: true,
  showConfirmButton: true,
  onConfirm: submitCopy,
  onBeforeClose: () => {
    return true;
  },
  onCancel: () => {
    copyModalApi.close();
  },
});

// 复制标准模型弹窗
const [CopyStandardModal, copyStandardModalApi] = useVbenModal({
  draggable: true,
  footer: true,
  showCancelButton: true,
  showConfirmButton: true,
  onConfirm: submitCopyStandard,
  onBeforeClose: () => {
    return true;
  },
  onCancel: () => {
    copyStandardModalApi.close();
  },
});

type OperateServiceItem = {
  key?: null | string;
  value?: null | string;
  secondValue?: null | string;
  thirdValue?: unknown;
};

const commandEditRow = ref<Record<string, any>>({});
const operateServiceLoading = ref(false);
const createCommandLoading = ref(false);
const operateServiceOptions = ref<OperateServiceItem[]>([]);
const operateTypeOptions = ref<Array<{ label: string; value: number }>>([]);
const selectedOperateType = ref<number>();
const operateIssueCommandText = ref('');

function normalizeOperateTypeOptions(
  raw: unknown,
): Array<{ label: string; value: number }> {
  if (raw == null || raw === '') {
    return [];
  }

  let data: unknown = raw;
  if (typeof data === 'string') {
    const s = data.trim();
    if (!s) {
      return [];
    }
    try {
      data = JSON.parse(s) as unknown;
    } catch {
      return [];
    }
  }

  if (Array.isArray(data)) {
    return data
      .map((item: any) => {
        const valueRaw = item?.key ?? item?.value ?? item?.id ?? item?.operateType;
        const labelRaw =
          item?.value ??
          item?.label ??
          item?.name ??
          item?.displayName ??
          item?.key;
        const value = Number.parseInt(String(valueRaw ?? ''), 10);
        if (Number.isNaN(value)) {
          return null;
        }
        return {
          value,
          label: String(labelRaw ?? value),
        };
      })
      .filter(Boolean) as Array<{ label: string; value: number }>;
  }

  if (typeof data === 'object') {
    return Object.entries(data as Record<string, unknown>)
      .map(([k, v]) => {
        const value = Number.parseInt(String(k), 10);
        if (Number.isNaN(value)) {
          return null;
        }
        return {
          value,
          label: String(v ?? k),
        };
      })
      .filter(Boolean) as Array<{ label: string; value: number }>;
  }

  return [];
}

const [OperateCommandModal, operateCommandModalApi] = useVbenModal({
  draggable: true,
  footer: true,
  showCancelButton: true,
  showConfirmButton: true,
  confirmText: '添加',
  onConfirm: submitOperateCommand,
  onBeforeClose: () => {
    commandEditRow.value = {};
    operateServiceOptions.value = [];
    operateTypeOptions.value = [];
    selectedOperateType.value = undefined;
    operateIssueCommandText.value = '';
    createCommandLoading.value = false;
    return true;
  },
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) {
      return;
    }
    await fetchOperateServiceOptions();
  },
});

// 创建新增表单 schema（传入获取平台和产品ID的函数，作为后备方案）
// 注意：实际使用时，值会从表单的 _ioTPlatform 和 _ioTPlatformProductId 字段获取
const addThingModelFormSchema = getAddThingModelFormSchema(
  () => {
    // 作为后备方案，返回响应式变量的值
    return ioTPlatform.value
      ? (Number.parseInt(ioTPlatform.value) as 1 | 2)
      : undefined;
  },
  () => {
    // 作为后备方案，返回响应式变量的值
    return productId.value || undefined;
  },
);

const [AddForm, addFormApi] = useVbenForm({
  collapsed: false,
  commonConfig: {
    labelWidth: 150,
    labelClass: 'whitespace-nowrap',
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: addThingModelFormSchema.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

// 创建编辑表单 schema（传入获取平台和产品ID的函数，编辑时从 editRow 获取）
const editThingModelFormSchema = getEditThingModelFormSchema(
  () => {
    // 编辑时优先从 editRow 获取
    if (editRow.value?.ioTPlatform) {
      return typeof editRow.value.ioTPlatform === 'string'
        ? Number.parseInt(editRow.value.ioTPlatform)
        : editRow.value.ioTPlatform;
    }
    // 如果没有，使用响应式变量
    return ioTPlatform.value
      ? (Number.parseInt(ioTPlatform.value) as 1 | 2)
      : undefined;
  },
  () => {
    // 编辑时优先从 editRow 获取
    return editRow.value?.ioTPlatformProductId || productId.value || undefined;
  },
);

const [EditForm, editFormApi] = useVbenForm({
  collapsed: false,
  commonConfig: {
    labelWidth: 150,
    labelClass: 'whitespace-nowrap',
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: editThingModelFormSchema.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [CopyForm, copyFormApi] = useVbenForm({
  collapsed: false,
  commonConfig: {
    labelWidth: 110,
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: copyThingModelFormSchema.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

// 复制标准模型表单（多选物模型类型）
const [CopyStandardForm, copyStandardFormApi] = useVbenForm({
  collapsed: false,
  commonConfig: {
    labelWidth: 160,
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: copyStandardThingModelFormSchema.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
});

// 监听路由参数变化，自动加载数据
watch(
  () => [route.query.productId, route.query.ioTPlatform],
  async ([newProductId, newIoTPlatform]) => {
    if (newProductId) {
      productId.value = newProductId as string;
    }
    if (newIoTPlatform) {
      ioTPlatform.value = newIoTPlatform as string;
    }
    if (route.query.productName) {
      productName.value = route.query.productName as string;
    }

    // 延迟执行，确保组件完全初始化
    if (gridApi) {
      setTimeout(async () => {
        try {
          await gridApi.reload();
        } catch (error) {
          console.error('加载数据时出错:', error);
        }
      }, 100);
    }
  },
  { immediate: false },
);

// 页面初始化时加载数据
onMounted(async () => {
  // 加载标识符类型选项
  await loadIdentifierTypeOptions();

  // 从路由参数初始化
  if (route.query.productId) {
    productId.value = route.query.productId as string;
  }
  if (route.query.productName) {
    productName.value = route.query.productName as string;
  }
  if (route.query.ioTPlatform) {
    ioTPlatform.value = route.query.ioTPlatform as string;
  }

  // 延迟加载数据，确保表格已初始化
  // 即使没有 productId，也要触发一次查询，让表格显示空白状态
  await nextTick();
  setTimeout(async () => {
    if (gridApi && gridApi.reload) {
      try {
        // 设置表单值（如果有路由参数）
        const formValues = await gridApi.formApi.getValues();
        if (route.query.ioTPlatform && !formValues.ioTPlatform) {
          await gridApi.formApi.setValues({
            ioTPlatform: route.query.ioTPlatform,
          });
        }
        if (route.query.productId && !formValues.ioTPlatformProductId) {
          await gridApi.formApi.setValues({
            ioTPlatformProductId: route.query.productId,
          });
        }
        await nextTick();
        // 无论是否有参数，都触发查询
        await gridApi.reload();
      } catch (error) {
        console.error('初始化加载数据时出错:', error);
      }
    }
  }, 300);
});

function normalizeFieldExtensionValue(fieldValue: unknown) {
  if (typeof fieldValue !== 'string') {
    return fieldValue;
  }
  const trimmed = fieldValue.trim();
  if (!trimmed) {
    return '';
  }
  try {
    return JSON.parse(trimmed);
  } catch {
    return fieldValue;
  }
}

function normalizeObjectJsonFieldForSubmit(
  fieldValue: unknown,
): null | Record<string, unknown> {
  if (fieldValue == null) {
    return null;
  }
  if (typeof fieldValue === 'string') {
    const trimmed = fieldValue.trim();
    if (!trimmed) {
      return null;
    }
    try {
      const parsed = JSON.parse(trimmed);
      if (parsed == null) {
        return null;
      }
      if (typeof parsed === 'object' && !Array.isArray(parsed)) {
        return parsed as Record<string, unknown>;
      }
      return null;
    } catch {
      return null;
    }
  }
  if (typeof fieldValue === 'object' && !Array.isArray(fieldValue)) {
    return fieldValue as Record<string, unknown>;
  }
  return null;
}

function formatFieldExtensionForForm(fieldValue: unknown) {
  if (fieldValue == null || fieldValue === '') {
    return '';
  }
  if (typeof fieldValue === 'string') {
    return fieldValue;
  }
  try {
    return JSON.stringify(fieldValue, null, 2);
  } catch {
    return String(fieldValue);
  }
}

function parseJsonFieldValue(
  fieldValue: unknown,
  fieldLabel: string,
): { ok: boolean; value: unknown } {
  if (fieldValue == null || fieldValue === '') {
    return { ok: true, value: fieldValue };
  }

  if (typeof fieldValue !== 'string') {
    return { ok: true, value: fieldValue };
  }

  const trimmed = fieldValue.trim();
  if (!trimmed) {
    return { ok: true, value: '' };
  }

  try {
    return {
      ok: true,
      value: JSON.parse(trimmed),
    };
  } catch {
    Message.error(`${fieldLabel}必须是合法JSON格式`);
    return { ok: false, value: fieldValue };
  }
}

// 新增和编辑提交的逻辑
async function submit() {
  const isEdit = !!editRow.value.id;
  const formApi = isEdit ? editFormApi : addFormApi;
  const api = isEdit
    ? postIoTplatformThingModelInfoUpdateAsync
    : postIoTplatformThingModelInfoCreateAsync;
  const { valid } = await formApi.validate();
  if (!valid) return;
  const formValues = await formApi.getValues();

  // 获取产品ID：优先从搜索表单获取最新值，如果没有则使用响应式变量，编辑时也可以从编辑行数据获取
  let finalProductId: string | undefined;
  if (isEdit && editRow.value.ioTPlatformProductId) {
    // 编辑时优先使用编辑行数据中的产品ID
    finalProductId = String(editRow.value.ioTPlatformProductId);
  } else {
    // 新增或编辑时，从搜索表单获取最新的产品ID
    const searchFormValues = gridApi?.formApi
      ? await gridApi.formApi.getValues()
      : {};
    // 新增弹窗里会保存 _ioTPlatformProductId，作为重要兜底，避免搜索表单值丢失导致未传产品ID
    finalProductId =
      formValues._ioTPlatformProductId ||
      searchFormValues.ioTPlatformProductId || productId.value || undefined;
    if (finalProductId) {
      finalProductId = String(finalProductId);
    }
  }

  // 检查是否有产品ID
  if (!finalProductId) {
    Message.error('产品ID不存在，无法保存物模型信息');
    return;
  }

  // 获取平台类型：优先从搜索表单获取最新值，如果没有则使用响应式变量，编辑时也可以从编辑行数据获取
  let finalPlatform: 1 | 2;
  if (isEdit && editRow.value.ioTPlatform) {
    // 编辑时优先使用编辑行数据中的平台类型
    finalPlatform =
      typeof editRow.value.ioTPlatform === 'string'
        ? (Number.parseInt(editRow.value.ioTPlatform) as 1 | 2)
        : editRow.value.ioTPlatform;
  } else {
    // 新增或编辑时，从搜索表单获取最新的平台类型
    const searchFormValues = gridApi?.formApi
      ? await gridApi.formApi.getValues()
      : {};
    const platformValue =
      formValues._ioTPlatform ||
      searchFormValues.ioTPlatform ||
      ioTPlatform.value ||
      '2';
    finalPlatform = Number.parseInt(String(platformValue)) as 1 | 2;
  }

  const ioTPlatformRawFieldExtensionParsed = parseJsonFieldValue(
    formValues.ioTPlatformRawFieldExtension,
    '平台物模型值类型扩展',
  );
  if (!ioTPlatformRawFieldExtensionParsed.ok) {
    return;
  }

  // 提交前移除仅供前端联动的临时字段，避免影响后端绑定
  const { _ioTPlatform, _ioTPlatformProductId, ...cleanFormValues } = formValues;

  const fetchParams: any = {
    ...cleanFormValues,
    // 自动添加平台和产品信息
    ioTPlatform: String(finalPlatform),
    ioTPlatformProductId: finalProductId,
    // 枚举按字符串值提交（如 "1" / "2"）
    ...(formValues.identifierType !== undefined &&
    formValues.identifierType !== null && {
      identifierType: String(formValues.identifierType),
    }),
    // 编辑时需要添加ID
    ...(isEdit && { id: editRow.value.id }),
    // 两个扩展字段必须传可映射的 JSON；空值统一传 "{}"
    standardFieldFieldExtension: normalizeObjectJsonFieldForSubmit(
      normalizeFieldExtensionValue(formValues.standardFieldFieldExtension),
    ),
    ioTPlatformRawFieldExtension: normalizeObjectJsonFieldForSubmit(
      ioTPlatformRawFieldExtensionParsed.value,
    ),
  };

  try {
    const resp = await api({ body: fetchParams });
    if (resp.data) {
      Message.success(
        editRow.value.id ? $t('common.editSuccess') : $t('common.addSuccess'),
      );
      thingModelModalApi.close();
      editRow.value = {};
      gridApi.reload();
    } else {
      Message.error(
        editRow.value.id ? $t('common.editFail') : $t('common.addFail'),
      );
    }
  } catch (error) {
    console.error('提交失败:', error);
  }
}

async function onEdit(record: any) {
  editRow.value = record;
  // 编辑时从选中对象获取平台和产品ID
  const platformValue = record.ioTPlatform
    ? ((typeof record.ioTPlatform === 'string'
      ? Number.parseInt(record.ioTPlatform)
      : record.ioTPlatform) as 1 | 2)
    : (Number.parseInt(ioTPlatform.value) as 1 | 2);
  const productIdValue = record.ioTPlatformProductId || productId.value;
  const filedTypeValue = record.filedType;

  thingModelModalApi.open();
  await nextTick();
  setTimeout(async () => {
    await editFormApi.setValues({
      ...record,
      standardFieldFieldExtension: formatFieldExtensionForForm(
        record.standardFieldFieldExtension,
      ),
      ioTPlatformRawFieldExtension: formatFieldExtensionForForm(
        record.ioTPlatformRawFieldExtension,
      ),
      _ioTPlatform: platformValue,
      _ioTPlatformProductId: productIdValue,
      // 确保 identifierType 转换为字符串格式，以便与下拉框的 key 匹配
      ...(record.identifierType !== undefined &&
      record.identifierType !== null && {
        identifierType: String(record.identifierType),
      }),
    });

    // 手动触发平台物模型编码字段的重新加载
    const fieldRef = editFormApi.getFieldComponentRef(
      'ioTPlatformRawFieldName',
    );
    if (fieldRef && typeof fieldRef.updateParam === 'function') {
      fieldRef.updateParam({
        body: {
          ioTPlatformType: platformValue,
          ioTPlatformProductId: productIdValue,
          ...(filedTypeValue ? { filedType: String(filedTypeValue) } : {}),
        },
      });
    }
  }, 100);
}

const openAddModal = async () => {
  editRow.value = {};
  // 打开新增弹窗时，从搜索表单中获取平台和产品ID（确保是最新的值）
  const formValues = gridApi?.formApi ? await gridApi.formApi.getValues() : {};
  const platformValue = formValues.ioTPlatform
    ? ((typeof formValues.ioTPlatform === 'string'
      ? Number.parseInt(formValues.ioTPlatform)
      : formValues.ioTPlatform) as 1 | 2)
    : (Number.parseInt(ioTPlatform.value) as 1 | 2);
  const productIdValue = formValues.ioTPlatformProductId || productId.value;

  // 更新响应式变量（保持同步）
  if (formValues.ioTPlatform) {
    ioTPlatform.value = String(formValues.ioTPlatform);
  }
  if (formValues.ioTPlatformProductId) {
    productId.value = String(formValues.ioTPlatformProductId);
  }

  thingModelModalApi.open();
  // 确保值已设置
  await nextTick();
  setTimeout(async () => {
    await addFormApi.setValues({
      _ioTPlatform: platformValue,
      _ioTPlatformProductId: productIdValue,
    });

    // 手动触发平台物模型编码字段的重新加载
    // 尝试从表单值中获取 filedType（可能用户已经选择了）
    const currentFormValues = await addFormApi.getValues();
    const filedTypeValue = currentFormValues.filedType;
    const fieldRef = addFormApi.getFieldComponentRef('ioTPlatformRawFieldName');
    if (fieldRef && typeof fieldRef.updateParam === 'function') {
      fieldRef.updateParam({
        body: {
          ioTPlatformType: platformValue,
          ioTPlatformProductId: productIdValue,
          ...(filedTypeValue ? { filedType: String(filedTypeValue) } : {}),
        },
      });
    }
  }, 100);
};

async function fetchOperateServiceOptions() {
  if (!commandEditRow.value?.ioTPlatformProductId) {
    Message.warning('当前物模型数据缺少产品ID，无法加载可操作指令');
    return;
  }
  if (!commandEditRow.value?.standardFieldName) {
    Message.warning('当前物模型数据缺少标准物模型标识符，无法加载可操作指令');
    return;
  }

  operateServiceLoading.value = true;
  try {
    const { data } = await postIoTplatformThingModelInfoGetIoTplatformThingModelService(
      {
        body: {
          id: String(commandEditRow.value.ioTPlatformProductId),
          standardFieldName: String(commandEditRow.value.standardFieldName),
          isGetOperateService: true,
        },
      },
    );
    operateServiceOptions.value = Array.isArray(data)
      ? (data as OperateServiceItem[])
      : [];
    const firstService = operateServiceOptions.value[0];
    operateTypeOptions.value = normalizeOperateTypeOptions(
      firstService?.secondValue,
    );
    selectedOperateType.value =
      operateTypeOptions.value.length > 0
        ? operateTypeOptions.value[0]?.value
        : undefined;
    if (operateServiceOptions.value.length === 0) {
      Message.warning('当前属性标识符暂无可操作指令');
    }
  } catch (error) {
    console.error('获取可操作指令列表失败:', error);
    Message.error('获取可操作指令列表失败');
    operateServiceOptions.value = [];
    operateTypeOptions.value = [];
    selectedOperateType.value = undefined;
  } finally {
    operateServiceLoading.value = false;
  }
}

function openOperateCommandModal(record: Record<string, any>) {
  if (!record?.id) {
    Message.warning('当前物模型数据缺少ID，无法添加默认操作指令');
    return;
  }
  const filedType = String(record?.filedType ?? '');
  if (!filedType.includes('Service')) {
    Message.warning('仅服务类型物模型支持添加默认操作指令');
    return;
  }
  commandEditRow.value = record;
  operateCommandModalApi.open();
}

async function submitOperateCommand() {
  if (!commandEditRow.value?.id) {
    return;
  }
  if (selectedOperateType.value == null) {
    Message.warning('请选择操作类型');
    return;
  }

  let issueCommand = operateIssueCommandText.value.trim();
  if (!issueCommand) {
    Message.warning('请填写指令内容');
    return;
  }

  createCommandLoading.value = true;
  try {
    const resp =
      await postIoTplatformThingModelInfoCreateIoTplatformThingModelCommand({
        body: {
          thingModelDataId: String(commandEditRow.value.id),
          operateType: selectedOperateType.value,
          issueCommand,
        },
      });
    if (resp.data) {
      Message.success('默认操作指令添加成功');
      operateCommandModalApi.close();
      await gridApi.reload();
    } else {
      Message.error('默认操作指令添加失败');
    }
  } catch (error) {
    console.error('默认操作指令添加失败:', error);
    Message.error('默认操作指令添加失败');
  } finally {
    createCommandLoading.value = false;
  }
}

// 模型刷新
async function onThingModelRefresh() {
  const formValues = gridApi?.formApi ? await gridApi.formApi.getValues() : {};
  const platformValue = formValues.ioTPlatform || ioTPlatform.value;
  const productIdValue = formValues.ioTPlatformProductId || productId.value;

  if (!productIdValue) {
    Message.error('请选择产品后再刷新模型');
    return;
  }

  const ioTPlatformType = Number.parseInt(String(platformValue || ''), 10);
  if (Number.isNaN(ioTPlatformType)) {
    Message.error('平台类型无效，无法刷新模型');
    return;
  }

  thingModelRefreshLoading.value = true;
  try {
    const resp =
      await postAggregationIoTplatformUpdateIoTplatformProductThingModelInfoAsync(
        {
          body: {
            ioTPlatformType,
            ioTPlatformProductId: String(productIdValue),
          },
        },
      );
    if (resp.data) {
      Message.success('模型刷新成功');
      await gridApi.reload();
    } else {
      Message.error('模型刷新失败');
    }
  } catch (error) {
    console.error('模型刷新失败:', error);
    Message.error('模型刷新失败');
  } finally {
    thingModelRefreshLoading.value = false;
  }
}

// 获取当前搜索表单中的平台/产品（导出、导入共用）
async function getCurrentPlatformAndProduct() {
  const formValues = gridApi?.formApi ? await gridApi.formApi.getValues() : {};
  const currentProductId = String(
    formValues.ioTPlatformProductId || productId.value || '',
  );
  const platformNum =
    Number.parseInt(
      String(formValues.ioTPlatform || ioTPlatform.value || '2'),
      10,
    ) || 2;
  return { currentProductId, platformNum };
}

// 导出当前产品的平台端物模型 JSON
async function onExportThingModel() {
  const { currentProductId, platformNum } =
    await getCurrentPlatformAndProduct();
  if (!currentProductId) {
    Message.error('请先选择产品再导出');
    return;
  }
  if (!hasData.value) {
    Message.error('当前产品暂无可导出的平台端物模型');
    return;
  }

  exportLoading.value = true;
  try {
    const { data } = await postIoTplatformThingModelInfoExportPlatformThingModel(
      {
        // 后端复杂入参按 body 绑定（生成的 query.input 为 nswag 产物）
        body: {
          ioTPlatformProductId: currentProductId,
          platform: platformNum,
        },
        responseType: 'blob',
      },
    );
    const url = window.URL.createObjectURL(new Blob([data as Blob]));
    const link = document.createElement('a');
    link.href = url;
    const now = new Date();
    const pad = (n: number) => String(n).padStart(2, '0');
    const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
    link.setAttribute(
      'download',
      `平台端物模型_${currentProductId}_${stamp}.json`,
    );
    document.body.append(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
    Message.success('导出成功');
  } catch (error) {
    console.error('导出平台端物模型失败:', error);
    Message.error('导出失败，请确认该产品已配置平台端物模型');
  } finally {
    exportLoading.value = false;
  }
}

// 触发隐藏文件选择框
function triggerImportThingModel() {
  if (!productId.value) {
    Message.error('请先选择导入目标产品');
    return;
  }
  importFileInputRef.value?.click();
}

// 选择文件后执行导入
async function onImportThingModelFileChange(e: Event) {
  const input = e.target as HTMLInputElement;
  const file = input.files?.[0];
  // 重置 input 值，保证同一文件可再次选择触发 change
  input.value = '';
  if (!file) {
    return;
  }

  const { currentProductId, platformNum } =
    await getCurrentPlatformAndProduct();
  if (!currentProductId) {
    Message.error('请先选择导入目标产品');
    return;
  }

  importLoading.value = true;
  try {
    const { data } = await postIoTplatformThingModelInfoImportPlatformThingModel(
      {
        query: {
          ioTPlatformProductId: currentProductId,
          platform: platformNum as any,
        },
        body: { file },
      },
    );
    if (data?.success) {
      Message.success(
        `导入成功：物模型 ${data.thingModelCount ?? 0} 条、扩展 ${data.extensionCount ?? 0} 条、指令 ${data.commandCount ?? 0} 条`,
      );
      await gridApi.reload();
    } else {
      Message.error('导入失败');
    }
  } catch (error) {
    // 具体失败原因（如目标产品不存在、文件解析失败）由全局错误拦截器统一提示
    console.error('导入平台端物模型失败:', error);
  } finally {
    importLoading.value = false;
  }
}

// 打开复制已有模型模态框
const openCopyAnotherThingModelModal = async () => {
  console.log('打开复制模态框，当前参数:', {
    productId: productId.value,
    productName: productName.value,
    ioTPlatform: ioTPlatform.value,
  });
  copyModalApi.open();
};

// 复制提交逻辑
async function submitCopy() {
  // 检查是否有产品ID
  if (!productId.value) {
    Message.error('产品ID不存在，无法复制物模型信息');
    return;
  }

  const { valid } = await copyFormApi.validate();
  if (!valid) return;

  const formValues = await copyFormApi.getValues();

  console.log('复制提交参数:', {
    formValues,
    params: {
      productId: productId.value,
      productName: productName.value,
      ioTPlatform: ioTPlatform.value,
    },
  });

  try {
    const resp = await postIoTplatformThingModelInfoCopyAnotherThingModelAsync({
      body: {
        ioTPlatform: Number.parseInt(ioTPlatform.value) as 1 | 2,
        ioTPlatformProductId: productId.value,
        sourceProductId: formValues.ioTPlatformProductId,
      },
    });

    if (resp.data) {
      Message.success('复制模型成功');
      copyModalApi.close();
      gridApi.reload();
    } else {
      Message.error('复制模型失败');
    }
  } catch (error) {
    console.error('复制模型失败:', error);
  }
}

// 打开复制标准模型模态框（逻辑与“复制已有模型”保持一致）
const openCopyStandardThingModelModal = () => {
  console.log('打开复制标准模型模态框，当前参数:', {
    productId: productId.value,
    productName: productName.value,
    ioTPlatform: ioTPlatform.value,
  });
  copyStandardModalApi.open();
};

// 复制标准模型提交逻辑（带物模型类型多选）
async function submitCopyStandard() {
  // 检查是否有产品ID
  if (!productId.value) {
    Message.error('产品ID不存在，无法复制标准模型');
    return;
  }

  const { valid } = await copyStandardFormApi.validate();
  if (!valid) return;

  const formValues = await copyStandardFormApi.getValues();

  console.log('复制标准模型提交参数:', {
    formValues,
    params: {
      productId: productId.value,
      productName: productName.value,
      ioTPlatform: ioTPlatform.value,
    },
  });

  try {
    const resp = await postIoTplatformThingModelInfoCopyStandardThingModel({
      body: {
        ioTPlatform: Number.parseInt(ioTPlatform.value) as 1 | 2,
        ioTPlatformProductId: productId.value,
        // 按物模型类型多选复制（使用字段 filedTypes，值为字典 key 列表）
        filedTypes: formValues.filedTypes,
      },
    });
    if (resp.data) {
      Message.success('复制标准模型成功');
      copyStandardModalApi.close();
      gridApi.reload();
    } else {
      Message.error('复制标准模型失败');
    }
  } catch (error) {
    console.error('复制标准模型失败:', error);
  }
}

// 删除函数
async function onDel(record: any) {
  try {
    const resp = await postIoTplatformThingModelInfoDeleteAsync({
      body: { id: record.id },
    });
    if (resp.data) {
      Message.success($t('common.deleteSuccess'));
      gridApi.reload();
    } else {
      Message.error($t('common.deleteFail'));
    }
  } catch (error) {
    console.error('删除失败:', error);
  }
}

// 旧的“复制标准模型”直调接口函数已不再使用，保留逻辑由新的弹窗 + submitCopyStandard 代替
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <TableAction :actions="[
          {
            label: $t('common.add'),
            type: 'primary',
            icon: 'ant-design:plus-outlined',
            onClick: openAddModal.bind(null),
            auth: ['AbpIdentity.Users.Create'],
            disabled: !productId,
          },
          {
            label: $t('abp.thingModelInfos.copyStandardThingModel'),
            type: 'default',
            icon: 'ant-design:copy-outlined',
            onClick: openCopyStandardThingModelModal,
            auth: ['AbpIdentity.Users.Create'],
            disabled: !productId,
          },
          {
            label: $t('abp.thingModelInfos.copyAnotherThingModelModal'),
            type: 'default',
            icon: 'ant-design:copy-outlined',
            onClick: openCopyAnotherThingModelModal,
            auth: ['AbpIdentity.Users.Create'],
            ifShow: !hasData,
            disabled: !productId,
          },
          {
            label: '模型刷新',
            type: 'default',
            icon: 'ant-design:reload-outlined',
            onClick: onThingModelRefresh,
            auth: ['AbpIdentity.Users.Create'],
            disabled: !productId,
            loading: thingModelRefreshLoading,
          },
          {
            label: '导出JSON',
            type: 'default',
            icon: 'ant-design:download-outlined',
            onClick: onExportThingModel,
            auth: ['AbpIdentity.Users.Create'],
            disabled: !productId,
            loading: exportLoading,
          },
          {
            label: '导入JSON',
            type: 'default',
            icon: 'ant-design:upload-outlined',
            onClick: triggerImportThingModel,
            auth: ['AbpIdentity.Users.Create'],
            disabled: !productId,
            loading: importLoading,
          },
        ]" />
      </template>

      <template #isValueNeedConvert="{ row }">
        <component :is="h(
          Tag,
          { color: row.isValueNeedConvert ? 'blue' : 'default' },
          () => (row.isValueNeedConvert ? '是' : '否'),
        )
          " />
      </template>

      <template #accessMode="{ row }">
        <component :is="h(
          Tag,
          {
            color:
              row.accessMode === 'rw'
                ? 'green'
                : row.accessMode === 'r'
                  ? 'orange'
                  : row.accessMode === 'w'
                    ? 'red'
                    : 'default',
          },
          () =>
            row.accessMode === 'rw'
              ? '读写模式'
              : row.accessMode === 'r'
                ? '只读模式'
                : row.accessMode === 'w'
                  ? '只写模式'
                  : '-',
        )
          " />
      </template>

      <template #identifierType="{ row }">
        {{ identifierTypeMap[row.identifierType] || '-' }}
      </template>

      <template #action="{ row }">
        <TableAction :actions="[
          {
            label: $t('common.edit'),
            type: 'link',
            size: 'small',
            auth: ['AbpIdentity.Users.Update'],
            onClick: onEdit.bind(null, row),
          },
          {
            label: $t('common.delete'),
            icon: 'ant-design:delete-outlined',
            type: 'link',
            size: 'small',
            auth: ['AbpIdentity.Users.Delete'],
            popConfirm: {
              title: $t('common.askConfirmDelete'),
              confirm: onDel.bind(null, row),
            },
          },
          {
            label: '指令',
            type: 'link',
            size: 'small',
            auth: ['AbpIdentity.Users.Update'],
            ifShow: String(row.filedType ?? '').includes('Service'),
            onClick: openOperateCommandModal.bind(null, row),
          },
        ]" />
      </template>
    </Grid>
    <!-- 隐藏的导入文件选择框 -->
    <input
      ref="importFileInputRef"
      type="file"
      accept=".json,application/json"
      style="display: none"
      @change="onImportThingModelFileChange"
    />

    <ThingModelModal :title="editRow.id ? $t('common.edit') : $t('common.add')" class="w-[800px]">
      <component :is="editRow.id ? EditForm : AddForm" />
    </ThingModelModal>

    <!-- 复制已有模型模态框 -->
    <CopyModal title="复制已有模型" class="w-[600px]">
      <CopyForm />
    </CopyModal>

    <!-- 复制标准模型（按物模型类型多选）模态框 -->
    <CopyStandardModal title="复制标准模型" class="w-[600px]">
      <CopyStandardForm />
    </CopyStandardModal>

    <OperateCommandModal title="默认操作指令添加" class="w-[640px]">
      <div v-if="operateServiceLoading" class="py-8 text-center text-gray-500">
        正在加载可操作指令列表...
      </div>
      <div v-else class="space-y-3">
        <div class="text-xs text-gray-500">
          属性标识符：{{ commandEditRow.ioTPlatformRawFieldName || '-' }}
        </div>
        <div class="flex items-center gap-2">
          <span class="w-24 flex-shrink-0 text-right text-sm text-gray-600">操作类型</span>
          <Select
            v-model:value="selectedOperateType"
            :options="operateTypeOptions"
            allow-clear
            class="min-w-0 flex-1"
            placeholder="请选择操作类型"
            size="small"
          />
        </div>
        <div class="space-y-1">
          <div class="text-sm font-medium text-gray-700">指令内容</div>
          <Input.TextArea
            v-model:value="operateIssueCommandText"
            :rows="4"
            placeholder="请输入默认操作指令内容"
          />
        </div>
      </div>
      <template #footer>
        <div class="flex w-full items-center justify-end gap-2">
          <Button @click="operateCommandModalApi.close()">
            {{ $t('common.cancel') }}
          </Button>
          <Button
            type="primary"
            :loading="createCommandLoading"
            :disabled="operateServiceLoading"
            @click="submitOperateCommand"
          >
            添加
          </Button>
        </div>
      </template>
    </OperateCommandModal>
  </Page>
</template>
