<template>
  <div class="cameraTreeWrapper">
    <div class="cameraTreeInputWrapper">
      <el-input
        v-model="filterText"
        placeholder="请输入相机的名称进行搜索"
        :suffix-icon="Search"
        class="filterTextInput"
      />
    </div>
    <el-scrollbar class="tree-scroll">
      <el-tree
        :data="cameraTree"
        :props="defaultProps"
        @node-click="handleClickCamera"
        node-key="code"
        :default-expand-all="false"
        :default-expanded-keys="cameraTree"
        :filter-node-method="filterNode"
        ref="treeRef"
        v-loading="treeLoading"
        :empty-text="treeEmptyText"
        element-loading-background="rgba(0, 0, 0, 0)"
      >
        <template #default="{ node, data }">
          <div
            class="treeNode"
            :class="{
              selectedCamera: isSelected(node, data.id),
            }"
          >
            <div v-if="data.nodeType === CameraTreeNodeType.camera" class="icons">
              <VideoCamera class="cameraIcon" />
              <WarningFilled v-if="isInvalid(data)" class="invalidCamera" style="color: red" />
            </div>

            <div class="cameraName">
              {{ node.label }}
            </div>

            <Thumbnail
              v-if="data.nodeType === CameraTreeNodeType.camera"
              :imageUrl="data.imageUrl"
              :code="data.code"
              position="right"
            >
              <div class="mask"></div>
            </Thumbnail>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
  import { ElInput, ElTree, ElScrollbar } from 'element-plus';
  import { onMounted, ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import { VideoCamera, WarningFilled, Search } from '@element-plus/icons-vue';
  import { CameraTreeNodeType, getCameraTree } from '@/api/camera/camera-preview';
  import { useCameraGroupList } from '@/store/modules/useCameraGroupList';
  import type { CameraGroupType } from '@/views/disaster/monitor/splitScreenRetrieval/type';
  import Thumbnail from '@/components/thumbnail/Thumbnail.vue';

  interface Tree {
    [key: string]: any;
  }

  const defaultProps = {
    children: 'children',
    label: 'name',
  };

  const cameraTree = ref();
  const filterText = ref('');
  const treeRef = ref<InstanceType<typeof ElTree>>();
  const childrenNodeList = ref<string[]>([]);
  const treeLoading = ref(false);
  const treeEmptyText = ref('');
  const props = defineProps<{ cameraGroup: CameraGroupType }>();

  const { cameraInPlay, playingGroup, totalRound } = storeToRefs(useCameraGroupList());
  const { addCameraIntoGroup, deleteCameraFromGroup, deleteCameraInPlaylist, getValidateCameraNum, restartPlay } =
    useCameraGroupList();

  const isSelected = (nodeData, id: number) => {
    return props.cameraGroup.children.find((x) => x.id === id && nodeData.data.nodeType === CameraTreeNodeType.camera);
  };

  const handleClickCamera = (nodeData) => {
    // 如果点击的不是摄像头
    if (nodeData.nodeType !== CameraTreeNodeType.camera) return;

    const cameraInGroup = props.cameraGroup.children.find((x) => x.id === nodeData.id);

    // 如果该摄像头在分组里，则从分组移除该摄像头，否则添加该摄像头进分组
    if (cameraInGroup) {
      cameraInPlay.value.includes(cameraInGroup)
        ? deleteCameraInPlaylist(props.cameraGroup, cameraInGroup)
        : deleteCameraFromGroup(props.cameraGroup, cameraInGroup);
    } else {
      const camera = {
        code: nodeData.code,
        name: nodeData.name,
        url: nodeData.pushStreamDTO.videoUrls?.pushstreamIp || '',
        id: nodeData.id,
        cameraGroupDetailId: -1,
        imageUrl: '',
      };

      addCameraIntoGroup(props.cameraGroup.id, camera);

      // 如果往正在轮播的分组添加相机,且该分组的有效相机数未能填满宫格数，则刷新当前播放的画面
      if (props.cameraGroup.id === playingGroup.value?.id && getValidateCameraNum() >= 0 && totalRound.value <= 1) {
        restartPlay();
      }
    }
  };

  watch(filterText, (val) => {
    childrenNodeList.value = [];
    treeRef.value!.filter(val);
  });

  function extractCodes(data: any[], codes: string[] = []) {
    data.forEach((item) => {
      codes.push(item.data.code);
      if (item.childNodes) {
        extractCodes(item.childNodes, codes);
      }
    });
    return codes;
  }

  const filterNode = (value: string, data: Tree, node) => {
    if (!value) return true;
    // 检查当前节点的 label 是否包含关键词
    const labelMatch = data.name.includes(value);

    if (labelMatch) {
      if (node.childNodes && node.childNodes.length > 0) {
        childrenNodeList.value = extractCodes(node.childNodes, []);
      }
    }

    if (childrenNodeList.value.includes(data.code)) {
      return true;
    } else {
      return labelMatch;
    }
  };

  const isInvalid = (data) => {
    if (data.networkingState !== 0) data.disable = true;
    return data.networkingState !== 0;
  };

  onMounted(() => {
    treeLoading.value = true;
    getCameraTree()
      .then((res) => {
        cameraTree.value = res;
        if (cameraTree.value.length === 0) treeEmptyText.value = '暂无数据';
      })
      .catch(() => {
        treeEmptyText.value = '暂无数据';
      })
      .finally(() => {
        treeLoading.value = false;
      });
  });
</script>
<style lang="scss" scoped>
  .cameraTreeWrapper {
    .cameraTreeInputWrapper {
      padding: 8px;
      .filterTextInput {
        margin: 8px 0;
      }
    }

    .tree-scroll {
      height: 400px;
      .selectedCamera {
        color: #1777ff !important;
      }
      .treeNode {
        display: flex;
        align-items: center;
        color: black;
        // position: relative;
        .icons {
          display: flex;
          align-items: center;
          position: relative;
          .cameraIcon {
            height: 18px;
            margin-right: 8px;
            color: black;
          }
          .invalidCamera {
            height: 14px;
            color: #dd5869;
            position: absolute;
            right: 0px;
            top: -5px;
          }
        }
        .cameraName {
        }
      }
      .mask {
        height: 26px;
        width: 100%;
      }
    }
  }

  :deep(.thumb-nail) {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99;
  }

  :deep(.el-tree-node__content) {
    position: relative;
  }
</style>
