<script setup lang="ts">
import { onLaunch, onShow } from '@dcloudio/uni-app'
import { useAppStore } from './stores/app'
import { useUserStore } from './stores/user'
import { useThemeStore } from '@/stores/theme'
import { addVisit } from './api/shop'
import { useSharedId } from './hooks/useShareMessage'
import { SHARE_ID, USER_SN } from './enums/constantEnums'
import { strToParams } from './utils/util'
import cache from './utils/cache'
import Cookies from 'js-cookie'
import { client } from '@/utils/client'

const appStore = useAppStore()
const { getUser } = useUserStore()
const { getTheme } = useThemeStore()

const cacheInvite = (query: any = {}) => {
    const { share_id } = query
    const user_sn =
        query.user_sn ||
        strToParams(decodeURIComponent(query['scene']))['user_sn'];
    console.log(query)
    console.log(user_sn)
    if (share_id) {
        cache.set(SHARE_ID, share_id)
    }
    if (user_sn) {
        cache.set(USER_SN, user_sn)
    }
}

//#ifdef H5
const setH5WebIcon = () => {
    const config = appStore.getWebsiteConfig
    let favicon: HTMLLinkElement = document.querySelector('link[rel="icon"]')!
    if (favicon) {
        favicon.href = config.logo
        return
    }
    favicon = document.createElement('link')
    favicon.rel = 'icon'
    favicon.href = config.logo
    document.head.appendChild(favicon)
}
//#endif

const getConfig = async () => {

    await setLocalStorage()
    // 获取配置信息
    await appStore.getConfig()
    //处理关闭h5渠道
    // #ifdef H5
    const { status, close, url } = appStore.getH5Config
    if (status == 0) {
        if (close == 1) return (location.href = url)
        uni.reLaunch({ url: '/pages/empty/empty' })
    }
    // #endif
}


// 企微登录
const setLocalStorage = async () => {
    const isWeCom = isWechatWork()

    // 获取localStorage中的配置信息
    const token = localStorage.getItem('app_token')
    const cookiesToken = Cookies.get('token')

    if (!cookiesToken) {
        if (isWeCom) {
            // 写入cookie
            const redirect = location.href
            Cookies.set('redirect', redirect)
            location.href = `${import.meta.env.VITE_APP_BASE_URL}/qywx/getWxUserByInside?terminal=${client}`
            return
        }
    } else {
        const obj = { expire: "", value: cookiesToken }
        localStorage.setItem("app_token", JSON.stringify(obj));
    }

}


// 判断是否为企微环境
const isWechatWork = () => {
    const ua = navigator.userAgent.toLowerCase();
    // 同时匹配 "micromessenger"（微信内核）和 "wxwork"（企业微信标识）
    return ua.includes('micromessenger') && ua.includes('wxwork');
}

onLaunch(async (opinion) => {
    getConfig()
    getTheme()
    await addVisit()
    getUser()
    useSharedId()
    cacheInvite(opinion?.query)
    //#ifdef H5
    setH5WebIcon()
    //#endif
})

onShow(() => {
    uni.hideTabBar()
})
</script>
<style lang="scss">
//</style>
