<template>
  <div class="permission-tree">
    <div v-for="item in items" :key="item.id" class="tree-node">
      <div class="node-content" :style="{ paddingLeft: `${level * 24}px` }">
        <!-- 展开/折叠按钮 -->
        <span v-if="hasChildren(item)" class="expand-icon" @click="toggleExpand(item.id)">
          <icon-right v-if="!isExpanded(item.id)" />
          <icon-down v-else />
        </span>
        <span v-else class="expand-icon-placeholder" />

        <!-- 复选框 -->
        <a-checkbox :model-value="isChecked(item.id)" :indeterminate="isIndeterminate(item)" @change="handleCheck(item.id, $event)" />

        <!-- 名称 -->
        <span class="node-name">{{ item.title }}</span>
      </div>

      <!-- 子节点 -->
      <div v-if="hasChildren(item) && isExpanded(item.id)" class="children">
        <PermissionTree
          :items="getChildren(item)"
          :selected-permissions="selectedPermissions"
          :level="level + 1"
          :expanded-keys="expandedKeys"
          @change="handleChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'

export interface PermissionItem {
  id: number
  title: string
  children?: PermissionItem[]
}

const props = withDefaults(
  defineProps<{
    items: PermissionItem[]
    selectedPermissions: number[]
    level?: number
    expandedKeys?: Set<number>
  }>(),
  {
    level: 0,
    expandedKeys: () => new Set(),
  }
)

const emit = defineEmits<{
  (e: 'change', permissions: number[]): void
}>()

// 本地展开状态
const localExpandedKeys = ref<Set<number>>(new Set())
const expandedKeys = computed(() => (props.expandedKeys.size > 0 ? props.expandedKeys : localExpandedKeys.value))

// 检查是否有子节点
const hasChildren = (item: PermissionItem) => {
  return item.children && item.children.length > 0
}

// 获取子节点
const getChildren = (item: PermissionItem): PermissionItem[] => {
  return item.children || []
}

// 检查是否展开
const isExpanded = (id: number) => {
  return expandedKeys.value.has(id)
}

// 切换展开状态
const toggleExpand = (id: number) => {
  if (expandedKeys.value.has(id)) {
    expandedKeys.value.delete(id)
  } else {
    expandedKeys.value.add(id)
  }
}

// 检查是否选中
const isChecked = (id: number) => {
  return props.selectedPermissions.includes(id)
}

// 检查是否半选状态
const isIndeterminate = (item: PermissionItem) => {
  if (!hasChildren(item)) return false
  const childIds = getAllChildIds(item)
  const selectedCount = childIds.filter((id) => props.selectedPermissions.includes(id)).length
  return selectedCount > 0 && selectedCount < childIds.length
}

// 递归获取所有子节点ID
const getAllChildIds = (item: PermissionItem): number[] => {
  const ids: number[] = []
  if (item.children) {
    item.children.forEach((child) => {
      ids.push(child.id)
      ids.push(...getAllChildIds(child))
    })
  }
  return ids
}

// 根据ID查找权限项
const findItemById = (items: PermissionItem[], id: number): PermissionItem | null => {
  for (const item of items) {
    if (item.id === id) return item
    if (item.children) {
      const found = findItemById(item.children, id)
      if (found) return found
    }
  }
  return null
}

// 获取父节点ID
const getParentIds = (items: PermissionItem[], targetId: number, parentIds: number[] = []): number[] => {
  for (const item of items) {
    if (item.children) {
      if (item.children.some((child) => child.id === targetId)) {
        return [...parentIds, item.id]
      }
      const result = getParentIds(item.children, targetId, [...parentIds, item.id])
      if (result.length > 0) return result
    }
  }
  return []
}

// 处理选中状态变化
const handleCheck = (id: number, checked: boolean) => {
  let newPermissions = [...props.selectedPermissions]

  if (checked) {
    // 添加当前权限
    if (!newPermissions.includes(id)) {
      newPermissions.push(id)
    }

    // 添加所有子权限
    const item = findItemById(props.items, id)
    if (item) {
      const childIds = getAllChildIds(item)
      childIds.forEach((childId) => {
        if (!newPermissions.includes(childId)) {
          newPermissions.push(childId)
        }
      })
    }
  } else {
    // 移除当前权限
    newPermissions = newPermissions.filter((pId) => pId !== id)

    // 移除所有子权限
    const item = findItemById(props.items, id)
    if (item) {
      const childIds = getAllChildIds(item)
      newPermissions = newPermissions.filter((pId) => !childIds.includes(pId))
    }

    // 移除父权限
    const parentIds = getParentIds(props.items, id)
    parentIds.forEach((parentId) => {
      newPermissions = newPermissions.filter((pId) => pId !== parentId)
    })
  }

  emit('change', newPermissions)
}

// 处理子组件变化
const handleChange = (permissions: number[]) => {
  emit('change', permissions)
}
</script>

<script lang="ts">
export default {
  name: 'PermissionTree',
}
</script>

<style scoped lang="less">
.permission-tree {
  .tree-node {
    .node-content {
      display: flex;
      align-items: center;
      padding: 4px 0;

      .expand-icon {
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: var(--color-text-2);
        transition: color 0.2s;

        &:hover {
          color: rgb(var(--primary-6));
        }
      }

      .expand-icon-placeholder {
        width: 20px;
        height: 20px;
      }

      .node-name {
        margin-left: 8px;
      }
    }

    .children {
      // 子节点样式
    }
  }
}
</style>
