<template>
  <ElDialog
    v-model="visible"
    title="角色权限分配"
    width="1000px"
    align-center
    class="permission-dialog"
    @close="handleClose"
  >
    <div v-loading="loading" class="permission-container flex h-[65vh]">
      <!-- 左侧：一级模块导航 -->
      <div class="module-nav w-[200px] border-r border-gray-100 pr-2">
        <ElScrollbar>
          <div
            v-for="item in permissionTree"
            :key="item.id"
            :class="['nav-item', activeModuleId === item.id ? 'active' : '']"
            @click="activeModuleId = item.id"
          >
            <span class="truncate">{{ item.name }}</span>
            <ElTag
              v-if="getModuleSelectedCount(item) > 0"
              size="small"
              round
              effect="light"
              class="ml-auto"
            >
              {{ getModuleSelectedCount(item) }}
            </ElTag>
          </div>
        </ElScrollbar>
      </div>

      <!-- 右侧：权限点展示区 -->
      <div class="module-content flex-1 pl-6 overflow-hidden flex flex-col">
        <div v-if="activeModule" class="flex items-center justify-between mb-4 pb-2 border-b">
          <div class="flex items-center gap-2">
            <h3 class="text-lg font-bold">{{ activeModule.name }}</h3>
            <span class="text-xs text-gray-400">请勾选该模块下的操作权限</span>
          </div>
          <div class="flex items-center gap-4">
            <ElCheckbox
              :model-value="isModuleAllSelected(activeModule)"
              :indeterminate="isModuleIndeterminate(activeModule)"
              @change="(val) => handleSelectAllModule(activeModule, !!val)"
            >
              全选当前模块
            </ElCheckbox>
          </div>
        </div>

        <ElScrollbar v-if="activeModule" class="flex-1">
          <div v-for="sub in activeModule.children" :key="sub.id" class="sub-module mb-6">
            <div class="flex items-center gap-2 mb-3">
              <div class="w-1 h-4 bg-primary rounded-full"></div>
              <span class="font-bold">{{ sub.name }}</span>
              <ElCheckbox
                size="small"
                :model-value="isSubModuleAllSelected(sub)"
                :indeterminate="isSubModuleIndeterminate(sub)"
                class="ml-4"
                @change="(val) => handleSelectSubModule(sub, !!val)"
              >
                全选
              </ElCheckbox>
            </div>

            <!-- 权限点平铺 -->
            <div class="grid grid-cols-2 lg:grid-cols-3 gap-3 pl-3">
              <div
                v-for="perm in sub.children"
                :key="perm.id"
                class="perm-item p-2 rounded hover:bg-gray-50 border border-transparent hover:border-gray-100 transition-all"
                :class="{ 'bg-blue-50/50 border-blue-100': isChecked(perm.id) }"
                @click="togglePermission(perm.id)"
              >
                <div class="flex items-start gap-2">
                  <ElCheckbox
                    :model-value="isChecked(perm.id)"
                    @update:model-value="togglePermission(perm.id)"
                    @click.stop
                  />
                  <div class="flex flex-col gap-0.5">
                    <div class="flex items-center gap-1">
                      <ElTag size="small" :type="getPermissionTagType(perm.code)" effect="plain">
                        {{ getPermissionAction(perm.code) }}
                      </ElTag>
                      <span class="text-sm font-medium leading-tight">{{ perm.name }}</span>
                    </div>
                    <span v-if="perm.description" class="text-[11px] text-gray-400 leading-tight">
                      {{ perm.description }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </ElScrollbar>

        <div v-else class="flex flex-col items-center justify-center h-full text-gray-400">
          <ElIcon :size="48"><Collection /></ElIcon>
          <p class="mt-2">请选择左侧模块进行权限配置</p>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex items-center justify-between w-full">
        <div class="text-sm text-gray-500">
          已选择 <span class="text-primary font-bold">{{ checkedKeys.length }}</span> 项权限
        </div>
        <div class="flex gap-2">
          <ElButton @click="handleClose">取消</ElButton>
          <ElButton type="primary" :loading="saving" @click="savePermission">保存更改</ElButton>
        </div>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { ElMessage, ElTag } from 'element-plus'
  import { Collection } from '@element-plus/icons-vue'
  import { fetchGetPermissionTree } from '@/api/permission'
  import {
    fetchGetTenantRolePermissions,
    fetchUpdateTenantRolePermissions
  } from '@/api/tenant-role'

  type RoleDto = Api.TenantRole.RoleDto

  interface Props {
    modelValue: boolean
    roleData?: RoleDto
    tenantId?: string | number
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    roleData: undefined,
    tenantId: undefined
  })

  const emit = defineEmits<Emits>()

  const loading = ref(false)
  const saving = ref(false)
  const checkedKeys = ref<string[]>([])
  const permissionTree = ref<any[]>([])
  const activeModuleId = ref<string | number>('')

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const activeModule = computed(() => {
    return permissionTree.value.find((m) => m.id === activeModuleId.value)
  })

  // 获取模块选中的数量
  const getModuleSelectedCount = (module: any) => {
    let count = 0
    const traverse = (items: any[]) => {
      items.forEach((item) => {
        if (!item.children || item.children.length === 0) {
          if (checkedKeys.value.includes(String(item.id))) count++
        } else {
          traverse(item.children)
        }
      })
    }
    if (module.children) traverse(module.children)
    return count
  }

  const isChecked = (id: string | number) => checkedKeys.value.includes(String(id))

  const togglePermission = (id: string | number) => {
    const sId = String(id)
    const index = checkedKeys.value.indexOf(sId)
    if (index > -1) {
      checkedKeys.value.splice(index, 1)
    } else {
      checkedKeys.value.push(sId)
    }
  }

  // 子模块全选
  const handleSelectSubModule = (sub: any, selected: boolean) => {
    const ids: string[] = []
    const traverse = (items: any[]) => {
      items.forEach((item) => {
        if (!item.children || item.children.length === 0) {
          ids.push(String(item.id))
        } else {
          traverse(item.children)
        }
      })
    }
    traverse(sub.children || [])

    ids.forEach((id) => {
      const idx = checkedKeys.value.indexOf(id)
      if (selected && idx === -1) checkedKeys.value.push(id)
      if (!selected && idx > -1) checkedKeys.value.splice(idx, 1)
    })
  }

  const isSubModuleAllSelected = (sub: any) => {
    const ids: string[] = []
    const traverse = (items: any[]) => {
      items.forEach((item) => {
        if (!item.children || item.children.length === 0) {
          ids.push(String(item.id))
        } else {
          traverse(item.children)
        }
      })
    }
    traverse(sub.children || [])
    return ids.length > 0 && ids.every((id) => checkedKeys.value.includes(id))
  }

  const isSubModuleIndeterminate = (sub: any) => {
    const ids: string[] = []
    const traverse = (items: any[]) => {
      items.forEach((item) => {
        if (!item.children || item.children.length === 0) {
          ids.push(String(item.id))
        } else {
          traverse(item.children)
        }
      })
    }
    traverse(sub.children || [])
    const checkedCount = ids.filter((id) => checkedKeys.value.includes(id)).length
    return checkedCount > 0 && checkedCount < ids.length
  }

  // 主模块全选
  const handleSelectAllModule = (module: any, selected: boolean) => {
    module.children?.forEach((sub: any) => handleSelectSubModule(sub, selected))
  }

  const isModuleAllSelected = (module: any) => {
    return module.children?.every((sub: any) => isSubModuleAllSelected(sub))
  }

  const isModuleIndeterminate = (module: any) => {
    if (isModuleAllSelected(module)) return false
    return module.children?.some(
      (sub: any) => isSubModuleIndeterminate(sub) || isSubModuleAllSelected(sub)
    )
  }

  const getPermissionTagType = (code: string) => {
    if (!code) return 'info'
    const lower = code.toLowerCase()
    if (lower.includes('create') || lower.includes('add')) return 'primary'
    if (lower.includes('read') || lower.includes('get') || lower.includes('list')) return 'success'
    if (lower.includes('update') || lower.includes('edit')) return 'warning'
    if (lower.includes('delete') || lower.includes('remove')) return 'danger'
    return 'info'
  }

  const getPermissionAction = (code: string) => {
    if (!code) return '权限'
    const parts = code.split(':')
    const last = parts[parts.length - 1]
    const actionMap: Record<string, string> = {
      read: '查看',
      create: '新增',
      update: '修改',
      delete: '删除',
      export: '导出',
      audit: '审核'
    }
    return actionMap[last] || last
  }

  const listToTree = (list: any[]): any[] => {
    const map = new Map<string, any>()
    const roots: any[] = []
    list.forEach((item) => {
      const node = { ...item, id: String(item.id), children: [] }
      map.set(node.id, node)
    })
    list.forEach((item) => {
      const sId = String(item.id)
      const node = map.get(sId)
      if (item.parentId && map.has(String(item.parentId))) {
        map.get(String(item.parentId)).children.push(node)
      } else {
        roots.push(node)
      }
    })
    return roots
  }

  const loadData = async () => {
    if (!props.roleData || !props.tenantId) return
    loading.value = true
    try {
      const [treeRes, permissions] = await Promise.all([
        fetchGetPermissionTree(),
        fetchGetTenantRolePermissions(props.tenantId, props.roleData.id)
      ])

      if (treeRes && treeRes.length > 0) {
        const hasChildren = treeRes.some((item: any) => item.children && item.children.length)
        const rawTree = hasChildren ? treeRes : listToTree(treeRes)

        // 深度优先遍历，提取所有真正的权限点（叶子节点）并按其“父路径”分组
        permissionTree.value = rawTree.map((module: any) => {
          const subModulesMap = new Map<string, any>()

          const collectPermissions = (node: any, parentName: string) => {
            const isLeaf = !node.children || node.children.length === 0
            if (isLeaf) {
              if (!subModulesMap.has(parentName)) {
                subModulesMap.set(parentName, {
                  id: `group-${parentName}-${module.id}`,
                  name: parentName,
                  children: []
                })
              }
              subModulesMap.get(parentName).children.push(node)
            } else {
              node.children.forEach((child: any) => {
                collectPermissions(child, node.name)
              })
            }
          }

          module.children?.forEach((child: any) => {
            collectPermissions(child, child.children?.length ? child.name : module.name)
          })

          return {
            ...module,
            children: Array.from(subModulesMap.values())
          }
        })

        if (permissionTree.value.length > 0) {
          activeModuleId.value = permissionTree.value[0].id
        }
      }

      checkedKeys.value = Array.isArray(permissions)
        ? permissions.map((item: any) => {
            const id = item?.id ?? item?.permissionId ?? item
            return String(id)
          })
        : []
    } catch (error) {
      void error
      ElMessage.error('加载权限数据失败')
    } finally {
      loading.value = false
    }
  }

  watch(
    () => props.modelValue,
    (val) => {
      if (val) loadData()
    }
  )

  const handleClose = () => {
    visible.value = false
  }

  const savePermission = async () => {
    if (!props.roleData || !props.tenantId) return
    saving.value = true
    try {
      await fetchUpdateTenantRolePermissions(props.tenantId, props.roleData.id, checkedKeys.value)
      ElMessage.success('权限保存成功')
      emit('success')
      handleClose()
    } catch (error) {
      console.error(error)
    } finally {
      saving.value = false
    }
  }
</script>

<style scoped lang="scss">
  .permission-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
      border-top: 1px solid var(--el-border-color-lighter);
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
  }

  .nav-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    margin-bottom: 4px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.2s;

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    &.active {
      font-weight: bold;
      color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }
  }

  .perm-item {
    cursor: pointer;
    user-select: none;
  }
</style>
