<template>
  <GiTable
    ref="tableRef"
    row-key="id"
    :data="tableData"
    :columns="columns"
    :loading="loading"
    :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
    :pagination="false"
    :disabled-tools="['fullscreen', 'size', 'setting']"
    :row-selection="{ type: 'checkbox', showCheckedAll, selectRowKeys: selectedKeys }"
    @select="select"
    @select-all="selectAll"
    @refresh="refresh"
  >
    <template #toolbar-left>
      <a-button v-permission="['system:role:updatePermission']" type="primary" :disabled="disabled" @click="save">
        <template #icon><icon-save /></template>保存权限
      </a-button>
    </template>
    <template #toolbar-right>
      <a-radio-group v-model="isCascade" type="button" :disabled="disabled">
        <a-radio :value="true">节点关联</a-radio>
        <a-radio :value="false">节点独立</a-radio>
      </a-radio-group>
      <a-button @click="onExpanded">
        <template #icon>
          <icon-list v-if="isExpanded" />
          <icon-mind-mapping v-else />
        </template>
        <template #default>
          <span v-if="!isExpanded">展开</span>
          <span v-else>折叠</span>
        </template>
      </a-button>
    </template>
    <template #expand-icon="{ expanded }">
      <IconDown v-if="expanded" />
      <IconRight v-else />
    </template>
    <template #title="{ record }">
      <GiSvgIcon :name="record.icon" :size="15" />
      <span style="margin-left: 5px; vertical-align: middle">{{ record.title }}</span>
    </template>
    <template #permissions="{ record }">
      <div v-if="record.permissions && record.permissions.length > 0">
        <a-checkbox-group v-model="record.checkedPermissions" :disabled="disabled" @change="selectPermission(record)">
          <a-checkbox v-for="permission in record.permissions" :key="permission.id" :value="permission.id">
            {{ permission.title }}
          </a-checkbox>
        </a-checkbox-group>
      </div>
    </template>
  </GiTable>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { Message, type TableInstance } from '@arco-design/web-vue'
import { type MenuResp } from '@/apis/system/menu'
import { getMenuTreeForRole, transformMenusWithPermissions, getRoleMenuIds, assignRoleMenus } from '@/apis/system/menu-adapter'
import { isMobile } from '@/utils'
import type GiTable from '@/components/GiTable/index.vue'
import { useTable } from '@/hooks'
import { getRole, updateRolePermission, getRoleDetail } from '@/apis'
import has from '@/utils/has'

// 扩展菜单类型以支持权限管理
interface ExtendedMenuResp extends MenuResp {
  permissions?: PermissionItem[]
  checkedPermissions?: (string | number)[]
  isChecked?: boolean
  disabled?: boolean
}

interface PermissionItem {
  id: string | number
  title: string
  parentId: string
  permission: string
  isChecked?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  roleId: '',
})

interface Props {
  roleId: string
}

const tableRef = ref<InstanceType<typeof GiTable>>()
// 是否父子联动
const isCascade = ref(true)
const isExpanded = ref(true)
// 是否禁用
const disabled = ref(false)

// 展开/折叠
const onExpanded = () => {
  isExpanded.value = !isExpanded.value
  tableRef.value?.tableRef?.expandAll(isExpanded.value)
}

/**
 * 递归处理菜单数据，并进行类型转换
 *
 * @param menus 菜单数据
 */
const transformMenu = (menus: MenuResp[]): ExtendedMenuResp[] => {
  return menus.map((item): ExtendedMenuResp => {
    const extendedItem: ExtendedMenuResp = { ...item }
    
    // 如果当前项有子项，递归处理子项
    if (item.children && item.children.length > 0) {
      // 过滤出 type 为 3 的按钮权限
      const permissions = item.children.filter((child) => child.type === 3 || child.permission).map((child): PermissionItem => ({
        id: child.id,
        title: child.title,
        parentId: child.parentId,
        permission: child.permission,
      }))

      // 过滤出 type 不为 3 的子项
      extendedItem.children = item.children.filter((child) => child.type !== 3 && !child.permission)

      // 如果有权限，将其添加到当前项的 permissions 属性中
      if (permissions.length > 0) {
        extendedItem.permissions = permissions
        extendedItem.checkedPermissions = permissions.filter((permission) => permission.isChecked).map(p => p.id)
      }

      // 递归处理剩余的子项
      extendedItem.children = transformMenu(extendedItem.children)

      // 如果 children 为空数组，移除 children 属性
      if (extendedItem.children.length === 0) {
        extendedItem.children = undefined
      }
    }

    return extendedItem
  })
}

