/**
 * CRMEB Admin 路由配置
 * 基于 CRMEB v5 标准版路由体系 1:1 映射
 * 
 * 路由结构说明:
 * - 一级菜单(topMenu): 主侧边栏显示的顶级模块
 * - 分组(group): 二级侧边栏的分组标题
 * - 菜单项(item): 具体的页面路由
 */

/**
 * 路由记录类型定义
 */
export type RouteRecord = {
  id: string              // 路由唯一标识,对应 CRMEB 的 name
  title: string           // 显示标题
  icon?: string           // 图标(仅一级菜单)
  path: string            // 路径(用于内部路由切换)
  componentKey: string    // 组件映射key
  parentId?: string       // 父路由ID
  groupId?: string        // 所属分组ID
  auth?: string[]         // 权限标识
  hidden?: boolean        // 是否隐藏
  keepAlive?: boolean     // 是否缓存
  order?: number          // 排序
  isAffix?: boolean       // 是否固定标签
}

/**
 * 菜单分组类型
 */
export type MenuGroup = {
  id: string
  title: string
  order?: number
}

/**
 * 一级菜单类型
 */
export type TopMenu = {
  id: string
  title: string
  icon: string
  path: string            // 默认跳转路径
  order: number
  groups: MenuGroup[]     // 该菜单下的分组列表
}

/**
 * ============================================
 * CRMEB 路由常量配置
 * ============================================
 */

/**
 * 一级菜单配置(主侧边栏)
 */
export const topMenus: TopMenu[] = [
  {
    id: 'home',
    title: '首页',
    icon: 'home',
    path: '/pages/mall/admin/homePage/index',
    order: 1,
    groups: []
  },
  {
    id: 'user',
    title: '用户',
    icon: 'user',
    path: '/pages/mall/admin/user/list',
    order: 2,
    groups: [
      { id: 'user-manage', title: '', order: 1 },
      { id: 'member-manage', title: '会员管理', order: 2 }
    ]
  },
  {
    id: 'product',
    title: '商品',
    icon: 'product',
    path: '/pages/mall/admin/product/list',
    order: 3,
    groups: [
      { id: 'product-manage', title: '商品管理', order: 1 }
    ]
  },
  {
    id: 'order',
    title: '订单',
    icon: 'order',
    path: '/pages/mall/admin/order/list',
    order: 4,
    groups: [
      { id: 'order-manage', title: '', order: 1 }
    ]
  },
  {
    id: 'marketing',
    title: '营销',
    icon: 'marketing',
    path: '/pages/mall/admin/marketing/coupon/list',
    order: 5,
    groups: [
      { id: 'marketing-tool', title: '营销工具', order: 1 },
      { id: 'marketing-activity', title: '营销活动', order: 2 }
    ]
  },
  {
    id: 'cms',
    title: '内容',
    icon: 'content',
    path: '/pages/mall/admin/cms/article/list',
    order: 6,
    groups: [
      { id: 'cms-manage', title: '内容管理', order: 1 }
    ]
  },
  {
    id: 'finance',
    title: '财务',
    icon: 'finance',
    path: '/pages/mall/admin/finance/record',
    order: 7,
    groups: [
      { id: 'finance-manage', title: '财务管理', order: 1 }
    ]
  },
  {
    id: 'statistic',
    title: '数据',
    icon: 'statistic',
    path: '/pages/mall/admin/statistic/index',
    order: 8,
    groups: [
      { id: 'statistic-data', title: '数据统计', order: 1 }
    ]
  },
  {
    id: 'setting',
    title: '设置',
    icon: 'setting',
    path: '/pages/mall/admin/setting/system/config',
    order: 9,
    groups: [
      { id: 'setting-system', title: '系统设置', order: 1 },
      { id: 'setting-application', title: '应用设置', order: 2 },
      { id: 'setting-maintain', title: '维护管理', order: 3 }
    ]
  }
]

/**
 * 完整路由表
 * 映射自 CRMEB router/modules/*
 */
