<template>
  <view class="tree-view">
    <view
      v-for="(item, index) in flattenedTree"
      :key="item.id"
      class="tree-item"
      :style="{ paddingLeft: (item.level * 40 + 24) + 'rpx' }"
    >
      <!-- 展开/收起图标 -->
      <view class="expand-icon" @click="toggleExpand(item)" v-if="item.hasChildren">
        <text class="icon-text">{{ item.expanded ? '▼' : '▶' }}</text>
      </view>
      <view class="expand-icon placeholder" v-else></view>
      
      <!-- 文件夹图标 -->
      <view class="folder-icon-wrapper">
        <image 
          :src="getIcon(item.type)" 
          mode="aspectFit" 
          class="folder-icon" 
        />
      </view>
      
      <!-- 文件夹名称 -->
      <text class="folder-name">{{ item.name }}</text>
      
      <!-- 选择按钮 -->
      <view 
        class="select-btn" 
        :class="{ disabled: !item.selectable }"
        @click="handleSelect(item)"
      >
        <text class="select-text">{{ item.selectable ? '选择' : '无权限' }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'TreeView',
  props: {
    treeData: {
      type: Array,
      default: () => []
    },
    iconMap: {
      type: Object,
      default: () => ({
        0: '/static/pages/scan/folderSelect/folder.svg',
        1: '/static/pages/scan/folderSelect/country.svg',
        2: '/static/pages/scan/folderSelect/center.svg'
      })
    },
    // 权限配置：'*' 表示全部可选，'1,2,3' 表示只有这些ID及其子节点可选
    permission: {
      type: String,
      default: '*'
    }
  },
  data() {
    return {
      expandedIds: new Set(),
      flattenedTree: [],
      permissionIds: new Set(), // 有权限的节点ID集合
      allowedNodeIds: new Set() // 允许选择的节点ID集合（包括子节点）
    }
  },
  watch: {
    treeData: {
      handler() {
        console.log('TreeView - treeData 变化:', this.treeData)
        this.parsePermission()
        this.buildFlattenedTree()
      },
      immediate: true,
      deep: true
    },
    permission: {
      handler() {
        console.log('TreeView - permission 变化:', this.permission)
        this.parsePermission()
        this.buildFlattenedTree()
      },
      immediate: true
    }
  },
  methods: {
    // 解析权限配置
    parsePermission() {
      console.log('========== 解析权限 ==========')
      console.log('权限配置:', this.permission)
      
      this.permissionIds.clear()
      this.allowedNodeIds.clear()
      
      // 如果是 '*'，表示全部可选
      if (this.permission === '*') {
        console.log('权限为 *，全部节点可选')
        return
      }
      
      // 解析逗号分隔的ID列表
      if (this.permission && this.permission.trim()) {
        const ids = this.permission.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        ids.forEach(id => this.permissionIds.add(id))
        console.log('有权限的节点ID:', Array.from(this.permissionIds))
        
        // 收集所有允许选择的节点（包括子节点）
        this.collectAllowedNodes(this.treeData)
        console.log('允许选择的节点ID:', Array.from(this.allowedNodeIds))
      }
    },
    
    // 递归收集允许选择的节点
    collectAllowedNodes(nodes) {
      if (!nodes || !Array.isArray(nodes)) return
      
      nodes.forEach(node => {
        // 如果当前节点有权限，则它及其所有子节点都可选
        if (this.permissionIds.has(node.id)) {
          this.addNodeAndChildren(node)
        } else if (node.children && node.children.length > 0) {
          // 继续检查子节点
          this.collectAllowedNodes(node.children)
        }
      })
    },
    
    // 添加节点及其所有子节点到允许列表
    addNodeAndChildren(node) {
      this.allowedNodeIds.add(node.id)
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.addNodeAndChildren(child)
        })
      }
    },
    
    // 检查节点是否可选
    isNodeSelectable(nodeId) {
      // 如果权限为 '*'，全部可选
      if (this.permission === '*') {
        return true
      }
      // 否则检查是否在允许列表中
      return this.allowedNodeIds.has(nodeId)
    },
    
    // 将树形数据扁平化
    buildFlattenedTree() {
      console.log('========== 开始构建扁平化树 ==========')
      this.flattenedTree = []
      this.flattenNode(this.treeData, 0)
      console.log('扁平化树构建完成，节点数:', this.flattenedTree.length)
      console.log('扁平化树:', this.flattenedTree)
    },
    
    // 递归扁平化节点
    flattenNode(nodes, level, parentPath = []) {
      if (!nodes || !Array.isArray(nodes)) {
        console.log('节点不是数组:', nodes)
        return
      }
      
      nodes.forEach(node => {
        const hasChildren = node.children && node.children.length > 0
        const isExpanded = this.expandedIds.has(node.id)
        const isSelectable = this.isNodeSelectable(node.id)
        
        // 构建当前节点的完整路径
        const currentPath = [...parentPath, node.name]
        const fullPath = currentPath.join('/')
        
        // 添加当前节点
        this.flattenedTree.push({
          id: node.id,
          name: node.name,
          type: node.type,
          level: level,
          hasChildren: hasChildren,
          expanded: isExpanded,
          selectable: isSelectable,
          fullPath: fullPath, // 完整路径
          originalNode: node
        })
        
        console.log(`添加节点: ${node.name}, level: ${level}, hasChildren: ${hasChildren}, expanded: ${isExpanded}, selectable: ${isSelectable}, path: ${fullPath}`)
        
        // 如果展开且有子节点，递归处理子节点
        if (isExpanded && hasChildren) {
          console.log(`展开子节点: ${node.name}, 子节点数: ${node.children.length}`)
          this.flattenNode(node.children, level + 1, currentPath)
        }
      })
    },
    
    // 切换展开/收起
    toggleExpand(item) {
      console.log('========== 切换展开状态 ==========')
      console.log('节点:', item.name)
      console.log('当前展开状态:', item.expanded)
      
      if (item.expanded) {
        this.expandedIds.delete(item.id)
        console.log('收起节点')
      } else {
        this.expandedIds.add(item.id)
        console.log('展开节点')
      }
      
      // 重新构建扁平化树
      this.buildFlattenedTree()
    },
    
    // 获取图标
    getIcon(type) {
      return this.iconMap[type] || this.iconMap[0]
    },
    
    // 选择节点
    handleSelect(item) {
      console.log('选择节点:', item.name, '是否可选:', item.selectable)
      console.log('完整路径:', item.fullPath)
      
      if (!item.selectable) {
        uni.showToast({
          title: '无权限选择此文件夹',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 返回节点信息，包含完整路径
      this.$emit('select', {
        ...item.originalNode,
        fullPath: item.fullPath
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-view {
  .tree-item {
    display: flex;
    align-items: center;
    padding: 20rpx 24rpx;
    border-bottom: 1rpx solid #f5f5f5;
    background: #ffffff;
    
    &:active {
      background: #f8f8f8;
    }
    
    .expand-icon {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8rpx;
      
      &.placeholder {
        visibility: hidden;
      }
      
      .icon-text {
        font-size: 20rpx;
        color: #999999;
      }
    }
    
    .folder-icon-wrapper {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16rpx;
      
      .folder-icon {
        width: 48rpx;
        height: 48rpx;
      }
    }
    
    .folder-name {
      flex: 1;
      font-size: 28rpx;
      color: #333333;
    }
    
    .select-btn {
      padding: 8rpx 24rpx;
      background: #1ec9c9;
      border-radius: 24rpx;
      
      &:active {
        background: #1ab8b8;
      }
      
      &.disabled {
        background: #cccccc;
        
        &:active {
          background: #cccccc;
        }
      }
      
      .select-text {
        font-size: 24rpx;
        color: #ffffff;
        font-weight: 500;
      }
    }
  }
}
</style>
