<script setup lang="ts">
import type { PropType } from 'vue';

import type { CategoryTree } from '#/api/workflow/category/model';

import { onMounted, ref, watch } from 'vue';

import { ElInput, ElSkeleton, ElTree } from 'element-plus';

import { categoryTree } from '#/api/workflow/category';
import { Refresh, Search } from '@element-plus/icons-vue';

defineOptions({ inheritAttrs: false });

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

const selectCode = defineModel('selectCode', {
  required: true,
  type: Number as PropType<number>,
  default: 0
});

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

const categoryTreeArray = ref<CategoryTree[]>([]);
/** 骨架屏加载 */
const showTreeSkeleton = ref<boolean>(true);
/** 树引用 */
const treeRef = ref<InstanceType<typeof ElTree>>();

// 过滤树形图回调
const filterNode = (value: string, data: CategoryTree) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 监听搜索值变化，触发树节点过滤
watch(searchValue, (val) => {
  treeRef.value?.filter(val);
});

async function loadTree() {
  showTreeSkeleton.value = true;
  searchValue.value = '';
  selectCode.value = 0;

  const treeData = await categoryTree();

  categoryTreeArray.value = treeData;
  showTreeSkeleton.value = false;
}

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

onMounted(loadTree);
</script>

<template>
  <div :class="$attrs.class">
    <ElSkeleton :loading="showTreeSkeleton" :rows="8" animated class="p-[8px]">
      <div
        class="bg-background flex h-full flex-col overflow-y-auto rounded-lg"
      >
        <!-- 固定在顶部 必须加上bg-background背景色 否则会产生'穿透'效果 -->
        <div class="bg-background z-100 sticky left-0 top-0 p-[8px]">
          <div class="flex gap-1">
            <ElInput
              v-model="searchValue"
              :placeholder="$t('pages.common.search')"
              size="small"
              clearable
              :prefix-icon="Search"
            />
            <el-button size="small" type="primary" :icon="Refresh" @click="handleReload" />
          </div>
        </div>
        <div class="h-full overflow-x-hidden px-[8px]">
          <ElTree
            v-bind="$attrs"
            v-if="categoryTreeArray.length > 0"
            ref="treeRef"
            :default-checked-keys="selectCode ? [selectCode] : []"
            :class="$attrs.class"
            :props="{ label: 'label', value: 'id', children: 'children' }"
            :data="categoryTreeArray"
            :expand-on-click-node="false"
            :default-expand-all="true"
            :filter-node-method="filterNode"
            @node-click="(data) => {
              // 点击节点时更新选中值
              selectCode = data.id;
              $emit('select');
            }"
          >
          </ElTree>
        </div>
      </div>
    </ElSkeleton>
  </div>
</template>



