import type { MenuItem, LoginResponse, UserInfoResponse, RoutesResponse } from '@/types/menu'

// ────────── 模拟用户数据库 ──────────
const mockUsers = {
  admin: { token: 'mock-token-admin', roles: ['admin'], name: '超级管理员', avatar: '' },
  editor: { token: 'mock-token-editor', roles: ['editor'], name: '内容编辑', avatar: '' },
}

// Token 反查用户
const tokenMap: Record<string, typeof mockUsers.admin> = {
  'mock-token-admin': mockUsers.admin,
  'mock-token-editor': mockUsers.editor,
}

// ────────── 模拟后端存储的全量路由 ──────────
// 真实场景中这份数据存在数据库，后端根据角色过滤后返回
const allAsyncRoutes: MenuItem[] = [
  {
    id: 1,
    parentId: 0,
    type: 1,
    sort: 0,
    path: '/dashboard',
    name: 'Dashboard',
    component: 'dashboard/index',
    meta: { title: '首页', icon: 'HomeFilled', roles: ['admin', 'editor'] },
  },
  {
    id: 200,
    parentId: 0,
    type: 1,
    sort: 5,
    path: '/sdk',
    name: 'Sdk',
    component: 'sdk/index',
    meta: { title: 'SDK管理', icon: 'Box', roles: ['admin'] },
    children: [
      {
        id: 201,
        parentId: 200,
        type: 1,
        sort: 1,
        path: 'detail',
        name: 'SdkDetail',
        component: 'sdk/detail',
        meta: { title: '管理详情', icon: 'Box', roles: ['admin'], hidden: true },
      },
    ],
  },
  {
    id: 100,
    parentId: 0,
    type: 0,
    sort: 10,
    path: '/system',
    name: 'System',
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
    children: [
      {
        id: 101,
        parentId: 100,
        type: 1,
        sort: 1,
        path: 'user',
        name: 'SystemUser',
        component: 'system/user/index',
        meta: { title: '用户管理', icon: 'User', roles: ['admin'] },
        children: [
          {
            id: 1011,
            parentId: 101,
            type: 2,
            sort: 1,
            path: '',
            permission: 'sys:user:add',
            meta: { title: '新增用户' },
          },
          {
            id: 1012,
            parentId: 101,
            type: 2,
            sort: 2,
            path: '',
            permission: 'sys:user:edit',
            meta: { title: '编辑用户' },
          },
          {
            id: 1013,
            parentId: 101,
            type: 2,
            sort: 3,
            path: '',
            permission: 'sys:user:delete',
            meta: { title: '删除用户' },
          },
        ],
      },
      {
        id: 102,
        parentId: 100,
        type: 1,
        sort: 2,
        path: 'role',
        name: 'SystemRole',
        component: 'system/role/index',
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin'] },
        children: [
          {
            id: 1021,
            parentId: 102,
            type: 2,
            sort: 1,
            path: '',
            permission: 'sys:role:add',
            meta: { title: '新增角色' },
          },
          {
            id: 1022,
            parentId: 102,
            type: 2,
            sort: 2,
            path: '',
            permission: 'sys:role:edit',
            meta: { title: '编辑角色' },
          },
          {
            id: 1023,
            parentId: 102,
            type: 2,
            sort: 3,
            path: '',
            permission: 'sys:role:delete',
            meta: { title: '删除角色' },
          },
          {
            id: 1024,
            parentId: 102,
            type: 2,
            sort: 4,
            path: '',
            permission: 'sys:role:assign',
            meta: { title: '分配权限' },
          },
        ],
      },
      {
        id: 103,
        parentId: 100,
        type: 1,
        sort: 3,
        path: 'menu',
        name: 'SystemMenu',
        component: 'system/menu/index',
        meta: { title: '菜单管理', icon: 'Menu', roles: ['admin'] },
        children: [
          {
            id: 1031,
            parentId: 103,
            type: 2,
            sort: 1,
            path: '',
            permission: 'sys:menu:add',
            meta: { title: '新增菜单' },
          },
          {
            id: 1032,
            parentId: 103,
            type: 2,
            sort: 2,
            path: '',
            permission: 'sys:menu:edit',
            meta: { title: '编辑菜单' },
          },
          {
            id: 1033,
            parentId: 103,
            type: 2,
            sort: 3,
            path: '',
            permission: 'sys:menu:delete',
            meta: { title: '删除菜单' },
          },
        ],
      },
    ],
  },
  {
    id: 300,
    parentId: 0,
    type: 0,
    sort: 20,
    path: '/content',
    name: 'Content',
    redirect: '/content/article',
    meta: { title: '内容管理', icon: 'Document', roles: ['admin', 'editor'] },
    children: [
      {
        id: 301,
        parentId: 300,
        type: 1,
        sort: 1,
        path: 'article',
        name: 'Article',
        component: 'content/article/index',
        meta: { title: '文章管理', icon: 'Document', roles: ['admin', 'editor'] },
      },
    ],
  },
]

// ────────── 工具函数 ──────────
function filterRoutesByRoles(routes: MenuItem[], roles: string[]): MenuItem[] {
  return routes.reduce<MenuItem[]>((acc, route) => {
    // type=2（按钮）没有 meta.roles，继承父节点权限，直接保留
    const allowed = route.meta?.roles
    const hasPermission = route.type === 2 || !allowed || roles.some((r) => allowed.includes(r))
    if (hasPermission) {
      const item = { ...route }
      if (item.children?.length) {
        item.children = filterRoutesByRoles(item.children, roles)
      }
      acc.push(item)
    }
    return acc
  }, [])
}

const delay = (ms: number) => new Promise((r) => setTimeout(r, ms))

// ────────── Mock 接口 ──────────
/** 模拟登录 */
export async function mockLogin(username: string, password: string): Promise<LoginResponse> {
  await delay(500)
  const user = mockUsers[username as keyof typeof mockUsers]
  if (user && password === '123456') {
    return { code: 200, data: { token: user.token } }
  }
  throw new Error('用户名或密码错误')
}

/** 模拟获取用户信息 */
export async function mockGetUserInfo(token: string): Promise<UserInfoResponse> {
  await delay(200)
  const user = tokenMap[token]
  if (!user) throw new Error('Token 无效或已过期')
  return { code: 200, data: { name: user.name, roles: user.roles, avatar: user.avatar } }
}

/** 模拟获取权限路由（后端根据角色过滤后返回） */
export async function mockGetRoutes(token: string): Promise<RoutesResponse> {
  await delay(300)
  const user = tokenMap[token]
  if (!user) throw new Error('Token 无效或已过期')
  // 深拷贝，避免修改原始数据
  const routes = filterRoutesByRoles(JSON.parse(JSON.stringify(allAsyncRoutes)), user.roles)
  return { code: 200, data: routes }
}
