<!--
 * @Author: Mm
 * @Date: 2025-03-10 10:42:57
 * @LastEditors: Mm
 * @LastEditTime: 2025-04-21 15:59:46
 * 不写bug的程序员不是一个好程序员!
-->
<script setup lang="ts">
import type { PropType } from "vue";

import type { DeptTree } from "#/api/system/user/model";

import { onMounted, ref, watch, computed } from "vue";

import { SyncOutlined } from "@ant-design/icons-vue";
import { Empty, InputSearch, Skeleton, Tree } from "ant-design-vue";

import { getDeptTree } from "#/api/system/user";

defineOptions({ inheritAttrs: false });

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

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

const searchValue = defineModel("searchValue", {
  type: String,
  default: "",
});
const expandedKeys = ref<any[]>([]);
const autoExpandParent = ref(true);
/** 部门数据源 */
type DeptTreeArray = DeptTree[];
const deptTreeArray = ref<DeptTreeArray>([]);
const filteredTreeData = ref<DeptTreeArray>([]);
/** 骨架屏加载 */
const showTreeSkeleton = ref<boolean>(true);

async function loadTree() {
  showTreeSkeleton.value = true;
  searchValue.value = "";
  selectDeptId.value = [];

  const ret = await getDeptTree();
  deptTreeArray.value = ret;
  expandedKeys.value = [deptTreeArray.value?.[0]?.id];
  filteredTreeData.value = ret;
  console.log(deptTreeArray.value, "deptTreeArray");

  showTreeSkeleton.value = false;
}

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

onMounted(() => {
  loadTree();
});

// 核心过滤逻辑：保留匹配节点及其父路径
const filterTree = (data: any, keyword: string, parentKeys = new Set()) => {
  return data
    .map((node: any) => {
      const newNode = { ...node };
      const isSelfMatched = newNode.label.toLowerCase().includes(keyword.toLowerCase());
      let hasMatchedChild = false;

      // 递归处理子节点
      if (newNode.children) {
        const filteredChildren = filterTree(newNode.children, keyword, parentKeys);
        hasMatchedChild = filteredChildren.length > 0;
        newNode.children = filteredChildren;
      }

      // 保留条件：自身匹配 或 有子节点匹配
      if (isSelfMatched || hasMatchedChild) {
        if (hasMatchedChild) parentKeys.add(newNode.id); // 收集需要展开的父节点
        return newNode;
      }

      return null;
    })
    .filter((node: any) => node !== null); // 过滤掉不匹配的节点
};

// 更新过滤后的树数据
const updateFilteredTree = (keyword: string) => {
  const expandKeysSet = new Set();
  const clonedData = deptTreeArray.value; // 深拷贝避免污染原始数据
  const filteredData = filterTree(clonedData, keyword, expandKeysSet);

  filteredTreeData.value = filteredData;
  expandedKeys.value = Array.from(expandKeysSet);
  autoExpandParent.value = true;
};

// 处理展开事件
const handleExpand = (keys: any) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

// 监听搜索词变化
watch(searchValue, (keyword) => {
  if (keyword.trim()) {
    updateFilteredTree(keyword.trim());
  } else {
    filteredTreeData.value = deptTreeArray.value;
    // expandedKeys.value = [];
    expandedKeys.value = [deptTreeArray.value?.[0]?.id];
  }
});
</script>

<template>
  <div :class="$attrs.class">
    <Skeleton :loading="showTreeSkeleton" :paragraph="{ rows: 8 }" active >
      <div class="bg-background flex h-full flex-col overflow-y-auto rounded-lg">
        <!-- 固定在顶部 必须加上bg-background背景色 否则会产生'穿透'效果 -->
        <div v-if="showSearch" class="bg-background 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>
        </div>
        <div class="h-full px-[8px] ">
          <Tree
            v-bind="$attrs"
            v-if="filteredTreeData.length > 0"
            v-model:selected-keys="selectDeptId"
            :class="$attrs.class"
            :field-names="{ title: 'label', key: 'id' }"
            :show-line="{ showLeafIcon: false }"
            :tree-data="filteredTreeData"
            :virtual="false"
            defaultExpandAll
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            @expand="handleExpand"
            @select="$emit('select')"
          >
            <template #title="{ label }">
              <span
                style="
                  display: flex;
                  align-items: center;
                  width: fit-content;
                  white-space: nowrap;
                  
                "
              >
                <img
                  width="16px"
                  height="16px"
                  src="../../../assets/logo.png"
                  alt=""
                  style="margin-right: 2px"
                />
                {{ label }}</span
              >
            </template>
          </Tree>
          <!-- 仅本人数据权限 可以考虑直接不显示 -->
          <div v-else class="mt-5">
            <Empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="无部门数据" />
          </div>
        </div>
      </div>
    </Skeleton>
  </div>
</template>
<style scoped>
.mm-tree{
  width: 260px;
  overflow-x: auto;
}
</style>
