<script>
import { isLoggedIn } from './utils/session.js'

/** 无需登录即可访问（公开报告链接、登录页） */
const isPublicRoute = (route) => {
  if (!route) return false
  if (route.includes('pages/login/Login')) return true
  if (route.includes('pages/report-view/reportView')) return true
  return false
}

function buildLoginRedirectPath() {
  try {
    const pages = getCurrentPages()
    const cur = pages[pages.length - 1]
    if (!cur) return ''
    let path = cur.route || ''
    if (!path.startsWith('/')) path = '/' + path
    const opts = cur.options || {}
    const keys = Object.keys(opts)
    if (keys.length === 0) return path
    const qs = keys.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(opts[k])}`).join('&')
    return `${path}?${qs}`
  } catch (_) {
    return ''
  }
}

function scheduleAuthGuard() {
  setTimeout(() => {
    try {
      if (isLoggedIn()) return
      const pages = getCurrentPages()
      if (pages.length === 0) return // 还没加载完页面，默认第一个页面是 login，不需要拦截
      const cur = pages[pages.length - 1]
      const route = cur && cur.route ? cur.route : ''
      if (isPublicRoute(route)) return
      const redirect = buildLoginRedirectPath()
      const safe =
        redirect &&
        redirect.startsWith('/pages/') &&
        !redirect.includes('..') &&
        !redirect.includes('//')
      const loginUrl = safe
        ? `/pages/login/Login?redirect=${encodeURIComponent(redirect)}`
        : '/pages/login/Login'
      uni.reLaunch({ url: loginUrl })
    } catch (_) {
      uni.reLaunch({ url: '/pages/login/Login' })
    }
  }, 50)
}

export default {
  onLaunch() {
    scheduleAuthGuard()
  },
  onShow() {
    scheduleAuthGuard()
  }
}
</script>

<style>
@import './assets/global.css';
page {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background: #fafaf8;
  font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #1a1a1a;
}
</style>
