<template>
  <div class="cameraTreeWrapper">
    <div class="cameraTreeTitle">场景树</div>
    <div class="cameraTreeInputWrapper">
      <el-input
        v-model="filterText"
        placeholder="请输入相机的名称进行搜索"
        :suffix-icon="Search"
        class="filterTextInput"
      />

      <el-tree
        :data="props.cameraTree"
        :props="defaultProps"
        @node-click="handleNodeClick"
        node-key="code"
        :default-expand-all="true"
        :filter-node-method="filterNode"
        ref="treeRef"
        v-loading="props.loading"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span
              ><span
                class="cameraCommon"
                :class="{
                  cameraSelect:
                    data.nodeType === CameraTreeNodeType.camera && data.id === Number(cameraId),
                }"
              ></span
              >{{ node.label }}</span
            >
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ElTree } from 'element-plus';
  import { ref, watch } from 'vue';
  import { useRouteQuery } from '@vueuse/router';
  import { Search } from '@element-plus/icons-vue';

  import useCameraDetail from '../../store/useCameraDetailStore';
  import { CameraTree, CameraTreeNodeType } from '@/api/camera/camera-preview';

  const props = defineProps<{ cameraTree: Tree[]; loading: boolean }>();

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

  const { setDetail } = useCameraDetail();

  const cameraId = useRouteQuery('cameraId');
  const defaultProps = {
    children: 'children',
    label: 'name',
  };

  const handleNodeClick = (e: CameraTree) => {
    console.log('e', e);
    console.log('CameraTreeNodeType', CameraTreeNodeType);

    if (e.nodeType === CameraTreeNodeType.camera) {
      console.log('aaa');

      cameraId.value = String(e.id);
      setDetail(e);
    }
  };

  const filterText = ref('');
  const treeRef = ref<InstanceType<typeof ElTree>>();

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

  const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.name?.includes(value);
  };
</script>
<style scoped>
  .cameraCommon {
    width: 6px;
    height: 6px;
    display: inline-block;
    margin-right: 6px;
  }

  .cameraSelect {
    width: 6px;
    height: 6px;
    background: #0052d9;
    display: inline-block;
    border-radius: 6px;
    margin-right: 6px;
  }
  .cameraTreeTitle {
    background: #f0f2f5;
    padding: 12px;
  }

  .cameraTreeInputWrapper {
    padding: 8px;
  }
  .filterTextInput {
    margin: 8px 0;
  }
</style>