// 更新表格数据的选中状态
const updateTableDataCheckedStatus = (data: ExtendedMenuResp[], selectedKeys: (string | number)[]) => {
  data.forEach((item) => {
    item.disabled = disabled.value
    // 设置菜单项的选中状态
    item.isChecked = selectedKeys.includes(item.id)
    // 设置权限的选中状态
    if (item.permissions) {
      item.checkedPermissions = item.permissions
        .filter((permission) => selectedKeys.includes(permission.id))
        .map((permission) => permission.id)
    }
    // 递归处理子菜单
    if (item.children) {
      updateTableDataCheckedStatus(item.children as ExtendedMenuResp[], selectedKeys)
    }
  })
}

const selectedKeys = ref<Set<string | number>>(new Set())

const {
  tableData,
  loading,
  search,
} = useTable(() => getMenuTreeForRole(), {
  immediate: true,
  formatResult(data: any[]) {
    return transformMenu(data as MenuResp[])
  },
  onSuccess: () => {
    nextTick(() => {
      tableRef.value?.tableRef?.expandAll(true)
    })
    // 初始加载时应用已选中的权限
    if (selectedKeys.value.size > 0) {
      updateTableDataCheckedStatus(tableData.value, Array.from(selectedKeys.value))
    }
    
    // 如果有角色ID，加载该角色已分配的菜单
    if (props.roleId) {
      loadRoleMenus(props.roleId);
    }
  },
})

// 加载角色已分配的菜单
const loadRoleMenus = async (roleId: string) => {
  try {
    const { data } = await getRoleMenuIds(roleId);
    if (data && data.length > 0) {
      // 更新选中的菜单
      selectedKeys.value = new Set(data.map(id => id));
      // 更新表格数据选中状态
      updateTableDataCheckedStatus(tableData.value, data);
    }
  } catch (error) {
    console.error('获取角色菜单失败', error);
  }
}

const columns: TableInstance['columns'] = [
  { title: '菜单', dataIndex: 'title', slotName: 'title', width: 170, fixed: !isMobile() ? 'left' : undefined },
  { title: '权限', dataIndex: 'permissions', slotName: 'permissions' },
]

// 级联选中子项
const cascadeSelectChild = (record: ExtendedMenuResp, isCascade: boolean) => {
  if (isCascade && record.children && record.children.length > 0) {
    ;(record.children as ExtendedMenuResp[]).forEach((child) => {
      child.isChecked = record.isChecked
      tableRef.value?.tableRef?.select(child.id, child.isChecked)
      child.isChecked
        ? selectedKeys.value.add(child.id)
        : selectedKeys.value.delete(child.id)
      if ((child.children && child.children.length > 0) || (child.permissions && child.permissions.length > 0)) {
        cascadeSelectChild(child, isCascade)
      }
    })
  }
  // 递归选中权限
  if (isCascade && record.permissions && record.permissions.length > 0) {
    record.permissions.forEach((permission) => {
      permission.isChecked = record.isChecked
      permission.isChecked
        ? selectedKeys.value.add(permission.id)
        : selectedKeys.value.delete(permission.id)
    })
    record.checkedPermissions = record.permissions.filter((permission) => permission.isChecked).map((permission) => permission.id)
  }
}

// 查找指定菜单
const findItem = (id: string, data: ExtendedMenuResp[]): ExtendedMenuResp | null => {
  for (const item of data) {
    if (item.id === id) return item
    if (item.children?.length) {
      const found = findItem(id, item.children as ExtendedMenuResp[])
      if (found) return found
    }
  }
  return null
}

