<script setup lang="ts">
import { onLaunch, onShow } from '@dcloudio/uni-app'
import { watch } from 'vue'
import { useAppMode } from '@/composables/useAppMode'
import { useAuth } from '@/composables/useAuth'
import { useTheme } from '@/composables/useTheme'
import { usePublicSettings } from '@/composables/usePublicSettings'
import { wxLoginApi } from '@/api'

const { hydrateAppMode, setLoginType } = useAppMode()
const { scheduleExpiryCheck, isAuthenticated, sessionExpired, confirmSessionExpired, login, getUser } = useAuth()
const { apply } = useTheme()
const { load } = usePublicSettings()

watch(sessionExpired, (v) => {
  if (!v) return
  uni.showModal({
    title: '登录已过期',
    content: '请重新登录',
    showCancel: false,
    success: () => confirmSessionExpired(),
  })
})

async function silentWxLogin() {
  // #ifdef MP-WEIXIN
  if (isAuthenticated()) return
  try {
    const loginRes = await new Promise<UniApp.LoginRes>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: resolve,
        fail: reject,
      })
    })
    if (!loginRes.code) return
    const res = await wxLoginApi(loginRes.code)
    login(res.token, { ...res.user }, res.expire)
    setLoginType('guest')
  }
  catch (e) {
    console.warn('[wx-login]', e)
  }
  // #endif
}

onLaunch(async () => {
  apply()
  hydrateAppMode()
  await load()
  await silentWxLogin()
  if (isAuthenticated()) {
    scheduleExpiryCheck()
    const u = getUser()
    if (u.role) {
      // keep loginType consistent after silent login
    }
  }
})

onShow(() => {
  apply()
  hydrateAppMode()
})
</script>

<style lang="scss">
@import '@/styles/art-fonts.scss';
@import '@/styles/art-tokens.scss';
</style>
