<template>
  <div class="cascader-select">
    <el-cascader
      v-model="selectedValues"
      :options="treeData"
      :props="cascaderProps"
      :placeholder="placeholder"
      :show-all-levels="true"
      :collapse-tags="true"
      filterable
      clearable
      multiple
      @change="handleChange"
    >
      <template slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
        <span v-if="!node.isLeaf" class="custom-label">
          ({{ getChildLeafCount(data) }}个选项)
        </span>
      </template>
    </el-cascader>

    <!-- 选中标签的详细展示 -->
    <div class="selected-tags" v-if="value.length">
      <el-tag
        v-for="id in value"
        :key="id"
        closable
        size="small"
        class="tag-item"
        @close="handleRemoveTag(id)"
      >
        {{ getNodeFullPath(id) }}
      </el-tag>
    </div>
  </div>
</template>

<script>
import { fetchMaterialTags } from '@/api/report';
export default {
  name: 'MaterialTagSelect',

  props: {
    value: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择标签...'
    }
  },

  data() {
    return {
      selectedValues: [], // 用于el-cascader的选中值（包含完整路径）
      cascaderProps: {
        multiple: true,
        checkStrictly: true, // 可以选择任意一级节点
        value: 'id',
        label: 'name',
        children: 'children',
        emitPath: true, // 返回完整路径
        leaf: 'isLeaf',
        expandTrigger: 'hover'
      },
      tagData: []
    }
  },

  computed: {
    // 转换为树形结构
    treeData() {
      return this.buildTree(this.tagData)
    }
  },

  created() {
    this.fetchTags()

  },

  watch: {
    // 监听外部value变化，更新内部选中状态
    value: {
      immediate: true,
      handler(newVal) {
        this.updateSelectedValues(newVal)
      }
    }
  },

  methods: {
    fetchTags() {
      fetchMaterialTags().then(res => {
        if (res.status === 200) {
          this.tagData = res.result.data.map(item => ({
            id: item.id,
            name: item.name,
            parentId: item.parentId || null  // 确保null值标准化处理
          }));

        } else {
          this.$message.error('获取素材标签失败');
        }
      }).catch(error => {
        console.error("请求失败:", error);
        this.$message.error('请求异常');
      });
    },
    // 构建树形数据
    buildTree(items) {
      const itemMap = new Map()
      const result = []

      // 创建所有节点
      items.forEach(item => {
        const node = {
          id: item.id,
          name: item.name,
          parentId: item.parentId,
          children: [],
          isLeaf: true // 默认为叶子节点，后面会更新
        }
        itemMap.set(item.id, node)
      })

      // 建立父子关系
      items.forEach(item => {
        const node = itemMap.get(item.id)
        if (item.parentId === null) {
          result.push(node)
        } else {
          const parent = itemMap.get(item.parentId)
          if (parent) {
            parent.children.push(node)
            parent.isLeaf = false // 有子节点，不是叶子节点
          }
        }
      })

      return result
    },

    // 获取节点的所有叶子节点数量
    getChildLeafCount(node) {
      let count = 0
      const countLeaves = (n) => {
        if (n.isLeaf) {
          count++
        } else if (n.children) {
          n.children.forEach(countLeaves)
        }
      }
      countLeaves(node)
      return count
    },

    // 处理选择变化
    handleChange(values) {
      // values 是一个数组，每个元素都是一个路径数组
      const selectedIds = values
        .map(path => path[path.length - 1]) // 获取每个路径的最后一个节点ID
        .filter(id => this.isLeafNode(id)) // 只保留叶子节点

      this.$emit('input', selectedIds)
      this.$emit('change', selectedIds)
    },

    // 判断是否为叶子节点
    isLeafNode(id) {
      const findNode = (nodes) => {
        for (const node of nodes) {
          if (node.id === id) {
            return node.isLeaf
          }
          if (node.children) {
            const found = findNode(node.children)
            if (found !== undefined) {
              return found
            }
          }
        }
      }
      return findNode(this.treeData)
    },

    // 获取节点完整路径名称
    getNodeFullPath(id) {
      const path = []
      const findPath = (nodes) => {
        for (const node of nodes) {
          path.push(node.name)
          if (node.id === id) {
            return true
          }
          if (node.children && findPath(node.children)) {
            return true
          }
          path.pop()
        }
        return false
      }
      findPath(this.treeData)
      return path.join(' / ')
    },

    // 处理标签移除
    handleRemoveTag(id) {
      const newValue = this.value.filter(v => v !== id)
      this.$emit('input', newValue)
      this.$emit('change', newValue)
    },

    // 更新内部选中状态
    updateSelectedValues(selectedIds) {
      const values = []
      const findPaths = (nodes, currentPath = []) => {
        for (const node of nodes) {
          const path = [...currentPath, node.id]
          if (selectedIds.includes(node.id) && node.isLeaf) {
            values.push(path)
          }
          if (node.children) {
            findPaths(node.children, path)
          }
        }
      }
      findPaths(this.treeData)
      this.selectedValues = values
    }
  }
}
</script>

<style scoped>



</style>