export const routes: RouteRecord[] = [
  // ========== 首页 ==========
  {
    id: 'home_index',
    title: '主页',
    icon: 'home',
    path: '/pages/mall/admin/homePage/index',
    componentKey: 'HomeIndex',
    isAffix: true,
    order: 1
  },

  // ========== 用户模块 ==========
  {
    id: 'user_statistic',
    title: '用户统计',
    path: '/pages/mall/admin/user/Statistic',
    componentKey: 'UserStatistic',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['admin-user-statistic-index'],
    order: 1
  },
  {
    id: 'user_list',
    title: '用户管理',
    path: '/pages/mall/admin/user/list',
    componentKey: 'UserList',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['admin-user-user-index'],
    order: 2
  },
  {
    id: 'user_group',
    title: '用户分组',
    path: '/pages/mall/admin/user/group',
    componentKey: 'UserGroup',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['user-user-group'],
    order: 3
  },
  {
    id: 'user_label',
    title: '用户标签',
    path: '/pages/mall/admin/user/label',
    componentKey: 'UserLabel',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['user-user-label'],
    order: 4
  },
  {
    id: 'user_level',
    title: '用户等级',
    path: '/pages/mall/admin/user/level',
    componentKey: 'UserLevel',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['user-user-level'],
    order: 5
  },
  {
    id: 'user_member_config',
    title: '用户配置',
    path: '/pages/mall/admin/user/MemberConfig',
    componentKey: 'UserMemberConfig',
    parentId: 'user',
    groupId: 'user-manage',
    auth: ['admin-user-member-config'],
    order: 6
  },
  {
    id: 'user_type',
    title: '会员类型',
    path: '/pages/mall/admin/user/grade/type',
    componentKey: 'UserGradeType',
    parentId: 'user',
    groupId: 'member-manage',
    auth: ['admin-user-member-type'],
    order: 1
  },
  {
    id: 'user_card',
    title: '卡密会员',
    path: '/pages/mall/admin/user/grade/card',
    componentKey: 'UserGradeCard',
    parentId: 'user',
    groupId: 'member-manage',
    auth: ['admin-user-grade-card'],
    order: 2
  },
  {
    id: 'user_record',
    title: '会员记录',
    path: '/pages/mall/admin/user/grade/record',
    componentKey: 'UserGradeRecord',
    parentId: 'user',
    groupId: 'member-manage',
    auth: ['admin-user-grade-record'],
    order: 3
  },
  {
    id: 'user_right',
    title: '会员权益',
    path: '/pages/mall/admin/user/grade/right',
    componentKey: 'UserGradeRight',
    parentId: 'user',
    groupId: 'member-manage',
    auth: ['admin-user-grade-right'],
    order: 4
  },

  // ========== 商品模块 ==========
  {
    id: 'product_productList',
    title: '商品管理',
    path: '/pages/mall/admin/product/list',
    componentKey: 'ProductList',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-store-storeProuduct-index'],
    keepAlive: true,
    order: 1
  },
  {
    id: 'product_productClassify',
    title: '商品分类',
    path: '/pages/mall/admin/product/classify',
    componentKey: 'ProductClassify',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-store-storeCategory-index'],
    order: 2
  },
  {
    id: 'product_productEvaluate',
    title: '商品评论',
    path: '/pages/mall/admin/product/reply',
    componentKey: 'ProductReply',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-store-storeProuduct-index'],
    order: 3
  },
  {
    id: 'product_productAttr',
    title: '商品规格',
    path: '/pages/mall/admin/product/attr',
    componentKey: 'ProductAttr',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-store-storeProuduct-index'],
    order: 4
  },
  {
    id: 'product_paramList',
    title: '商品参数',
    path: '/pages/mall/admin/product/param',
    componentKey: 'ProductParam',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-product-param-list'],
    order: 5
  },
  {
    id: 'product_labelList',
    title: '商品标签',
    path: '/pages/mall/admin/product/label',
    componentKey: 'ProductLabel',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-product-label-list'],
    order: 6
  },
  {
    id: 'product_protectionList',
    title: '商品保障',
    path: '/pages/mall/admin/product/protection',
    componentKey: 'ProductProtection',
    parentId: 'product',
    groupId: 'product-manage',
    auth: ['admin-product-protection-list'],
    order: 7
  },

  // ========== 订单模块 ==========
  {
    id: 'order_statistic',
    title: '订单统计',
    path: '/pages/mall/admin/order/statistic',
    componentKey: 'OrderStatistic',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-statistic-index'],
    order: 1
  },
  {
    id: 'order_list',
    title: '订单管理',
    path: '/pages/mall/admin/order/list',
    componentKey: 'OrderList',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-storeOrder-index'],
    keepAlive: true,
    order: 2
  },
  {
    id: 'order_refund',
    title: '售后订单',
    path: '/pages/mall/admin/order/refund',
    componentKey: 'OrderRefund',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-refund-index'],
    order: 3
  },
  {
    id: 'order_cashier',
    title: '收银订单',
    path: '/pages/mall/admin/order/cashier',
    componentKey: 'OrderCashier',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-cashier-index'],
    order: 4
  },
  {
    id: 'order_verify',
    title: '核销记录',
    path: '/pages/mall/admin/order/verify',
    componentKey: 'OrderVerify',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-verify-index'],
    order: 5
  },
  {
    id: 'order_config',
    title: '订单配置',
    path: '/pages/mall/admin/order/config',
    componentKey: 'OrderConfig',
    parentId: 'order',
    groupId: 'order-manage',
    auth: ['admin-order-config-index'],
    order: 6
  },

  // ========== 营销模块 ==========
  {
    id: 'marketing_coupon',
    title: '优惠券',
    path: '/pages/mall/admin/marketing/coupon/list',
    componentKey: 'MarketingCoupon',
    parentId: 'marketing',
    groupId: 'marketing-tool',
    auth: ['admin-marketing-storeCoupon-index'],
    order: 1
  },
  {
    id: 'marketing_integral',
    title: '积分管理',
    path: '/pages/mall/admin/marketing/integral/list',
    componentKey: 'MarketingIntegral',
    parentId: 'marketing',
    groupId: 'marketing-tool',
    auth: ['admin-marketing-storeIntegral-index'],
    order: 2
  },
  {
    id: 'marketing_bargain',
    title: '砍价活动',
    path: '/pages/mall/admin/marketing/bargain/list',
    componentKey: 'MarketingBargain',
    parentId: 'marketing',
    groupId: 'marketing-activity',
    auth: ['admin-marketing-storeBargain-index'],
    order: 3
  },
  {
    id: 'marketing_combination',
    title: '拼团活动',
    path: '/pages/mall/admin/marketing/combination/list',
    componentKey: 'MarketingCombination',
    parentId: 'marketing',
    groupId: 'marketing-activity',
    auth: ['admin-marketing-storeCombination-index'],
    order: 4
  },
  {
    id: 'marketing_seckill',
    title: '秒杀活动',
    path: '/pages/mall/admin/marketing/seckill/list',
    componentKey: 'MarketingSeckill',
    parentId: 'marketing',
    groupId: 'marketing-activity',
    auth: ['admin-marketing-storeSeckill-index'],
    order: 5
  },

  // ========== 内容模块 ==========
  {
    id: 'cms_article',
    title: '文章管理',
    path: '/pages/mall/admin/cms/article/list',
    componentKey: 'CmsArticle',
    parentId: 'cms',
    groupId: 'cms-manage',
    auth: ['admin-cms-article-index'],
    order: 1
  },
  {
    id: 'cms_category',
    title: '文章分类',
    path: '/pages/mall/admin/cms/category/list',
    componentKey: 'CmsCategory',
    parentId: 'cms',
    groupId: 'cms-manage',
    auth: ['admin-cms-category-index'],
    order: 2
  },

  // ========== 财务模块 ==========
  {
    id: 'finance_record',
    title: '财务记录',
    path: '/pages/mall/admin/finance/record',
    componentKey: 'FinanceRecord',
    parentId: 'finance',
    groupId: 'finance-manage',
    auth: ['admin-finance-record-index'],
    order: 1
  },

  // ========== 数据统计模块 ==========
  {
    id: 'statistic_index',
    title: '数据概览',
    path: '/pages/mall/admin/statistic/index',
    componentKey: 'StatisticIndex',
    parentId: 'statistic',
    groupId: 'statistic-data',
    auth: ['admin-statistic-index'],
    order: 1
  },

  // ========== 设置模块 ==========
  {
    id: 'setting_systemConfig',
    title: '系统配置',
    path: '/pages/mall/admin/setting/system/config',
    componentKey: 'SettingSystemConfig',
    parentId: 'setting',
    groupId: 'setting-system',
    auth: ['admin-setting-system-config'],
    order: 1
  },
  {
    id: 'setting_systemAdmin',
    title: '管理员管理',
    path: '/pages/mall/admin/setting/system/admin',
    componentKey: 'SettingSystemAdmin',
    parentId: 'setting',
    groupId: 'setting-system',
    auth: ['admin-setting-system-admin'],
    order: 2
  },
  {
    id: 'setting_systemRole',
    title: '角色管理',
    path: '/pages/mall/admin/setting/system/role',
    componentKey: 'SettingSystemRole',
    parentId: 'setting',
    groupId: 'setting-system',
    auth: ['admin-setting-system-role'],
    order: 3
  }
]

