import type { RouteRecordRaw } from 'vue-router'
import type { MenuTreeNode } from '@/types/api/role'

/**
 * 动态路由注册：根据登录接口返回的 sysMenus 树生成路由记录，
 * 并挂到 / (Home) 之下。
 *
 * - 叶子节点（path 以 / 开头）查表得到 component，register 到 / 下
 * - /system/downloadClient 是特例：保留原 beforeEnter 下载逻辑
 * - 找不到 component 的路径直接跳过（防御后端乱返）
 */

type RouteComponent = RouteRecordRaw['component']
type LazyComponent = () => Promise<{ default: RouteComponent } | RouteComponent>

// path -> lazy import。Dashboard 保留为同步导入以便静态路由共用
import Dashboard from '@/views/Dashboard.vue'

export const dynamicComponentMap: Record<string, LazyComponent> = {
  '/order/list': () => import('@/views/order/index.vue'),
  '/pod-order/list': () => import('@/views/order/pod/index.vue'),
  '/pod-cn-order/list': () => import('@/views/order/podCN/index.vue'),
  '/pod-us-order/list': () => import('@/views/order/podUs/index.vue'),
  '/pod-us-order/orderTracking': () =>
    import('@/views/order/orderTracking/index.vue'),
  '/pod-us-order/podUsSchedulingRules': () =>
    import('@/views/order/podUsSchedulingRules/index.vue'),
  '/order/factory-order-new': () =>
    import('@/views/order/factoryOrderNew/index.vue'),
  '/order/cancel-order-process': () =>
    import('@/views/order/cancelOrderProcess/index.vue'),
  '/order/allocation-sorting-rule': () =>
    import('@/views/order/allocationSortingRule/index.vue'),
  '/pod-cn-order/orderTracking': () =>
    import('@/views/order/orderTracking/indexcn.vue'),
  '/pod-delivery-note/list': () =>
    import('@/views/order/pod/deliveryOrderList.vue'),
  '/production/complete': () => import('@/views/production/complete.vue'),
  '/system/user': () => import('@/views/system/UserPage.vue'),
  '/system/role-manage': () => import('@/views/system/RoleManagementPage.vue'),
  '/system/external-authorisation': () =>
    import('@/views/system/externalAuthorisationPage.vue'),
  '/system/customers': () => import('@/views/system/CustomersPage.vue'),
  '/supply/out-of-stock-statistics': () =>
    import('@/views/supply/OutOfStockStatistics.vue'),
  '/supply/stocking-order': () =>
    import('@/views/supply/stockingOrder/index.vue'),
  '/system/delivery-note': () => import('@/views/DeliveryNotePage.vue'),
  '/account/statement-note': () => import('@/views/AccountStatementNote.vue'),
  '/account/pod-bill-order': () => import('@/views/podBillOrder/index.vue'),
  '/account/pod-us-bill-order': () =>
    import('@/views/podUsBillOrder/index.vue'),
  '/typesetting-management/list': () =>
    import('@/views/typesetting/TypesettingManagement.vue'),
  '/logistics/logisticsMethod': () =>
    import('@/views/logistics/logisticsMethod.vue'),
  '/logistics/logisticsCompany': () =>
    import('@/views/logistics/logisticsCompany.vue'),
  '/logistics/shippingAddress': () =>
    import('@/views/logistics/shippingAddress.vue'),
  '/logistics/logisticsQuotation': () =>
    import('@/views/logistics/logisticsQuotation.vue'),
  '/logistics/declarationRule': () =>
    import('@/views/logistics/declarationRule.vue'),
  '/logistics/logisticsPartition': () =>
    import('@/views/logistics/logisticsPartition.vue'),
  '/logistics/logisticsCalculate': () =>
    import('@/views/logistics/logisticsCalculate.vue'),
  '/logistics/sortingConfiguration': () =>
    import('@/views/logistics/sortingConfiguration.vue'),
  '/logistics/logisticsTracking': () =>
    import('@/views/logistics/logisticsTracking.vue'),
  '/warehouse/manage': () => import('@/views/warehouse/manage.vue'),
  '/warehouse/receipt-doc': () => import('@/views/warehouse/receiptDoc.vue'),
  '/warehouse/issue-doc': () => import('@/views/warehouse/issueDoc.vue'),
  '/warehouse/stocking-plan': () =>
    import('@/views/warehouse/stockingPlan.vue'),
  '/warehouse/stocking-application': () =>
    import('@/views/warehouse/stockingApplicationOrder/index.vue'),
  '/warehouse/warning': () => import('@/views/warehouse/warning.vue'),
  '/warehouse/position': () => import('@/views/warehouse/position.vue'),
  '/setting/settingIndex': () => import('@/views/setting/settingIndex.vue'),
  '/MyDownloads': () => import('@/views/MyDownloads.vue'),
  '/supply/supplierManagement': () =>
    import('@/views/supply/supplierManagement/index.vue'),
}

