<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { message } from 'ant-design-vue';

import ConfirmModal from '@/components/ConfirmModal.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import {
  addDeviceBind,
  equipmentDetails,
  getAllGatewayLinkProtocol,
  getAllGatewayList,
  getParamValueListAutomatic,
} from '@/api';

import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type { Key } from 'ant-design-vue/es/table/interface';
import type {
  AutomaticMatchingItem,
  CustomizationData,
  CustomParameters,
  DeviceGateways,
  DeviceParamGroupRels,
  DeviceParamGroups,
  EquipmentInformationForm,
  GatewayDataItem,
  GroupingList,
  GroupItem,
  ListEquipmentParametersItem,
  PhysicalInterfaceList,
  SerialNumberItem,
  UseGuideStepItemExpose,
  UseGuideStepItemProps,
} from '@/types';

const columns = [
  {
    title: t('createDevice.gatewaySerialNumber'),
    dataIndex: 'snCode',
    key: 'snCode',
    ellipsis: true,
  },
  {
    title: t('createDevice.gatewayModel'),
    dataIndex: 'modelName',
    key: 'modelName',
    ellipsis: true,
  },
  {
    title: t('createDevice.physicalInterface'),
    dataIndex: 'linkName',
    key: 'linkName',
    ellipsis: true,
  },
  {
    title: t('createDevice.groupNumber'),
    dataIndex: 'groupNumber',
    key: 'groupNumber',
    ellipsis: true,
  },

  {
    title: t('createDevice.parameters'),
    key: 'tags',
    ellipsis: true,
  },
  {
    title: t('common.operation'),
    key: 'action',
    width: 80,
  },
];

const devColumns = [
  {
    title: t('createDevice.equipmentParameterCoding'),
    dataIndex: 'deviceParamCode',
    key: 'deviceParamCode',
    ellipsis: true,
  },
  {
    title: t('createDevice.equipmentParameterName'),
    dataIndex: 'deviceParamName',
    key: 'deviceParamName',
    ellipsis: true,
  },
  {
    title: t('createDevice.gatewayParameterEncoding'),
    dataIndex: 'gatewayParamCode',
    ellipsis: true,
  },
  {
    title: t('createDevice.gatewayParameterName'),
    dataIndex: 'gatewayParamName',
    ellipsis: true,
  },
  {
    title: t('setupProtocol.protocolParamFields.unit'),
    dataIndex: 'unit',
    ellipsis: true,
  },
  {
    title: t('createDevice.groupName'),
    dataIndex: 'groupId',
    key: 'groupId',
    ellipsis: true,
  },
  {
    title: t('createDevice.whetherProcessData'),
    dataIndex: 'isProcessData',
    key: 'isProcessData',
    ellipsis: true,
  },
  {
    title: t('common.operation'),
    key: 'action',
    width: 80,
  },
];

const customizationColumns = [
  {
    title: t('createDevice.equipmentSequenceNumber'),
    dataIndex: 'index',
    key: 'index',
    ellipsis: true,
  },
  {
    title: t('createDevice.equipmentParameterCoding'),
    dataIndex: 'deviceParamCode',
    key: 'deviceParamCode',
    ellipsis: true,
  },
  {
    title: t('createDevice.equipmentParameterName'),
    dataIndex: 'deviceParamName',
    key: 'deviceParamName',
    ellipsis: true,
  },
  {
    title: t('createDevice.customFormula'),
    dataIndex: 'customFormula',
    key: 'customFormula',
    ellipsis: true,
  },
  {
    title: t('setupProtocol.protocolParamFields.unit'),
    dataIndex: 'unit',
    key: 'unit',
    ellipsis: true,
  },
  {
    title: t('createDevice.keepDecimalPlaces'),
    dataIndex: 'decimalDigits',
    key: 'decimalDigits',
    ellipsis: true,
  },
  {
    title: t('createDevice.groupName'),
    dataIndex: 'paramGroupId',
    key: 'paramGroupId',
    ellipsis: true,
  },

  {
    title: t('createDevice.whetherProcessData'),
    dataIndex: 'isProcessData',
    key: 'isProcessData',
    ellipsis: true,
  },
  {
    title: t('common.operation'),
    dataIndex: 'action',
    key: 'action',
    width: 80,
  },
];

const protocolEquipmentColumns = [
  {
    title: t('common.serialNumber'),
    dataIndex: 'index',
    key: 'index',
    ellipsis: true,
    width: 60,
  },
  {
    title: t('createDevice.gatewayParameterEncoding'),
    dataIndex: 'gatewayParamCode',
    key: 'gatewayParamCode',
    ellipsis: true,
  },
  {
    title: t('setupProtocol.protocolParamFields.gatewayParamName'),
    dataIndex: 'gatewayParamName',
    key: 'gatewayParamName',
    ellipsis: true,
  },
];

const groupingColumns = [
  {
    title: t('createDevice.groupName'),
    dataIndex: 'groupName',
    key: 'groupName',
  },
  {
    title: t('common.operation'),
    dataIndex: 'action',
    key: 'action',
    width: 60,
  },
];

interface GatewayList {
  snCode: string;
  snCodeShow: boolean;
  modelName: string;
  modelNameShow: boolean;
  linkName: string;
  divId: number;
  linkId?: number;
  links: PhysicalInterfaceList[];
  linkLists: PhysicalInterfaceList[];
  groupNumber?: number;
  groupNumberShow: boolean;
  groupList: GroupItem[];
  groupNumberList: GroupItem[];
}

const modalGatewayRef = useTemplateRef('modalGateway');
const modalEquipmentRef = useTemplateRef('modalEquipment');
const modalCustomizationRef = useTemplateRef('modalCustomization');

const props = defineProps<UseGuideStepItemProps<EquipmentInformationForm>>();
const gatewayList = ref<GatewayList[]>([]);
const monitorAssociationGatewayList = ref<ListEquipmentParametersItem[]>([]);
const controlAssociationGatewayList = ref<ListEquipmentParametersItem[]>([]);
const paramValueListAutomaticData = ref<AutomaticMatchingItem[]>([]);

const groupingList = ref<GroupingList[]>([]);

const groupingDisplayList = ref<GroupingList[]>([]);

const deviceParamGroups = ref<DeviceParamGroups[]>([]);
const deviceGateways = ref<DeviceGateways[]>([]);
const deviceParamGroupRels = ref<DeviceParamGroupRels[]>([]);
const customizationData = ref<CustomizationData[]>([]);

const { handleRequest } = useRequest();

const listEquipmentParameters = ref<ListEquipmentParametersItem[]>([]);
const listAllEquipmentParameters = ref<ListEquipmentParametersItem[]>([]);
const remoteListEquipmentParameters = ref<ListEquipmentParametersItem[]>([]);
const remoteAllListEquipmentParameters = ref<ListEquipmentParametersItem[]>([]);
const monitorChooselistEquipment = ref<ListEquipmentParametersItem[]>([]);
const controlChooselistEquipment = ref<ListEquipmentParametersItem[]>([]);
const serialNumberItem = ref<SerialNumberItem[]>([]);
const monitorEquipmentLsit = ref<Key[]>([]);
const controlEquipmentLsit = ref<Key[]>([]);
const open = ref<boolean>(false);
const open1 = ref<boolean>(false);
const open2 = ref<boolean>(false);
const gatewayIndex = ref<number>(0);
const equipmentIndex = ref<number>(0);
const customizationIndex = ref<number>(0);

