<script setup lang="ts">
import type { PropType } from "vue";
import { onMounted, ref } from "vue";
import { handleNode } from "@vben/utils";
import { Empty, Skeleton, Tree } from "ant-design-vue";
import { communityTree } from "#/api/property/community";
import type { CommunityVO } from "#/api/property/community/model";

defineOptions({ inheritAttrs: false });

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

const emit = defineEmits<{
  /**
   * 点击刷新按钮的事件
   */
  reload: [];
  /**
   * 点击节点的事件
   */
  select: [];
}>();

const selectFloorId = defineModel("selectFloorId", {
  type: Array as PropType<string[]>,
});

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

type TreeArray = CommunityVO[];
const treeArray = ref<TreeArray>([]);
/** 骨架屏加载 */
const showTreeSkeleton = ref<boolean>(true);

async function loadTree() {
  showTreeSkeleton.value = true;
  searchValue.value = "";
  selectFloorId.value = [];
  const ret = await communityTree(3);
  const splitStr = "/";
  handleNode(ret, "label", splitStr, function (node: any) {
    if (node.level != 3) {
      node.disabled = true;
    }
  });
  treeArray.value = ret;
  showTreeSkeleton.value = false;
}

onMounted(loadTree);
</script>

<template>
  <div :class="$attrs.class">
    <Skeleton :loading="showTreeSkeleton"
              :paragraph="{ rows: 8 }"
              active
              class="p-[8px] flex-1 min-h-0">
      <div class="bg-background flex h-full flex-col overflow-y-auto rounded-lg">
        <div class="h-full overflow-x-hidden px-[8px]">
          <Tree v-bind="$attrs"
                v-if="treeArray.length > 0"
                v-model:selected-keys="selectFloorId"
                :field-names="{ title: 'label', key: 'id' }"
                :show-line="{ showLeafIcon: false }"
                :tree-data="treeArray"
                :virtual="false"
                default-expand-all
                @select="$emit('select')">
            <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 v-else
               class="mt-5">
            <Empty :image="Empty.PRESENTED_IMAGE_SIMPLE"
                   description="暂无数据" />
          </div>
        </div>
      </div>
    </Skeleton>
  </div>
</template>
