<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { SyncOutlined } from '@ant-design/icons-vue';
import { InputSearch, Skeleton, Tree } from 'ant-design-vue';
import { treeList } from '#/api/sis/deviceChannel';
import type { TreeNode } from '#/api/common';

defineOptions({ inheritAttrs: false });

withDefaults(defineProps<{ showSearch?: boolean }>(), { showSearch: true });

const emit = defineEmits<{

  checked: [];
  /**
   * 点击节点的事件
   */
  reload: [];
  select: [];
}>();

const searchValue = defineModel('searchValue', {
  type: String,
  default: '',
});

/** 通道数据源 */
const channelTree = ref<TreeNode[]>([]);
/** 骨架屏加载 */
const showTreeSkeleton = ref<boolean>(true);

async function loadChannelTree() {
  showTreeSkeleton.value = true;
  searchValue.value = '';
  const ret = await treeList();
  channelTree.value = ret;
  showTreeSkeleton.value = false;
}

async function handleReload() {
  await loadChannelTree();
  emit('reload');
}

onMounted(loadChannelTree);
</script>

<template>
  <div class="h-[800px]" :class="$attrs.class">
    <Skeleton
      :loading="showTreeSkeleton"
      :paragraph="{ rows: 8 }"
      active
      class="p-[8px]"
    >
      <div
        class="flex h-full flex-col overflow-y-auto rounded-lg"
      >
        <!-- 固定在顶部 必须加上bg-background背景色 否则会产生'穿透'效果 -->
        <divx
          v-if="showSearch"
          class="z-100 sticky left-0 top-0 p-[8px]"
        >
          <InputSearch
            v-model:value="searchValue"
            :placeholder="$t('pages.common.search')"
            size="small"
          >
            <template #enterButton>
              <a-button @click="handleReload">
                <SyncOutlined class="text-primary" />
              </a-button>
            </template>
          </InputSearch>
        </divx>
        <div class="h-full overflow-x-hidden px-[8px]">
          <Tree
            v-bind="$attrs"
            v-if="channelTree.length > 0"
            :class="$attrs.class"
            :show-line="{ showLeafIcon: false }"
            :tree-data="channelTree"
            :virtual="false"
            default-expand-all
            checkable
            @select="$emit('select')"
            @check="$emit('checked')"
          >
            <template #title="{ label }">
              <span v-if="label.indexOf(searchValue) > -1">
                {{ label.substring(0, label.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{
                  label.substring(
                    label.indexOf(searchValue) + searchValue.length,
                  )
                }}
              </span>
              <span v-else>{{ label }}</span>
            </template>
          </Tree>
        </div>
      </div>
    </Skeleton>
  </div>
</template>