let gatewayId: number;

let linkId: number;
let groupNumberId: number;

const deviceId = props.form.devId;

const customParameters = ref<CustomParameters[]>([]);

const agreementKey = ref<string>('monitoring');
const agreementListKey = ref<string>('monitoring');

const monitorSearchContent = ref<string>('');
const controlSearchContent = ref<string>('');

const selectParameters = (value: number, id: number, groupNumber: number) => {
  listAllEquipmentParameters.value = [];
  listEquipmentParameters.value = [];
  monitorEquipmentLsit.value = [];
  monitorChooselistEquipment.value = [];
  remoteAllListEquipmentParameters.value = [];
  remoteListEquipmentParameters.value = [];
  controlEquipmentLsit.value = [];
  controlChooselistEquipment.value = [];
  monitorSearchContent.value = '';
  controlSearchContent.value = '';
  if (value) {
    if (groupNumber) {
      gatewayId = id;
      linkId = value;
      groupNumberId = groupNumber;
      postGatewayLinkProtocolList(value, id, 'monitor', groupNumber);
      postGatewayLinkProtocolList(value, id, 'control', groupNumber);
      obtainParamValueListAutomatic(value, groupNumber);
    } else {
      message.warning(t('createDevice.pleaseSelectGroupNumber'));
    }
  } else {
    message.warning(t('createDevice.pleasePhysicalInterface'));
  }
};

const queryReset = (value: string) => {
  if (value === 'monitor') {
    monitorSearchContent.value = '';
  } else if (value === 'control') {
    controlSearchContent.value = '';
  }
  fuzzyQuery(value);
};

const fuzzyQuery = (value: string) => {
  if (value === 'monitor') {
    listEquipmentParameters.value = listAllEquipmentParameters.value.filter((item) =>
      item.gatewayParamName.includes(monitorSearchContent.value),
    );
  } else if (value === 'control') {
    remoteListEquipmentParameters.value = remoteAllListEquipmentParameters.value.filter((item) =>
      item.gatewayParamName.includes(controlSearchContent.value),
    );
  }
};

const postGatewayLinkProtocolList = (linkId: number, id: number, monitorType: string, groupNumber: number) => {
  handleRequest(async () => {
    const records = await getAllGatewayLinkProtocol<GatewayDataItem[]>({
      linkId,
      monitorType,
      linkProtocolId: groupNumber,
      searchContent: monitorType === 'monitor' ? monitorSearchContent.value : controlSearchContent.value,
    });
    if (records.length) {
      if (monitorType === 'monitor') {
        records.forEach((item) => {
          listAllEquipmentParameters.value.push({
            ...item,
            deviceParamCode: item.platformParamCode,
            deviceParamName: item.platformParamName,
            groupId: undefined,
            groupSerialNum: 1,
            groupParamSerialNum: undefined,
            isProcessData: false,
            gatewayId: id,
            groupName: item.paramGroupName,
            groupIdShow: false,
            linkId,
            gatewayLinkProtocolId: groupNumber,
          });
        });
        fuzzyQuery('monitor');

        monitorAssociationGatewayList.value.forEach((item) => {
          if (id === item.gatewayId && linkId === item.linkId && groupNumber === item.gatewayLinkProtocolId) {
            monitorEquipmentLsit.value.push(item.id);
            monitorChooselistEquipment.value.push(item);
          }
        });
      } else if (monitorType === 'control') {
        records.forEach((item) => {
          remoteAllListEquipmentParameters.value.push({
            ...item,
            deviceParamCode: item.platformParamCode,
            deviceParamName: item.platformParamName,
            groupId: undefined,
            groupSerialNum: 1,
            groupParamSerialNum: undefined,
            isProcessData: false,
            gatewayId: id,
            groupName: item.paramGroupName,
            groupIdShow: false,
            linkId,
            gatewayLinkProtocolId: groupNumber,
          });
        });

        fuzzyQuery('control');

        controlAssociationGatewayList.value.forEach((item) => {
          if (id === item.gatewayId && linkId === item.linkId && groupNumber === item.gatewayLinkProtocolId) {
            controlEquipmentLsit.value.push(item.id);
            controlChooselistEquipment.value.push(item);
          }
        });
      }
    }
  });
};

const gatewayDelete = (divId: number, linkDeleteId: number, index: number, groupNumber: number) => {
  modalGatewayRef.value?.showView();
  gatewayIndex.value = index;
  gatewayId = divId;
  linkId = linkDeleteId;
  groupNumberId = groupNumber;
};

const customizationDelete = (index: number) => {
  modalCustomizationRef.value?.showView();
  customizationIndex.value = index;
};

const gatewayDevDelete = (index: number) => {
  modalEquipmentRef.value?.showView();
  equipmentIndex.value = index;
};

const handleOk = () => {
  if (monitorChooselistEquipment.value.length) {
    monitorAssociationGatewayList.value = mergeArrays(
      monitorAssociationGatewayList.value,
      monitorChooselistEquipment.value,
    );
  } else {
    monitorAssociationGatewayList.value = monitorAssociationGatewayList.value.filter(
      (item) =>
        !(item.gatewayId === gatewayId && item.linkId === linkId && item.gatewayLinkProtocolId === groupNumberId),
    );
  }

  if (controlChooselistEquipment.value.length) {
    controlAssociationGatewayList.value = mergeArrays(
      controlAssociationGatewayList.value,
      controlChooselistEquipment.value,
    );
  } else {
    controlAssociationGatewayList.value = controlAssociationGatewayList.value.filter(
      (item) =>
        !(item.gatewayId === gatewayId && item.linkId === linkId && item.gatewayLinkProtocolId === groupNumberId),
    );
  }

  const dataList = [...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value];

  groupingList.value = Array.from(new Set(dataList.map((item) => item.groupName))).map((groupName, index) => ({
    groupName,
    id: index,
  }));
  dataList.forEach((item) => {
    groupingList.value.forEach((i) => {
      if (item.groupName === i.groupName) {
        item.groupId = i.id;
      }
    });
  });
  open.value = false;
};

// 合并逻辑
const mergeArrays = (a: ListEquipmentParametersItem[], b: ListEquipmentParametersItem[]) => {
  // 找出b中所有的gatewayId和linkId组合
  const bCombinations = new Set(b.map((item) => `${item.gatewayId}-${item.linkId}-${item.gatewayLinkProtocolId}`));

  // 处理后的数组
  const result = [
    // 保留b中存在的项（gatewayId和linkId匹配的）
    ...b,
    // 保留a中gatewayId和linkId不在b中的项
    ...a.filter((item) => !bCombinations.has(`${item.gatewayId}-${item.linkId}-${item.gatewayLinkProtocolId}`)),
  ];

  return result;
};

const deleteAll = () => {
  if (agreementKey.value === 'monitoring') {
    monitorEquipmentLsit.value = [];
    monitorChooselistEquipment.value = [];
  } else {
    controlEquipmentLsit.value = [];
    controlChooselistEquipment.value = [];
  }
};

