<script setup lang="ts">
import { onHide, onLaunch, onShow } from '@dcloudio/uni-app'
import { BarChart, LineChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'

import { navigateToInterceptor } from '@/router/interceptor'
import { useUserStore } from '@/store/user'
import { tabbarStore } from './tabbar/store'
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'

// 注册 ECharts 组件
echarts.use([
  LineChart,
  BarChart,
  GridComponent,
  LegendComponent,
  TooltipComponent,
  CanvasRenderer,
])

const userStore = useUserStore()

// 不需要登录验证的页面路径
const publicPages = [
  '/pages/auth/splash',
  '/pages/auth/index',
]

// 检查是否为公开页面
function isPublicPage(path: string) {
  return publicPages.some(page => path.includes(page.replace('/pages/', '')))
}

// 处理登录状态检查和页面跳转
function handlePageNavigation(targetPath?: string) {
  const isLoggedIn = userStore.isLogin && userStore.accessToken

  // 如果未登录且不是公开页面，跳转到加载页
  if (!isLoggedIn && targetPath && !isPublicPage(targetPath)) {
    console.log('用户未登录，跳转到加载页')
    uni.reLaunch({
      url: '/pages/auth/index',
    })
    return
  }

  // 如果已登录且访问的是登录相关页面，跳转到首页
  if (isLoggedIn && targetPath && isPublicPage(targetPath)) {
    console.log('用户已登录，跳转到首页')
    uni.reLaunch({
      url: '/pages/index/index',
    })
    return
  }

  // 正常处理页面跳转
  if (targetPath) {
    navigateToInterceptor.invoke({ url: targetPath })
  }
  else {
    // 根据登录状态决定默认跳转页面
    const defaultUrl = isLoggedIn ? '/pages/index/index' : '/pages/auth/splash'
    navigateToInterceptor.invoke({ url: defaultUrl })
  }
}

onLaunch((options) => {
  // 处理直接进入页面路由的情况：如h5直接输入路由、微信小程序分享后进入等
  // https://github.com/unibest-tech/unibest/issues/192
  console.log('App Launch', options)

  const targetPath = options?.path ? `/${options.path}` : undefined

  // 延迟执行以确保 store 已初始化
  setTimeout(() => {
    handlePageNavigation(targetPath)
    // 处理直接进入路由非首页时，tabbarIndex 不正确的问题
    tabbarStore.setAutoCurIdx(options.path)
  }, 100)
})

onShow((options) => {
  console.log('App Show', options)

  // 每次显示应用时检查登录状态
  const isLoggedIn = userStore.isLogin && userStore.accessToken
  if (!isLoggedIn) {
    // 检查当前页面是否为公开页面
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const currentRoute = currentPage?.route || ''

    if (!isPublicPage(`/${currentRoute}`)) {
      console.log('应用显示时检测到未登录，跳转到登录页')
      uni.reLaunch({
        url: '/pages/auth/index',
      })
    }
  }
})

onHide(() => {
  console.log('App Hide')
})
</script>

<style lang="scss">
swiper,
scroll-view {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

image {
  width: 100%;
  height: 100%;
  vertical-align: middle;
}
</style>