/**
 * ============================================
 * 工具函数
 * ============================================
 */

/**
 * 获取所有一级菜单
 */
export function getTopMenus(): TopMenu[] {
  return topMenus.sort((a, b) => a.order - b.order)
}

/**
 * 根据一级菜单ID获取其分组列表
 */
export function getGroupsByTopMenu(topMenuId: string): MenuGroup[] {
  const menu = topMenus.find(m => m.id === topMenuId)
  return menu ? menu.groups.sort((a, b) => (a.order || 0) - (b.order || 0)) : []
}

/**
 * 根据分组ID获取该分组下的路由列表
 */
export function getRoutesByGroup(groupId: string): RouteRecord[] {
  return routes
    .filter(r => r.groupId === groupId && !r.hidden)
    .sort((a, b) => (a.order || 0) - (b.order || 0))
}

/**
 * 根据一级菜单ID获取其所有子路由(分组后)
 */
export function getRoutesByTopMenu(topMenuId: string): Map<string, RouteRecord[]> {
  const groups = getGroupsByTopMenu(topMenuId)
  const result = new Map<string, RouteRecord[]>()
  
  groups.forEach(group => {
    result.set(group.id, getRoutesByGroup(group.id))
  })
  
  return result
}

/**
 * 根据路由ID查找路由记录
 */