const addEquipment = (index: number) => {
  if (agreementKey.value === 'monitoring') {
    monitorEquipmentLsit.value.splice(index, 1);
    monitorChooselistEquipment.value.splice(index, 1);
  } else {
    controlEquipmentLsit.value.splice(index, 1);
    controlChooselistEquipment.value.splice(index, 1);
  }
};

const addGateway = () => {
  if (serialNumberItem.value.length) {
    const { links, id, snCode, modelName } = serialNumberItem.value[0];
    const { linkId: physicalId } = links[0];
    linkId = physicalId;

    gatewayId = id;
    gatewayList.value.push({
      snCode,
      modelName,
      linkName: '',
      divId: id,
      linkId: undefined,
      snCodeShow: false,
      modelNameShow: false,
      links,
      linkLists: links,
      groupNumber: undefined,
      groupNumberShow: false,
      groupList: [],
      groupNumberList: [],
    });
  }
};

const addCustomizationData = () => {
  customizationData.value.push({
    deviceParamCode: '',
    deviceParamName: '',
    customFormula: '',
    unit: '',
    decimalDigits: undefined,
    paramGroupId: groupingList.value.length ? groupingList.value[0].id : undefined,
    groupSerialNum: 1,
    groupParamSerialNum: undefined,
    isProcessData: false,
    paramNumShow: false,
    paramNameShow: false,
    customFormulaShow: false,
    unitShow: false,
    decimalDigitsShow: false,
    groupSerialNumShow: false,
    paramGroupIdShow: false,
    paramGroupName: groupingList.value.length ? groupingList.value[0].groupName : '',
  });
};

const customizationChange = (value: SelectValue, option: DefaultOptionType, index: number) => {
  customizationData.value[index].groupSerialNum = option.serialNum;
  customizationData.value[index].paramGroupName = option.groupName;
  customizationData.value[index].paramGroupIdShow = false;
};

const selectGrouping = (value: SelectValue, option: DefaultOptionType, index: number) => {
  if (agreementListKey.value === 'monitoring') {
    monitorAssociationGatewayList.value[index].groupSerialNum = option.serialNum;
    monitorAssociationGatewayList.value[index].groupName = option.groupName;
    monitorAssociationGatewayList.value[index].groupIdShow = false;
  } else {
    controlAssociationGatewayList.value[index].groupSerialNum = option.serialNum;
    controlAssociationGatewayList.value[index].groupName = option.groupName;
    controlAssociationGatewayList.value[index].groupIdShow = false;
  }
};

const serialNumberAdd = (value: SelectValue, option: DefaultOptionType, index: number) => {
  const { links, modelName, id } = option;

  gatewayList.value[index].snCodeShow = false;
  gatewayId = option.id;
  gatewayList.value[index].modelName = modelName;
  gatewayList.value[index].divId = id;

  gatewayList.value[index].links = links;
  gatewayList.value[index].linkLists = links;
  gatewayList.value[index].linkName = '';
  gatewayList.value[index].groupNumber = undefined;
  gatewayList.value[index].groupList = [];
  gatewayList.value[index].groupNumberList = [];
};

const obtainParamValueListAutomatic = (linkId: number, groupNumber: number) => {
  handleRequest(async () => {
    const { autoVos } = await getParamValueListAutomatic({
      linkId,
      deviceTypeId: Number(props.form.deviceType),
      deviceId,
      linkProtocolId: groupNumber,
    });

    paramValueListAutomaticData.value = autoVos;
    if (paramValueListAutomaticData.value.length) {
      open2.value = true;
    }
    open.value = true;
  });
};

const linkSwitch = (value: SelectValue, option: DefaultOptionType, index: number, divId: number) => {
  linkId = option.linkId;
  gatewayId = divId;
  gatewayList.value[index].linkId = option.linkId;
  gatewayList.value[index].modelNameShow = false;

  gatewayList.value[index].groupList = option.groups;
  gatewayList.value[index].groupNumberList = option.groups;

  // 创建gatewayList的键集合
  const bKeys = new Set(gatewayList.value.map((item) => `${item.divId},${item.linkId},${item.groupNumber}`));

  // 过滤数组
  const monitor = monitorAssociationGatewayList.value.filter((item) =>
    bKeys.has(`${item.gatewayId},${item.linkId},${item.gatewayLinkProtocolId}`),
  );

  monitorAssociationGatewayList.value = monitor;

  // 过滤数组
  const control = controlAssociationGatewayList.value.filter((item) =>
    bKeys.has(`${item.gatewayId},${item.linkId},${item.gatewayLinkProtocolId}`),
  );

  controlAssociationGatewayList.value = control;
  gatewayList.value[index].groupNumber = undefined;
};

const groupSwitch = (value: SelectValue, option: DefaultOptionType, index: number) => {
  groupNumberId = option.groupNumber;
  gatewayList.value[index].groupNumberShow = true;

  // 创建gatewayList的键集合
  const bKeys = new Set(gatewayList.value.map((item) => `${item.divId},${item.linkId},${item.groupNumber}`));

  // 过滤数组
  const monitor = monitorAssociationGatewayList.value.filter((item) =>
    bKeys.has(`${item.gatewayId},${item.linkId},${item.gatewayLinkProtocolId}`),
  );

  monitorAssociationGatewayList.value = monitor;

  // 过滤数组
  const control = controlAssociationGatewayList.value.filter((item) =>
    bKeys.has(`${item.gatewayId},${item.linkId},${item.gatewayLinkProtocolId}`),
  );

  controlAssociationGatewayList.value = control;
};

const addSelect = (record: GatewayList) => {
  // const list = gatewayList.value.filter((item) => item.linkId !== record.linkId);
  // const seenIds = new Set(list.map((item) => item.linkId));
  // // 使用filter方法过滤数组a，排除在数组b中已经出现的ID
  // record.links = record.linkLists.filter((item) => !seenIds.has(item.linkId));
  record.modelNameShow = true;
};

const addGroupSelect = (record: GatewayList) => {
  const list = gatewayList.value.filter((item) => item.groupNumber !== record.groupNumber);
  const seenIds = new Set(list.map((item) => item.groupNumber));
  // 使用filter方法过滤数组a，排除在数组b中已经出现的ID
  record.groupList = record.groupNumberList.filter((item) => !seenIds.has(item.id));
  record.groupNumberShow = true;
};