// 级联选中父项目
const cascadeSelectParent = (record: ExtendedMenuResp, isCascade: boolean) => {
  if (isCascade && record.parentId && record.parentId !== '0') {
    const parent = findItem(record.parentId, tableData.value)
    if (parent) {
      // 如果父项目的某个子项被选中了，它就依然保持选中状态
      parent.isChecked = (parent.children as ExtendedMenuResp[])?.some((child) => child.isChecked) || false
      tableRef.value?.tableRef?.select(parent.id, parent.isChecked)
      if (!parent.isChecked && !record.isChecked) {
        selectedKeys.value.delete(parent.id)
      } else {
        selectedKeys.value.add(parent.id)
      }
      if (parent.parentId && parent.parentId !== '0') {
        cascadeSelectParent(parent, isCascade)
      }
    }
  }
}

// 选中
const select: TableInstance['onSelect'] = (rowKeys, checked, record) => {
  const isChecked = rowKeys.includes(checked)
  isChecked
    ? selectedKeys.value.add(record.id)
    : selectedKeys.value.delete(record.id)
  ;(record as ExtendedMenuResp).isChecked = isChecked
  // 级联选中子项
  cascadeSelectChild(record as ExtendedMenuResp, isCascade.value)
  // 级联选中父项
  cascadeSelectParent(record as ExtendedMenuResp, isCascade.value)
}

// 全选
const selectAll: TableInstance['onSelectAll'] = (checked) => {
  tableData.value.forEach((item) => {
    item.isChecked = checked
    checked
        ? selectedKeys.value.add(item.id)
        : selectedKeys.value.delete(item.id)
    cascadeSelectChild(item, true)
  })
}

// 选中权限
const selectPermission = (record: ExtendedMenuResp) => {
  const checkPermissions = record.checkedPermissions || []
  // 取消选中
  if (checkPermissions.length === 0) {
    if (isCascade.value) {
      record.isChecked = false
      selectedKeys.value.delete(record.id)
      tableRef.value?.tableRef?.select(record.id, record.isChecked)
      cascadeSelectParent(record, isCascade.value)
    }
    record.permissions?.forEach((permission) => {
      permission.isChecked = false
      selectedKeys.value.delete(permission.id)
    })
    return
  }
  // 选中
  if (checkPermissions.length > 0) {
    if (isCascade.value) {
      record.isChecked = true
      selectedKeys.value.add(record.id)
      tableRef.value?.tableRef?.select(record.id, record.isChecked)
      cascadeSelectParent(record, isCascade.value)
    }
    record.permissions?.forEach((permission) => {
      permission.isChecked = checkPermissions.includes(permission.id)
      permission.isChecked
        ? selectedKeys.value.add(permission.id)
        : selectedKeys.value.delete(permission.id)
    })
  }
}

// 保存
const save = async () => {
  try {
    disabled.value = true;
    await assignRoleMenus(
      props.roleId,
      Array.from(selectedKeys.value).map(id => String(id))
    );
    Message.success('保存成功');
  } catch (error) {
    console.error('保存权限失败', error);
    Message.error('保存失败');
  } finally {
    disabled.value = false;
  }
}

const showCheckedAll = ref(true)
// 加载角色详情
const fetchRole = async (id: string) => {
  try {
    loading.value = true
    disabled.value = !has.hasPermOr(['system:role:updatePermission'])
    // 查询角色详情 - 使用新接口
    const { data } = await getRoleDetail(id)
    if (!disabled.value) {
      disabled.value = data.isSystem
    }
    isCascade.value = true // 新接口暂时设为默认值
    // 更新选中键集合 - 需要根据实际情况调整
    selectedKeys.value = new Set([]) // 暂时为空，等后端提供菜单权限查询接口
    // 更新表格数据的选中状态
    updateTableDataCheckedStatus(tableData.value, [])
    // 手动设置表格行的选中状态，确保组件响应
    await nextTick(() => {
      tableRef.value?.tableRef?.selectAll(false)
      showCheckedAll.value = !disabled.value
    })
  } finally {
    loading.value = false
  }
}

// 刷新
const refresh = () => {
  search()
  fetchRole(props.roleId)
}

// 监听 roleId 的变化
watch(
  () => props.roleId,
  async (newRoleId) => {
    if (newRoleId) {
      await fetchRole(newRoleId)
    }
  },
  { immediate: true },
)
</script>

<style scoped lang="scss"></style>
