import { createRouter, createWebHistory } from "vue-router"
import ScreenLayout from "../layout/ScreenLayout.vue"
import { getToken } from "../utils/auth"
import {
  ensureScreenAutoLogin,
  getUrlScreenLoginCipher,
  SCREEN_LOGIN_CIPHER_ERROR,
  SCREEN_LOGIN_UUID_ERROR,
  stripScreenLoginTokenQuery,
  stripScreenLoginUuidQuery,
  tryScreenLoginWithCipher
} from "../utils/screenAutoLogin"

/**
 * 大屏路由表（路径与后端 /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
})

/** URL ?token= 密文登录；失败则提示公钥不对并跳转登录页 */
async function tryLoginWithUrlToken(to, next) {
  const cipher = getUrlScreenLoginCipher(to.query)
  if (!cipher) {
    return false
  }
  try {
    await tryScreenLoginWithCipher(cipher)
    const query = stripScreenLoginTokenQuery(to.query)
    if (to.path === "/login") {
      const redirect =
        typeof to.query.redirect === "string" ? to.query.redirect : "/home"
      next({ path: redirect, replace: true })
      return true
    }
    next({ path: to.path, query, replace: true })
    return true
  } catch {
    next({
      path: "/login",
      query: { screenLoginError: SCREEN_LOGIN_CIPHER_ERROR },
      replace: true
    })
    return true
  }
}

/** URL ?uuid= 免密登录；失败则提示并跳转登录页 */
async function tryLoginWithUrlUuid(to, next) {
  const { attempted, ok } = await ensureScreenAutoLogin(to.query)
  if (!attempted) {
    return false
  }
  if (ok) {
    const query = stripScreenLoginUuidQuery(to.query)
    if (to.path === "/login") {
      const redirect =
        typeof to.query.redirect === "string" ? to.query.redirect : "/home"
      next({ path: redirect, replace: true })
      return true
    }
    next({ path: to.path, query, replace: true })
    return true
  }
  next({
    path: "/login",
    query: { screenLoginError: SCREEN_LOGIN_UUID_ERROR },
    replace: true
  })
  return true
}

/** 未登录跳转登录页；URL ?token= / ?uuid= 优先 */
router.beforeEach(async (to, _from, next) => {
  const token = getToken()
  if (to.path === "/login") {
    if (token) {
      next({ path: "/home" })
      return
    }
    if (await tryLoginWithUrlToken(to, next)) {
      return
    }
    if (await tryLoginWithUrlUuid(to, next)) {
      return
    }
    next()
    return
  }
  const needAuth = to.matched.some((r) => r.meta.requiresAuth)
  if (needAuth && !getToken()) {
    if (await tryLoginWithUrlToken(to, next)) {
      return
    }
    if (await tryLoginWithUrlUuid(to, next)) {
      return
    }
    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