const rowSelectedChange = (selectedRowKeys: Key[], selectedRows: ListEquipmentParametersItem[]) => {
  const selectedLength = selectedRows.length;
  const selectedAllLength = listAllEquipmentParameters.value.length;
  const selectedEquipmentLength = listEquipmentParameters.value.length;
  const selectedRemoteLength = remoteListEquipmentParameters.value.length;
  const selectedRemoteAllLength = remoteAllListEquipmentParameters.value.length;
  if (agreementKey.value === 'monitoring') {
    if (selectedEquipmentLength === selectedAllLength) {
      monitorEquipmentLsit.value = selectedRowKeys;
      monitorChooselistEquipment.value = selectedRows;
    } else {
      if (selectedEquipmentLength < selectedAllLength) {
        if (selectedLength === 0) {
          monitorChooselistEquipment.value = arrayObjectIdFiltering(
            monitorChooselistEquipment.value,
            listEquipmentParameters.value,
          );
          monitorEquipmentLsit.value = arrayIdFiltering(monitorEquipmentLsit.value, listEquipmentParameters.value);
        } else {
          monitorChooselistEquipment.value = [...monitorChooselistEquipment.value, ...selectedRows].filter(
            (item, index, self) => {
              // 检查当前对象的ID是否已经在之前的元素中出现过
              return self.findIndex((obj) => obj.id === item.id) === index;
            },
          );
          monitorEquipmentLsit.value = [...new Set([...monitorEquipmentLsit.value, ...selectedRowKeys])];
        }
      }
    }
  } else {
    if (selectedRemoteLength === selectedRemoteAllLength) {
      controlEquipmentLsit.value = selectedRowKeys;
      controlChooselistEquipment.value = selectedRows;
    } else {
      if (selectedRemoteLength < selectedRemoteAllLength) {
        if (selectedLength === 0) {
          controlChooselistEquipment.value = arrayObjectIdFiltering(
            controlChooselistEquipment.value,
            remoteListEquipmentParameters.value,
          );
          controlEquipmentLsit.value = arrayIdFiltering(
            controlEquipmentLsit.value,
            remoteListEquipmentParameters.value,
          );
        } else {
          controlChooselistEquipment.value = [...controlChooselistEquipment.value, ...selectedRows].filter(
            (item, index, self) => {
              // 检查当前对象的ID是否已经在之前的元素中出现过
              return self.findIndex((obj) => obj.id === item.id) === index;
            },
          );
          controlEquipmentLsit.value = [...new Set([...controlEquipmentLsit.value, ...selectedRowKeys])];
        }
      }
    }
  }
};

const arrayObjectIdFiltering = (a: ListEquipmentParametersItem[], b: ListEquipmentParametersItem[]) => {
  // 使用Set来存储数组b中已经遇到的ID
  const seenIds = new Set(b.map((item) => item.id));
  // 使用filter方法过滤数组a，排除在数组b中已经出现的ID
  return a.filter((item) => !seenIds.has(item.id));
};

const arrayIdFiltering = (a: Key[], b: ListEquipmentParametersItem[]) => {
  // 从数组b中提取所有对象的id属性
  const idsToRemove = b.map((item) => item.id);

  // 使用filter方法过滤数组a，排除在idsToRemove数组中已经出现的元素
  return a.filter((item) => !idsToRemove.includes(Number(item)));
};

const validateParams = () => {
  const errors: string[] = [];
  const codes = new Set<string>();

  const dataList = [
    ...monitorAssociationGatewayList.value,
    ...controlAssociationGatewayList.value,
    ...customizationData.value,
  ];

  dataList.forEach((param) => {
    if (codes.has(param.deviceParamCode)) {
      errors.push(`${t('createDevice.equipmentParameterCoding')}:" ${param.deviceParamCode} "${t('common.rzpeat')}`);
    }

    codes.add(param.deviceParamCode);
  });

  return errors;
};

const finish = async () => {
  const dataList = [
    ...monitorAssociationGatewayList.value,
    ...controlAssociationGatewayList.value,
    ...customizationData.value,
  ];
  if (gatewayList.value.some((item) => item.linkName == '')) {
    throw new Error(t('createDevice.physicalInterfaceEmpty'));
  }

  if (gatewayList.value.some((item) => item.groupNumber == undefined)) {
    throw new Error(t('createDevice.groupNumberMustEmpty'));
  }

  if ([...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value].length === 0) {
    throw new Error(t('createDevice.equipmentParametersEmpty'));
  }
  if (dataList.some((item) => item.deviceParamCode == '')) {
    throw new Error(t('createDevice.parameterEncodingEmpty'));
  }

  if (dataList.some((item) => item.deviceParamName == '')) {
    throw new Error(t('createDevice.equipmentParameterNameEmpty'));
  }
  const valueList = validateParams();
  if (valueList.length) {
    throw new Error(t('createDevice.parameterEncodingRepeat'));
  }

  if (customizationData.value.some((item) => item.paramGroupName == '')) {
    throw new Error(t('createDevice.groupNameEmpty'));
  }

  deviceParamGroups.value = [];
  customParameters.value = [];
  deviceGateways.value = [];
  deviceParamGroupRels.value = [];

  customizationData.value.forEach((item) => {
    const {
      customFormula,
      unit,
      decimalDigits,
      isProcessData,
      paramGroupId,
      deviceParamName,
      deviceParamCode,
      paramGroupName,
    } = item;
    deviceParamGroups.value.push({
      groupName: paramGroupName,
      deviceId,
    });
    customParameters.value.push({
      customFormula,
      unit,
      decimalDigits,
      deviceId,
      isProcessData,
      paramGroupId,
      paramType: 2,
      deviceParamCode,
      deviceParamName,
      paramGroupName,
    });
  });

  [...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value].forEach((item) => {
    const {
      id,
      gatewayId,
      linkId,
      groupName,
      deviceParamCode,
      deviceParamName,
      isProcessData,
      unit,
      gatewayLinkProtocolId,
    } = item;
    deviceParamGroups.value.push({
      groupName,
      deviceId,
    });
    deviceGateways.value.push({
      deviceId,
      gatewayId,
      gatewayProtocolId: id,
      linkId,
      gatewayLinkProtocolId,
    });
    deviceParamGroupRels.value.push({
      deviceId,
      protocolParamId: id,
      paramGroupName: groupName,
      paramType: 1,
      deviceParamCode,
      deviceParamName,
      isProcessData,
      unit,
      gatewayId,
      gatewayLinkProtocolId,
    });
  });

  const uniqueList = computed(() => {
    const map = new Map<string, DeviceParamGroups>();
    deviceParamGroups.value.forEach((item) => {
      map.set(item.groupName, item); // 始终覆盖，保留最后一次
    });
    return Array.from(map.values());
  });
  deviceParamGroups.value = uniqueList.value;

  await addDeviceBind({
    deviceParamGroups: deviceParamGroups.value,
    deviceGateways: deviceGateways.value,
    deviceParamGroupRels: deviceParamGroupRels.value,
    protocolParamCustomDevDTOS: customParameters.value,
  });
};

defineExpose<UseGuideStepItemExpose>({
  finish,
});

const groupSettings = () => {
  groupingDisplayList.value = JSON.parse(JSON.stringify(groupingList.value));
  open1.value = true;
};

const addGroupingList = () => {
  groupingDisplayList.value.push({
    groupName: '',
    id: groupingDisplayList.value.length,
  });
};

const deleteGroupingList = (index: number, id: number) => {
  const dataList = [...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value];

  if (dataList.some((item) => item.groupId == id)) {
    return message.warning(t('createDevice.cannotBeDeletedGroupNumber'));
  }
  groupingDisplayList.value.splice(index, 1);
};

const handleOk1 = () => {
  if (groupingDisplayList.value.some((item) => item.groupName == '')) {
    return message.warning(t('createDevice.groupNameEmpty'));
  }
  if (new Set(groupingDisplayList.value.map((item) => item.groupName)).size !== groupingDisplayList.value.length) {
    return message.warning(t('createDevice.groupNameRepeat'));
  }
  groupingList.value = groupingDisplayList.value;
  const dataList = [...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value];

  dataList.forEach((item) => {
    groupingList.value.forEach((i) => {
      if (item.groupId === i.id) {
        item.groupName = i.groupName;
      }
    });
  });

  customizationData.value.forEach((item) => {
    groupingList.value.forEach((i) => {
      if (item.paramGroupId === i.id) {
        item.paramGroupName = i.groupName;
      }
    });
  });

  open1.value = false;
};