/** dashboard 是登录后的默认页，保留为静态路由 */
export { Dashboard }

/**
 * 把后端返回的叶子节点规范化为 router 用的完整路径。
 * 优先级：route > path > 顶层名+叶子名/name
 * - route 已带 / → 原样返回
 * - path 含 _ → 把 _ 替换成 /，并补 / 前缀
 * - 都没有 → 用顶层 name + 叶子名兜底
 */
export function buildLeafPath(
  leaf: MenuTreeNode,
  topName: string = '',
): string {
  const r = leaf.route
  if (r?.startsWith('/')) return r
  if (r) return '/' + r.replace(/_/g, '/')
  const p = leaf.path
  if (p?.startsWith('/')) return p
  if (p?.includes('_')) {
    return '/' + p.replace(/_/g, '/')
  }
  const leafPart = p || leaf.name
  if (!leafPart) return ''
  if (topName) {
    return `/${topName}/${leafPart}`
  }
  return `/${leafPart}`
}

/** 把所有叶子 path 从 sysMenus 树里展平为路由可用的完整路径 */
export function flattenLeafPaths(nodes: MenuTreeNode[] = []): string[] {
  return flattenLeafNodes(nodes).map((n) => n.path)
}

/**
 * 展平 sysMenus 的所有叶子节点，输出 { path, title }，
 * 供 buildDynamicRoutes 注册路由时写入 meta.title。
 */
export function flattenLeafNodes(
  nodes: MenuTreeNode[] = [],
): Array<{ path: string; title: string }> {
  const out: Array<{ path: string; title: string }> = []
  for (const top of nodes) {
    const topName = top.name
    const walk = (arr: MenuTreeNode[]) => {
      for (const n of arr) {
        if (n.children?.length) {
          walk(n.children)
        } else {
          const p = buildLeafPath(n, topName)
          if (p) out.push({ path: p, title: n.name || n.title })
        }
      }
    }
    if (top.children?.length) {
      walk(top.children)
    } else {
      const p = buildLeafPath(top, topName)
      if (p) out.push({ path: p, title: top.name || top.title })
    }
  }
  return out
}

/**
 * 把 sysMenus 转换成可注册到 router 的 RouteRecordRaw 列表。
 */
export function buildDynamicRoutes(
  menus: MenuTreeNode[] = [],
): RouteRecordRaw[] {
  const leaves = flattenLeafNodes(menus)
  const records: RouteRecordRaw[] = []
  for (const { path: p, title } of leaves) {
    if (p === '/system/downloadClient') {
      // 特殊路由：触发 exe 下载，无组件
      records.push({
        path: p,
        component: { render: () => null } as unknown as RouteComponent,
        beforeEnter() {
          const a = document.createElement('a')
          a.href = '/exeFiles/JomallProductionAssistantSetup.exe'
          a.download = '生产客户端.exe'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          // 取消导航，停留在当前页面，只触发下载不出现空白页
          return false
        },
        meta: { title: '下载生产客户端' },
      } as RouteRecordRaw)
      continue
    }
    const loader = dynamicComponentMap[p]
    if (!loader) continue
    records.push({
      path: p,
      name: p,
      // 使用异步加载的 component
      component: loader as unknown as RouteComponent,
      meta: { title },
    } as RouteRecordRaw)
  }
  return records
}
