<template>
  <el-cascader
    v-model="internalValue"
    :options="categoryOptions"
    :props="categoryProps"
    clearable
    placeholder="请选择资料分类"
    @change="handleChange"
  />
</template>

<script>
import * as MaterialInfoApi from "@/api/server/materialinfo";

export default {
  props: {
    value: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      internalValue: [],
      categoryOptions: [],  // 最多3级的数据
      categoryProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true,  // 必须按层级选择
        emitPath: true,       // 不返回完整路径
      }
    };
  },
  methods: {
    // 加载分类树，并限制深度为3级
    async loadCategoryTree() {
      const res = await MaterialInfoApi.getMaterialCategoryTree();
      this.categoryOptions = this.limitTreeDepth(res.data, 3);
    },

    // 递归限制树的深度
    limitTreeDepth(nodes, maxDepth, currentDepth = 1) {
      if (currentDepth >= maxDepth) {
        // 达到最大深度时，移除子节点（防止继续展开）
        return nodes.map(node => ({
          ...node,
          children: undefined  // 或 children: null
        }));
      }
      // 递归处理子节点
      return nodes.map(node => ({
        ...node,
        children: node.children
          ? this.limitTreeDepth(node.children, maxDepth, currentDepth + 1)
          : undefined
      }));
    },

    // 处理选择变化
    handleChange(value) {
      if (!value || value.length === 0) {
        this.$emit('input', null);
        this.$emit('update:categoryName', '');
        return;
      }
      // 获取末级 ID
      const categoryId = value[value.length - 1];
      this.$emit('input', categoryId);

      // 根据 ID 路径找名称路径
      const namePath = this.getLabelPathByValuePath(value, this.categoryOptions);
      const categoryName = namePath.join(" / ");
      this.$emit('update:categoryName', categoryName);
    },
    getLabelPathByValuePath(valuePath, nodes) {
      const labels = [];
      let currentNodes = nodes;
      for (const id of valuePath) {
        const node = currentNodes.find(n => n.id === id);
        if (!node) break;
        labels.push(node.name);
        currentNodes = node.children || [];
      }
      return labels;
    },
    findPathById(id, nodes, path = []) {
      for (const node of nodes) {
        if (node.id === id) {
          return [...path, node.id];
        }
        if (node.children && node.children.length > 0) {
          const res = this.findPathById(id, node.children, [...path, node.id]);
          if (res.length) return res;
        }
      }
      return [];
    }



  },
  created() {
    this.loadCategoryTree();
  },
  watch: {
    // 监听外部传入的 categoryId
    async value(newVal) {
      if (!newVal) {
        this.internalValue = [];
        return;
      }
      if (this.categoryOptions.length === 0) {
        await this.loadCategoryTree(); // 确保分类数据已加载
      }
      this.internalValue = this.findPathById(newVal, this.categoryOptions);
    }
  },

};
</script>