const useUniqueArray = (data: ListEquipmentParametersItem[]) => {
  const seen = new Set<string>();
  return data.filter((item) => {
    if (seen.has(item.deviceParamCode)) return false;
    seen.add(item.deviceParamCode);
    return true;
  });
};

const addAutomaticMatching = () => {
  paramValueListAutomaticData.value.forEach((item) => {
    const { gatewayParamCode, gatewayParamName, platformParamCode, platformParamName, id, unit, paramGroupName } = item;
    if (item.readWriteTypeCode === 'read_only') {
      monitorChooselistEquipment.value.push({
        gatewayParamCode,
        gatewayParamName,
        deviceParamCode: platformParamCode,
        deviceParamName: platformParamName,
        id,
        groupId: undefined,
        groupSerialNum: 1,
        groupParamSerialNum: undefined,
        isProcessData: false,
        gatewayId,
        groupName: paramGroupName,
        groupIdShow: false,
        linkId,
        unit,
        gatewayLinkProtocolId: groupNumberId,
      });
    } else if (item.readWriteTypeCode === 'read_write') {
      controlChooselistEquipment.value.push({
        gatewayParamCode,
        gatewayParamName,
        deviceParamCode: platformParamCode,
        deviceParamName: platformParamName,
        id,
        groupId: undefined,
        groupSerialNum: 1,
        groupParamSerialNum: undefined,
        isProcessData: false,
        gatewayId,
        groupName: paramGroupName,
        groupIdShow: false,
        linkId,
        unit,
        gatewayLinkProtocolId: groupNumberId,
      });
    }
  });

  monitorChooselistEquipment.value = useUniqueArray(monitorChooselistEquipment.value);
  controlChooselistEquipment.value = useUniqueArray(controlChooselistEquipment.value);

  monitorChooselistEquipment.value.forEach((item) => {
    if (gatewayId === item.gatewayId) {
      monitorEquipmentLsit.value.push(item.id);
    }
  });
  monitorEquipmentLsit.value = [...new Set(monitorEquipmentLsit.value)];

  controlChooselistEquipment.value.forEach((item) => {
    if (gatewayId === item.gatewayId) {
      controlEquipmentLsit.value.push(item.id);
    }
  });

  controlEquipmentLsit.value = [...new Set(controlEquipmentLsit.value)];

  open2.value = false;
};

const confirmGateway = () => {
  gatewayList.value.splice(gatewayIndex.value, 1);
  monitorAssociationGatewayList.value = monitorAssociationGatewayList.value.filter(
    (item) => !(item.gatewayId === gatewayId && item.linkId === linkId && item.gatewayLinkProtocolId === groupNumberId),
  );
  controlAssociationGatewayList.value = controlAssociationGatewayList.value.filter(
    (item) => !(item.gatewayId === gatewayId && item.linkId === linkId && item.gatewayLinkProtocolId === groupNumberId),
  );
  modalGatewayRef.value?.hideView();
};

const confirmEquipment = () => {
  if (agreementListKey.value === 'monitoring') {
    monitorAssociationGatewayList.value.splice(equipmentIndex.value, 1);
  } else {
    controlAssociationGatewayList.value.splice(equipmentIndex.value, 1);
  }

  modalEquipmentRef.value?.hideView();
};

const confirmCustomization = () => {
  customizationData.value.splice(customizationIndex.value, 1);
  modalCustomizationRef.value?.hideView();
};

onMounted(() => {
  handleRequest(async () => {
    serialNumberItem.value = await getAllGatewayList();
    const { gatewayInfoVos, protocolParamDeviceInfoVos, protocolParamCustomDevVos } = await equipmentDetails(deviceId);
    const dataList = [...protocolParamDeviceInfoVos, ...protocolParamCustomDevVos];

    groupingList.value = Array.from(new Set(dataList.map((item) => item.groupName))).map((groupName, index) => ({
      groupName,
      id: index,
    }));

    if (gatewayInfoVos.length) {
      gatewayInfoVos.forEach((item) => {
        const { snCode, modelName, id, linkName, linkId, gatewayLinkProtocolId } = item;
        serialNumberItem.value.forEach((ite) => {
          if (ite.id === id) {
            gatewayList.value.push({
              snCode,
              modelName,
              linkName,
              divId: id,
              linkId,
              snCodeShow: false,
              modelNameShow: false,
              links: ite.links,
              linkLists: ite.links,
              groupNumber: gatewayLinkProtocolId,
              groupNumberShow: false,
              groupList: ite.links.find((item) => item.linkId === linkId)?.groups || [],
              groupNumberList: ite.links.find((item) => item.linkId === linkId)?.groups || [],
            });
          }
        });
      });
    }

    if (protocolParamDeviceInfoVos.length) {
      protocolParamDeviceInfoVos.forEach((item) => {
        const {
          deviceParamCode,
          deviceParamName,
          gatewayParamCode,
          gatewayParamName,
          gatewayId,
          groupName,
          id,
          linkId,
          unit,
          isProcessData,
          gatewayLinkProtocolId,
        } = item;

        if (item.readWriteTypeCode === 'read_only') {
          monitorAssociationGatewayList.value.push({
            gatewayParamCode,
            gatewayParamName,
            deviceParamCode,
            deviceParamName,
            unit,
            id,
            groupId: undefined,
            groupSerialNum: 1,
            groupParamSerialNum: undefined,
            isProcessData: isProcessData ? true : false,
            gatewayId: Number(gatewayId),
            groupName,
            groupIdShow: false,
            linkId: Number(linkId),
            gatewayLinkProtocolId,
          });
        } else if (item.readWriteTypeCode === 'read_write') {
          controlAssociationGatewayList.value.push({
            gatewayParamCode,
            gatewayParamName,
            deviceParamCode,
            deviceParamName,
            unit,
            id,
            groupId: undefined,
            groupSerialNum: 1,
            groupParamSerialNum: undefined,
            isProcessData: isProcessData ? true : false,
            gatewayId: Number(gatewayId),
            groupName,
            groupIdShow: false,
            linkId: Number(linkId),
            gatewayLinkProtocolId,
          });
        }
      });

      const dataList = [...monitorAssociationGatewayList.value, ...controlAssociationGatewayList.value];

      dataList.forEach((item) => {
        groupingList.value.forEach((i) => {
          if (item.groupName === i.groupName) {
            item.groupId = i.id;
          }
        });
      });
    }

    if (protocolParamCustomDevVos.length) {
      protocolParamCustomDevVos.forEach((item) => {
        const { deviceParamCode, deviceParamName, customFormula, unit, decimalDigits, isProcessData, groupName } = item;
        customizationData.value.push({
          deviceParamCode,
          deviceParamName,
          customFormula,
          unit,
          decimalDigits,
          paramGroupId: undefined,
          groupSerialNum: 1,
          groupParamSerialNum: undefined,
          isProcessData,
          paramNumShow: false,
          paramNameShow: false,
          customFormulaShow: false,
          unitShow: false,
          decimalDigitsShow: false,
          groupSerialNumShow: false,
          paramGroupIdShow: false,
          paramGroupName: groupName,
        });
      });

      customizationData.value.forEach((item) => {
        groupingList.value.forEach((i) => {
          if (item.paramGroupName === i.groupName) {
            item.paramGroupId = i.id;
          }
        });
      });
    }
  });
});
</script>

