import { createApp } from 'vue'
import App from './App.vue'
import { setupI18n } from './locales'
import { setupAssets, setupScrollbarStyle } from './plugins'
import { setupStore } from './store'
import { setupRouter } from './router'
import { fetchOpenid, fetchRedirectUrl } from '@/api'
import { useStorage } from '@vueuse/core'
import { init as initEruda } from '@/utils/console'

if (useStorage('showConsole', 0).value > new Date().getTime()) {
    initEruda()
} else if (location.origin.includes('http://192.168')) {
    initEruda()
}
sessionStorage.entryUrl = location.href
console.log('entryUrl', sessionStorage.entryUrl)
const query = new URLSearchParams(location.search)
const invitor = query.get('invitor')
if (invitor) {
    useStorage('invitor', '', sessionStorage).value = invitor as string
}
// const

const isWechat = /micromessenger/i.test(navigator.userAgent)

const openid = useStorage('openid', '', sessionStorage)
if (isWechat) {
    if (!openid.value) {
        const code = query.get('code')
        if (code) {
            fetchOpenid(code as string).then(res => {
                openid.value = res as string
            })
        } else {
            fetchRedirectUrl(window.location.origin + '/ui/home').then((res: any) => {
                window.location.href = res.url
            })
        }
    }
}

const loadSplash = (onload?: any, onerror?: any) =>
    new Promise((resolve, reject) => {
        let isHide = false
        function hideSplash() {
            if (isHide) return
            isHide = true
            if (splash) {
                splash.style.opacity = '0'
                setTimeout(() => {
                    splash.style.display = 'none'
                }, 800)
            }
            resolve('')
        }
        const splash = document.getElementById('splash-screen')
        if (splash) {
            splash.style.opacity = '1'
            splash.style.display = 'block'
        }
        setTimeout(() => {
            hideSplash()
        }, 1000)
    })

async function bootstrap() {
    const app = createApp(App)
    setupAssets()

    setupScrollbarStyle()

    setupStore(app)

    setupI18n(app)

    await setupRouter(app)
    await loadSplash()

    app.mount('#app')
}

bootstrap()
