<script setup lang="ts">
import { onHide, onLaunch, onShow } from '@dcloudio/uni-app'
import { navigateToInterceptor } from '@/router/interceptor'
import { useAuthStore } from '@/store/auth'
import { useTokenStore } from '@/store/token'
import { getCode } from '@/utils/dd'

onLaunch((options) => {
  // 初始化 store
  const tokenStore = useTokenStore()
  const authStore = useAuthStore()
  
  // 钉钉免登录逻辑
  async function handleDingTalkAutoLogin() {
    try {
      console.log('尝试钉钉免登录...')
      const code = await getCode()
      console.log('获取到钉钉授权码:', { code })
      if (code) {
        const tokenInfo = await authStore.authDingTalkLogin(code)
        tokenStore.setTokenInfo(tokenInfo)
      }
      console.log('钉钉免登录成功')
    }
    catch (error) {
      console.error('钉钉免登录失败，将跳转到登录页面:', error)
      uni.navigateTo({ url: '/pages-fg/login/login' })
    }
  }

  // 执行钉钉免登录
  handleDingTalkAutoLogin()
})
onShow((options) => {
  // 处理直接进入页面路由的情况：如h5直接输入路由、微信小程序分享后进入等
  // https://github.com/unibest-tech/unibest/issues/192
  if (options?.path) {
    navigateToInterceptor.invoke({ url: `/${options.path}`, query: options.query })
  }
  else {
    navigateToInterceptor.invoke({ url: '/' })
  }
})
onHide(() => {})
</script>

<style lang="scss">

</style>