<template>
  <div>
    <div class="gateway-parameters-content">
      <AFlex justify="space-between" class="gateway-parameters-bottom">
        <span class="header-text">{{ $t('createDevice.associationGatewayParameters') }}</span>
        <AButton class="default-button" @click="addGateway">{{ $t('common.newAddition') }}</AButton>
      </AFlex>

      <div>
        <ATable :columns="columns" :data-source="gatewayList" :pagination="false">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'snCode'">
              <ASelect
                v-model:value="record.snCode"
                class="select-width"
                :options="serialNumberItem"
                :field-names="{ label: 'snCode', value: 'id' }"
                @click="record.snCodeShow = true"
                @blur="record.snCodeShow = false"
                :show-arrow="record.snCodeShow"
                @change="(value, option) => serialNumberAdd(value, option, index)"
              />
            </template>
            <template v-if="column.key === 'linkName'">
              <ASelect
                class="select-width"
                v-model:value="record.linkName"
                @click="addSelect(record as GatewayList)"
                @blur="record.modelNameShow = false"
                :show-arrow="record.modelNameShow"
                :options="record.links"
                :field-names="{ label: 'linkName', value: 'linkId' }"
                @change="(value, option) => linkSwitch(value, option, index, record.divId)"
              />
            </template>
            <template v-if="column.key === 'groupNumber'">
              <ASelect
                class="select-width"
                v-model:value="record.groupNumber"
                @click="addGroupSelect(record as GatewayList)"
                @blur="record.groupNumberShow = false"
                :show-arrow="record.groupNumberShow"
                :options="record.groupList"
                :field-names="{ label: 'group', value: 'id' }"
                @change="(value, option) => groupSwitch(value, option, index)"
              />
            </template>

            <template v-if="column.key === 'tags'">
              <span
                class="select-parameters"
                @click="selectParameters(record.linkId, record.divId, record.groupNumber)"
                >{{ $t('createDevice.selectParameters') }}</span
              >
            </template>
            <template v-if="column.key === 'action'">
              <SvgIcon
                @click="gatewayDelete(record.divId, record.linkId, index, record.groupNumber)"
                class="grouping-delete-svg"
                name="delete"
              />
            </template>
          </template>
        </ATable>
      </div>

      <div class="gateway-margin">
        <span class="header-text">{{ $t('createDevice.configureDeviceParameters') }}</span>
      </div>

      <ATabs v-model:active-key="agreementListKey">
        <ATabPane key="monitoring" :tab="$t('createDevice.dataMonitoring')">
          <ATable :columns="devColumns" :data-source="monitorAssociationGatewayList" :pagination="false">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'deviceParamCode'">
                <AInput
                  :class="record.deviceParamCodeShow ? 'determine-color' : ''"
                  v-model:value="record.deviceParamCode"
                  @click="record.deviceParamCodeShow = true"
                  @blur="record.deviceParamCodeShow = false"
                />
              </template>
              <template v-else-if="column.key === 'deviceParamName'">
                <AInput
                  :class="record.deviceParamNameShow ? 'determine-color' : ''"
                  v-model:value="record.deviceParamName"
                  @click="record.deviceParamNameShow = true"
                  @blur="record.deviceParamNameShow = false"
                />
              </template>
              <template v-else-if="column.key === 'groupId'">
                <ASelect
                  class="select-width"
                  v-model:value="record.groupId"
                  @click="record.groupIdShow = true"
                  @blur="record.groupIdShow = false"
                  :show-arrow="record.groupIdShow ? true : false"
                  :options="groupingList"
                  :field-names="{ label: 'groupName', value: 'id' }"
                  @change="(value, option) => selectGrouping(value, option, index)"
                />
              </template>
              <template v-else-if="column.key === 'groupParamSerialNum'">
                <AInputNumber
                  :class="record.decimalDigitsShow ? 'determine-color' : ''"
                  v-model:value="record.groupParamSerialNum"
                  :controls="record.decimalDigitsShow ? true : false"
                  @click="record.decimalDigitsShow = true"
                  @blur="record.decimalDigitsShow = false"
                  :min="1"
                />
              </template>
              <template v-else-if="column.key === 'isProcessData'">
                <ASwitch v-model:checked="record.isProcessData" />
              </template>

              <template v-else-if="column.key === 'action'">
                <SvgIcon @click="gatewayDevDelete(index)" class="grouping-delete-svg" name="delete" />
              </template>
            </template>
          </ATable>
        </ATabPane>
        <ATabPane key="remote" :tab="$t('createDevice.remoteControl')" force-render>
          <ATable :columns="devColumns" :data-source="controlAssociationGatewayList" :pagination="false">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'deviceParamCode'">
                <AInput
                  :class="record.deviceParamCodeShow ? 'determine-color' : ''"
                  v-model:value="record.deviceParamCode"
                  @click="record.deviceParamCodeShow = true"
                  @blur="record.deviceParamCodeShow = false"
                />
              </template>
              <template v-else-if="column.key === 'deviceParamName'">
                <AInput
                  :class="record.deviceParamNameShow ? 'determine-color' : ''"
                  v-model:value="record.deviceParamName"
                  @click="record.deviceParamNameShow = true"
                  @blur="record.deviceParamNameShow = false"
                />
              </template>
              <template v-else-if="column.key === 'groupId'">
                <ASelect
                  class="select-width"
                  v-model:value="record.groupId"
                  @click="record.groupIdShow = true"
                  @blur="record.groupIdShow = false"
                  :show-arrow="record.groupIdShow ? true : false"
                  :options="groupingList"
                  :field-names="{ label: 'groupName', value: 'id' }"
                  @change="(value, option) => selectGrouping(value, option, index)"
                />
              </template>
              <template v-else-if="column.key === 'groupParamSerialNum'">
                <AInputNumber
                  :class="record.decimalDigitsShow ? 'determine-color' : ''"
                  v-model:value="record.groupParamSerialNum"
                  :controls="record.decimalDigitsShow ? true : false"
                  @click="record.decimalDigitsShow = true"
                  @blur="record.decimalDigitsShow = false"
                  :min="1"
                />
              </template>
              <template v-else-if="column.key === 'isProcessData'">
                <ASwitch v-model:checked="record.isProcessData" />
              </template>

              <template v-else-if="column.key === 'action'">
                <SvgIcon @click="gatewayDevDelete(index)" class="grouping-delete-svg" name="delete" />
              </template>
            </template>
          </ATable>
        </ATabPane>

        <template #rightExtra>
          <AButton class="default-button" @click="groupSettings">{{ $t('createDevice.groupSettings') }}</AButton>
        </template>
      </ATabs>

      <AFlex justify="space-between" class="gateway-margin">
        <span class="header-text">{{ $t('createDevice.customizedMonitoringParameters') }}</span>
        <div>
          <AButton class="default-button" @click="addCustomizationData">{{ $t('common.newAddition') }}</AButton>
        </div>
      </AFlex>

      <ATable :columns="customizationColumns" :data-source="customizationData" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ index + 1 }}
          </template>
          <template v-else-if="column.key === 'deviceParamCode'">
            <ATooltip :destroy-tooltip-on-hide="true">
              <template #title>{{ record.deviceParamCode }}</template>
            </ATooltip>
            <AInput
              :class="record.paramNumShow ? 'determine-color' : ''"
              v-model:value="record.deviceParamCode"
              @click="record.paramNumShow = true"
              @blur="record.paramNumShow = false"
            />
          </template>
          <template v-else-if="column.key === 'deviceParamName'">
            <AInput
              :class="record.paramNameShow ? 'determine-color' : ''"
              v-model:value="record.deviceParamName"
              @click="record.paramNameShow = true"
              @blur="record.paramNameShow = false"
            />
          </template>
          <template v-else-if="column.key === 'customFormula'">
            <AInput
              :class="record.customFormulaShow ? 'determine-color' : ''"
              v-model:value="record.customFormula"
              @click="record.customFormulaShow = true"
              @blur="record.customFormulaShow = false"
            />
          </template>
          <template v-else-if="column.key === 'unit'">
            <AInput
              :class="record.unitShow ? 'determine-color' : ''"
              v-model:value="record.unit"
              @click="record.unitShow = true"
              @blur="record.unitShow = false"
            />
          </template>
          <template v-else-if="column.key === 'decimalDigits'">
            <AInputNumber
              :class="record.decimalDigitsShow ? 'determine-color' : ''"
              v-model:value="record.decimalDigits"
              :controls="record.decimalDigitsShow"
              @click="record.decimalDigitsShow = true"
              @blur="record.decimalDigitsShow = false"
              :min="1"
            />
          </template>
          <template v-else-if="column.key === 'paramGroupId'">
            <ASelect
              class="select-width"
              v-model:value="record.paramGroupId"
              :options="groupingList"
              :field-names="{ label: 'groupName', value: 'id' }"
              @click="record.paramGroupIdShow = true"
              @blur="record.paramGroupIdShow = false"
              :show-arrow="record.paramGroupIdShow"
              @change="(value, option) => customizationChange(value, option, index)"
            />
          </template>
          <template v-else-if="column.key === 'groupParamSerialNum'">
            <AInputNumber
              :class="record.groupSerialNumShow ? 'determine-color' : ''"
              v-model:value="record.groupParamSerialNum"
              :controls="record.groupSerialNumShow"
              @click="record.groupSerialNumShow = true"
              @blur="record.groupSerialNumShow = false"
              :min="1"
            />
          </template>
          <template v-else-if="column.key === 'isProcessData'">
            <ASwitch v-model:checked="record.isProcessData" />
          </template>
          <template v-else-if="column.key === 'action'">
            <SvgIcon @click="customizationDelete(index)" class="grouping-delete-svg" name="delete" />
          </template>
        </template>
      </ATable>
    </div>

    <AModal
      v-model:open="open"
      :title="$t('createDevice.selectGatewayProtocolParameters')"
      width="920px"
      :footer="null"
      :mask-closable="false"
      :keyboard="false"
    >
      <div class="gateway-parameters">
        <AFlex>
          <div class="gateway-parameters-left">
            <ATabs v-model:active-key="agreementKey">
              <ATabPane key="monitoring" :tab="$t('createDevice.dataMonitoring')">
                <AFlex justify="space-between" align="center" class="gateway-parameters-left-bottom">
                  <AInput
                    :placeholder="t('common.search')"
                    v-model:value="monitorSearchContent"
                    class="input-width"
                    allow-clear
                  >
                    <template #prefix>
                      <SvgIcon class="search-svg" name="search-o" />
                    </template>
                  </AInput>
                  <div>
                    <AButton class="button-margin" type="primary" @click="fuzzyQuery('monitor')">
                      {{ $t('common.query') }}
                    </AButton>
                    <AButton type="primary" ghost @click="queryReset('monitor')">{{ $t('common.reset') }}</AButton>
                  </div>
                </AFlex>

                <ATable
                  :row-selection="{
                    type: 'checkbox',
                    selectedRowKeys: monitorEquipmentLsit,
                    onChange: rowSelectedChange,
                  }"
                  row-key="id"
                  :columns="protocolEquipmentColumns"
                  :data-source="listEquipmentParameters"
                  :scroll="{ y: 270 }"
                  :pagination="false"
                >
                  <template #bodyCell="{ column, index }">
                    <template v-if="column.key === 'index'">
                      {{ index + 1 }}
                    </template>
                  </template>
                </ATable>
              </ATabPane>
              <ATabPane key="remote" :tab="$t('createDevice.remoteControl')" force-render>
                <AFlex justify="space-between" align="center" class="gateway-parameters-left-bottom">
                  <AInput
                    :placeholder="t('common.search')"
                    class="input-width"
                    v-model:value="controlSearchContent"
                    allow-clear
                  >
                    <template #prefix>
                      <SvgIcon class="search-svg" name="search-o" />
                    </template>
                  </AInput>

                  <div>
                    <AButton class="button-margin" type="primary" @click="fuzzyQuery('control')">
                      {{ $t('common.query') }}
                    </AButton>
                    <AButton type="primary" ghost @click="queryReset('control')">{{ $t('common.reset') }}</AButton>
                  </div>
                </AFlex>

                <ATable
                  :row-selection="{
                    type: 'checkbox',
                    selectedRowKeys: controlEquipmentLsit,
                    onChange: rowSelectedChange,
                  }"
                  row-key="id"
                  :columns="protocolEquipmentColumns"
                  :data-source="remoteListEquipmentParameters"
                  :scroll="{ y: 270 }"
                  :pagination="false"
                >
                  <template #bodyCell="{ column, index }">
                    <template v-if="column.key === 'index'">
                      {{ index + 1 }}
                    </template>
                  </template>
                </ATable>
              </ATabPane>
            </ATabs>
          </div>

          <div class="gateway-parameters-right" v-if="agreementKey === 'monitoring'">
            <AFlex justify="space-between" class="gateway-parameters-right-top">
              <div>
                <span></span>{{ $t('common.selected') }} ({{ monitorEquipmentLsit.length }} /
                {{ listAllEquipmentParameters.length }})
              </div>
              <SvgIcon class="delete-all-svg" @click="deleteAll" name="delete" />
            </AFlex>

            <AFlex :vertical="true" class="gateway-parameters-right-height main-container">
              <AFlex
                justify="space-between"
                v-for="(item, index) in monitorChooselistEquipment"
                :key="item.id"
                class="gateway-parameters-right-dev"
              >
                <AFlex justify="space-between" align="center" class="gateway-parameters-right-width">
                  <ATooltip>
                    <template #title>{{ item.gatewayParamCode }} - {{ item.gatewayParamName }}</template>
                    <div class="gateway-parameters-right-text">
                      {{ item.gatewayParamCode }} - {{ item.gatewayParamName }}
                    </div>
                  </ATooltip>

                  <SvgIcon class="delete-svg" @click="addEquipment(index)" name="close-circle-o" />
                </AFlex>
              </AFlex>
            </AFlex>
          </div>

          <div v-else class="gateway-parameters-right">
            <AFlex justify="space-between" class="gateway-parameters-right-top">
              <div>
                <span></span>{{ $t('common.selected') }} ({{ controlEquipmentLsit.length }} /
                {{ remoteAllListEquipmentParameters.length }})
              </div>
              <SvgIcon class="delete-all-svg" @click="deleteAll" name="delete" />
            </AFlex>

            <AFlex :vertical="true" class="main-container gateway-parameters-right-height">
              <AFlex
                justify="space-between"
                v-for="(item, index) in controlChooselistEquipment"
                :key="item.id"
                class="gateway-parameters-right-dev"
              >
                <AFlex justify="space-between" align="center" class="gateway-parameters-right-width">
                  <div class="gateway-parameters-right-text">
                    {{ item.gatewayParamCode }} - {{ item.gatewayParamName }}
                  </div>
                  <SvgIcon class="delete-svg" @click="addEquipment(index)" name="close-circle-o" />
                </AFlex>
              </AFlex>
            </AFlex>
          </div>
        </AFlex>
      </div>

      <AFlex justify="space-between">
        <div class="but-text">
          <span class="footer-text-right"
            >{{ $t('createDevice.selectionMonitoringParameters') }}{{ monitorEquipmentLsit.length
            }}{{ $t('common.item') }}</span
          >
          <span
            >{{ $t('createDevice.remoteControlSelection') }}{{ controlEquipmentLsit.length
            }}{{ $t('common.item') }}</span
          >
        </div>
        <div class="footer-div-top">
          <AButton class="off-but" @click="open = false">{{ $t('common.cancel') }}</AButton>
          <AButton type="primary" @click="handleOk">{{ $t('common.save') }}</AButton>
        </div>
      </AFlex>
    </AModal>
    <AModal
      v-model:open="open1"
      :title="$t('createDevice.groupSettings')"
      @ok="handleOk1"
      width="460px"
      :mask-closable="false"
      :keyboard="false"
      :ok-text="$t('common.save')"
    >
      <br />

      <ATable :columns="groupingColumns" :data-source="groupingDisplayList" :pagination="false">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'groupName'">
            <AInput v-model:value="record.groupName" />
          </template>
          <template v-else-if="column.key === 'action'">
            <SvgIcon @click="deleteGroupingList(index, record.id)" class="grouping-delete-svg" name="delete" />
          </template>
        </template>
      </ATable>

      <AButton class="group-button" type="dashed" @click="addGroupingList">{{ $t('common.newAddition') }}</AButton>
    </AModal>

    <AModal v-model:open="open2" width="460px" :closable="false" @ok="addAutomaticMatching" :ok-text="$t('common.use')">
      <template #title>
        <AFlex align="center">
          <SvgIcon class="question-svg" name="question-circle" />
          <div class="modal-title">{{ $t('createDevice.automaticMatching') }}?</div>
        </AFlex>
      </template>
      <div class="description">{{ $t('createDevice.matchParameters') }}</div>
    </AModal>

    <ConfirmModal
      ref="modalGateway"
      :title="$t('common.deleteConfirmation')"
      :description-text="$t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirmGateway"
    />
    <ConfirmModal
      ref="modalEquipment"
      :title="$t('common.deleteConfirmation')"
      :description-text="$t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirmEquipment"
    />
    <ConfirmModal
      ref="modalCustomization"
      :title="$t('common.deleteConfirmation')"
      :description-text="$t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirmCustomization"
    />
  </div>
