<script setup lang="ts">
import { onMounted, ref, useTemplateRef } from 'vue';

import Visual2DEditor from '@/components/visual-2d/Visual2DEditor.vue';
import Visual2DPreview from '@/components/visual-2d/Visual2DPreview.vue';
import { useRequest } from '@/hooks/request';
import { getGroupModuleInfo, getPageList, noPaginationDevicesList } from '@/api';
import { VisualModuleType } from '@/constants';

import DeviceControl from './device-control/DeviceControl.vue';
import DeviceBatchExe from './DeviceBatchExe.vue';
import DeviceCtrlModal from './DeviceCtrlModal.vue';

import type {
  AllDevicesList,
  DevGroupTabCompProps,
  DeviceGroupItem,
  DeviceGroupTree,
  DeviceGroupTreeChild,
  GroupModuleInfo,
} from '@/types';

const props = defineProps<DevGroupTabCompProps>();

const deviceControlRef = useTemplateRef('deviceControl');
const deviceCtrlModalRef = useTemplateRef('deviceCtrlModal');
const deviceBatchExeRef = useTemplateRef('deviceBatchExe');
const visual2DEditorRef = useTemplateRef('visual2DEditor');
const visual2DPreviewRef = useTemplateRef('visual2DPreview');

const { isLoading, handleRequest } = useRequest();
const moduleInfo = ref<GroupModuleInfo>();
const deviceList = ref<DeviceGroupTree[]>([]);

onMounted(() => {
  handleRequest(async () => {
    const groups = await getPageList();
    const devices = await noPaginationDevicesList();
    deviceList.value = transformGroupsAndDevices(groups, devices);

    moduleInfo.value = await getGroupModuleInfo({
      groupId: props.deviceGroupId,
      moduleType: VisualModuleType.Module2D,
    });
  });
});

const transformGroupsAndDevices = (groups: DeviceGroupItem[], devices: AllDevicesList[]): DeviceGroupTree[] => {
  // 创建一个映射表，用于快速查找每个组ID对应的设备
  const deviceMap = new Map<number, AllDevicesList[]>();

  devices.forEach((device) => {
    if (!deviceMap.has(device.groupId)) {
      deviceMap.set(device.groupId, []);
    }

    deviceMap.get(device.groupId)!.push(device);
  });

  // 转换顶级分组
  return groups.map((group) => {
    // 转换当前组
    const transformed: DeviceGroupTree = {
      ...group,
      label: group.groupName,
      children: [],
    };

    // 转换子分组（二级分组），并过滤掉没有设备的分组
    if (group.deviceGroupChilds && group.deviceGroupChilds.length > 0) {
      transformed.children = group.deviceGroupChilds
        .map((child) => {
          const transformedChild: DeviceGroupTreeChild = {
            ...child,
            label: child.groupName,
            children: [],
          };

          // 查找并添加属于这个二级分组的设备
          const childDevices = deviceMap.get(child.id) || [];

          transformedChild.children = childDevices.map((device) => ({
            ...device,
            label: device.deviceName,
          }));

          return transformedChild;
        })
        .filter((child) => child.children.length > 0); // 过滤掉没有设备的二级分组
    }

    return transformed;
  });
};

const openEditor = () => {
  visual2DEditorRef.value?.showView();
};

const openDevCtrlModal = (id: number) => {
  if (!id) {
    return;
  }

  deviceCtrlModalRef.value?.showView();
};

const exportImg = () => {
  visual2DPreviewRef.value?.exportImg();
};

const maximizeView = () => {
  console.log('maximize view');
};

defineExpose({
  openEditor,
  exportImg,
  maximizeView,
});
</script>

<template>
  <div class="real-time-monitor-container">
    <template v-if="moduleInfo?.leId">
      <Visual2DPreview
        ref="visual2DPreview"
        :info="moduleInfo"
        :device-list="deviceList"
        @click="deviceControlRef?.closeCtrlPanel"
        @open-dev-ctrl-modal="openDevCtrlModal"
      />
      <Visual2DEditor ref="visual2DEditor" :info="moduleInfo" :device-list="deviceList" />
    </template>
    <DeviceControl ref="deviceControl" />
    <DeviceCtrlModal ref="deviceCtrlModal" @open-dev-batch-exe="deviceBatchExeRef?.showView" />
    <DeviceBatchExe ref="deviceBatchExe" />
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
  </div>
</template>

<style lang="scss" scoped>
.real-time-monitor-container {
  height: 100%;
  background: #1e2530;
  border-radius: 12px;
}
</style>
