import type { NdmNvrResultVO } from '@/apis';

// 解析 clusterList 字段
export const parseIpListFromClusterList = (nvr: NdmNvrResultVO) => {
  const ipList = (nvr.clusterList ?? '').split(';');
  return ipList.map((ip) => ip.trim()).filter((ip) => !!ip);
};

export const isNvrCluster = (maybeNvrCluster: NdmNvrResultVO) => {
  const { ipAddress } = maybeNvrCluster;
  const ipList = parseIpListFromClusterList(maybeNvrCluster);
  if (ipList.length === 0) return false;
  if (ipList.length === 1 && ipList.at(0) === ipAddress) return false;
  return true;
};

export const nvrInCluster = (nvr: NdmNvrResultVO, cluster: NdmNvrResultVO) => {
  const { ipAddress } = nvr;
  if (!ipAddress) return false;
  const ipList = parseIpListFromClusterList(cluster);
  return ipList.includes(ipAddress);
};

export const createNvrClusterRelationship = (nvrDevices: NdmNvrResultVO[]) => {
  const nvrClusters = nvrDevices.filter((nvr) => isNvrCluster(nvr));
  const nvrNotClusters = nvrDevices.filter((nvr) => !isNvrCluster(nvr));
  const nodedNvrIpAddressSet = new Set<string | null>();
  const nvrStandalones: NdmNvrResultVO[] = [];
  const nvrTreeMap = new Map<string, NdmNvrResultVO[]>();
  // 遍历所有非集群录像机，将它们分配到对应的录像机集群中
  for (const nvr of nvrNotClusters) {
    for (const cluster of nvrClusters) {
      if (nvrInCluster(nvr, cluster)) {
        if (!!cluster.ipAddress) {
          // 写入录像机与集群的关系
          nvrTreeMap.set(cluster.ipAddress, [...(nvrTreeMap.get(cluster.ipAddress) ?? []), nvr]);
          // 记录已分配的录像机IP地址
          nodedNvrIpAddressSet.add(nvr.ipAddress);
        }
      }
    }
  }
  // 分配完成后，过滤出未分配的录像机，形成录像机单机列表
  nvrNotClusters.forEach((device) => {
    if (!nodedNvrIpAddressSet.has(device.ipAddress)) {
      nvrStandalones.push(device);
    }
  });

  return {
    nvrClusters,
    // nvrNotClusters,
    nvrTreeMap,
    nvrStandalones,
  };
};