</template>

<style lang="scss" scoped>
.button-margin {
  margin-right: 12px;
}

.footer-div-top {
  margin-top: 24px;
}

.footer-text-right {
  margin-right: 32px;
}

.gateway-parameters-right-width {
  width: 250px;
}

.gateway-parameters-right-height {
  height: 390px;
}

.gateway-parameters-right-top {
  width: 100%;
  padding-bottom: 24px;
}

.input-width {
  width: 256px;
}

.gateway-parameters-left-bottom {
  margin-bottom: 16px;
}

.gateway-margin {
  margin-top: 40px;
  margin-bottom: 20px;
}

.select-width {
  width: 100%;
}

.gateway-parameters-bottom {
  margin-bottom: 20px;
}

:deep(.gateway-parameters-content) {
  .ant-input {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .ant-select-selector {
    background-color: rgb(255 255 255 / 0%);
    border-color: rgb(255 255 255 / 0%);
    border-radius: 3px;
  }

  .ant-select:not(.ant-select-disabled, .ant-select-customize-input, .ant-pagination-size-changer):hover
    .ant-select-selector {
    border-color: #d9d9d9;
  }

  .ant-select-focused.ant-select:not(.ant-select-disabled, .ant-select-customize-input, .ant-pagination-size-changer)
    .ant-select-selector {
    border-color: var(--antd-color-primary-hover);
  }

  .ant-tabs-nav::before {
    border: 0;
  }
}

.modal-title {
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: #333;
  text-align: left;
}

.gateway-parameters-right-text {
  width: 225px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-text {
  margin-top: 5px;
  font-size: 16px;
  font-style: normal;
  font-weight: 600;
  line-height: 24px;
  color: #333;
  text-align: left;
}

.select-parameters {
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: #32bac0;
  text-align: left;
  cursor: pointer;
}

.gateway-parameters {
  width: 872px;
  height: 473px;
  margin-top: 24px;
  overflow: hidden;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.gateway-parameters-left {
  width: 572px;
  padding: 24px;
  padding-top: 12px;
}

.gateway-parameters-right {
  width: 298px;
  padding: 24px 18px 24px 24px;
  border-left: 1px solid #e4e7ed;
}

.gateway-parameters-right-dev {
  width: 100%;
  height: 24px;
  margin-bottom: 24px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: #666;
  text-align: left;
}

.off-but {
  margin-right: 16px;
  color: var(--antd-color-primary-hover);
  border-color: var(--antd-color-primary-hover);
}

.but-text {
  margin-top: 28px;
}

.search-svg {
  width: 12px;
  height: 12px;
  margin-right: 5px;
  margin-bottom: 2px;
  color: #b2b2b2;
  cursor: pointer;
}

.delete-all-svg {
  margin-right: 10px;
  font-size: 26px;
  color: #000;
  cursor: pointer;
}

.delete-svg {
  margin-right: 5px;
  font-size: 16px;
  color: #000;
  cursor: pointer;
}

.gateway-parameters-content .ant-input {
  background-color: rgb(255 255 255 / 0%);
  border-color: rgb(255 255 255 / 0%);
  border-radius: 3px;
}

.gateway-parameters-content .ant-input:hover {
  border-color: #d9d9d9;
}

.gateway-parameters-content .ant-input-number {
  background-color: rgb(255 255 255 / 0%);
  border-color: rgb(255 255 255 / 0%);
  border-radius: 3px;
}

.gateway-parameters-content .ant-input-number:hover {
  border-color: #d9d9d9;
}

.gateway-parameters-content .ant-table-content .determine-color {
  border-color: var(--antd-color-primary-hover);
}

.group-button {
  width: 412px;
  height: 40px;
  margin-top: 8px;
}

.grouping-delete-svg {
  font-size: 21px;
  color: var(--antd-color-primary-hover);
  cursor: pointer;
}

.question-svg {
  margin-right: 16px;
  font-size: 24px;
  color: #e6a23c;
}

.description {
  margin-top: 8px;
  margin-bottom: 50px;
  margin-left: 40px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 20px;
  color: #666;
  text-align: left;
}
</style>