export function findRouteById(routeId: string): RouteRecord | null {
  return routes.find(r => r.id === routeId) || null
}

/**
 * 根据路径查找路由记录
 */
export function findRouteByPath(path: string): RouteRecord | null {
  // 标准化路径: 去除查询参数和前导斜杠
  const normalizePath = (p: string): string => {
    let result = p.startsWith('/') ? p.slice(1) : p
    const queryIndex = result.indexOf('?')
    return queryIndex >= 0 ? result.slice(0, queryIndex) : result
  }
  
  const normalizedPath = normalizePath(path)
  return routes.find(r => normalizePath(r.path) === normalizedPath) || null
}

/**
 * 构建默认打开的标签页列表
 */
export function buildDefaultTabs(): RouteRecord[] {
  return routes.filter(r => r.isAffix)
}

/**
 * 获取路由的面包屑路径
 */
export function getBreadcrumb(routeId: string): Array<{id: string, title: string}> {
  const route = findRouteById(routeId)
  if (!route) return []
  
  const breadcrumb: Array<{id: string, title: string}> = []
  
  // 添加一级菜单
  if (route.parentId) {
    const topMenu = topMenus.find(m => m.id === route.parentId)
    if (topMenu) {
      breadcrumb.push({ id: topMenu.id, title: topMenu.title })
    }
  }
  
  // 添加当前路由
  breadcrumb.push({ id: route.id, title: route.title })
  
  return breadcrumb
}
