import { createRouter, createWebHistory } from "vue-router"
import ScreenLayout from "../layout/ScreenLayout.vue"
import { getToken } from "../utils/auth"

/**
 * 大屏路由表（路径与后端 /bigScreen/* 业务对应，便于联调）
 * meta.titleZh / titleBo：浏览器标题与页面双语标题参考
 */
const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/login/index.vue"),
    meta: {
      titleZh: "登录",
      titleBo: "ཐོ་ཞུགས།",
      public: true
    }
  },
  {
    path: "/",
    component: ScreenLayout,
    redirect: "/home",
    meta: { requiresAuth: true },
    children: [
      {
        path: "home",
        name: "ScreenHome",
        component: () => import("../views/home/index.vue"),
        meta: {
          titleZh: "数字畜牧一张图",
          titleBo: "གཙོ་ངོས།"
        }
      },
      {
        path: "livestock-resources",
        name: "LivestockResources",
        component: () => import("../views/livestockResources/index.vue"),
        meta: {
          titleZh: "畜牧资源",
          titleBo: "སྐྱེས་ཁམས་ཐོན་ཁུངས།"
        }
      },
      {
        path: "trade-sales",
        name: "TradeSales",
        component: () => import("../views/tradeSales/index.vue"),
        meta: {
          titleZh: "交易销售",
          titleBo: "འབྲེལ་གཏོང་ཚོང་འབུལ།"
        }
      },
      {
        path: "common-prosperity",
        name: "CommonProsperity",
        component: () => import("../views/commonProsperity/index.vue"),
        meta: {
          titleZh: "共同富裕统计",
          titleBo: "སྤྱི་འགྲོས་ཕྱུག་པོའི་བསྡུས་རྩིས།"
        }
      },
      {
        path: "epidemic-risk",
        name: "EpidemicRisk",
        component: () => import("../views/epidemicRisk/index.vue"),
        meta: {
          titleZh: "疫病风险统计",
          titleBo: "ནད་རིམས་ཉེན་ཁའི་བསྡུས་རྩིས།"
        }
      },
      {
        path: ":pathMatch(.*)*",
        name: "NotFound",
        component: () => import("../views/error/404.vue"),
        meta: {
          titleZh: "页面不存在",
          titleBo: "ཤོག་ངོས་མི་འདུག"
        }
      }
    ]
  }
]

const router = createRouter({
  // 与 ruoyi-ui router.base 一致；生产 import.meta.env.BASE_URL 为 /screen/
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

/** 未登录跳转登录页；已登录访问 /login 则进首页 */
router.beforeEach((to, _from, next) => {
  const token = getToken()
  if (to.path === "/login") {
    next(token ? { path: "/home" } : undefined)
    return
  }
  const needAuth = to.matched.some((r) => r.meta.requiresAuth)
  if (needAuth && !token) {
    next({ path: "/login", query: { redirect: to.fullPath } })
    return
  }
  next()
})

/** 根据路由 meta 更新浏览器标签标题 */
router.afterEach((to) => {
  const zh = to.meta?.titleZh
  const appTitle = import.meta.env.VITE_APP_TITLE || "ruoyi-screen"
  document.title = zh ? `${zh} - ${appTitle}` : appTitle
})

export default router
