<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 { useRoute, useRouter } from 'uniapp-router-next'
import { checkAppVersion } from '@/api/app'
import { reportDevice } from '@/utils/device'

const appStore = useAppStore()
const { getUser } = useUserStore()
const { getTheme } = useThemeStore()
const router = useRouter()
const route = useRoute()

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

const getConfig = async () => {
    await appStore.getConfig()
    configLoaded = true
    //#ifdef H5
    setH5WebIcon()
    //#endif
    const { status, page_status, page_url } = appStore.getH5Config
    if (route.meta.webview) return
    //处理关闭h5渠道
    //#ifdef H5
    if (status == 0) {
        if (page_status == 1 && page_url) {
            try {
                if (new URL(page_url).origin !== location.origin) return (location.href = page_url)
            } catch (e) {
                /* page_url格式异常，走空页面 */
            }
        }
        router.reLaunch('/pages/web_closed/web_closed')
    }
    //#endif
}

onLaunch(async (options: any) => {
    console.log('[app] onLaunch 开始执行')
    // 检测邀请码
    const inviteCode = options?.query?.invite_code
    if (inviteCode) {
        uni.setStorageSync('invite_code', inviteCode)
        console.log('[app] 保存邀请码:', inviteCode)
    }
    // #ifdef H5
    // H5端从URL参数中获取invite_code
    const urlParams = new URLSearchParams(window.location.search)
    const h5InviteCode = urlParams.get('invite_code')
    if (h5InviteCode) {
        uni.setStorageSync('invite_code', h5InviteCode)
        console.log('[app] H5保存邀请码:', h5InviteCode)
    }
    // #endif
    getTheme()
    getConfig()
    // 设备信息上报（异步，失败不阻塞）
    reportDevice()
    //#ifdef H5
    setH5WebIcon()
    //#endif
    // #ifdef APP-PLUS
    checkAppUpdate()
    // #endif
    const userStore = useUserStore()
    if (userStore.isLogin) {
        try {
            await getUser()
        } catch (e) {
            console.log('[app] getUser error:', e)
        }
    }
    console.log('[app] onLaunch 执行完毕')
})

let configLoaded = false

onShow(() => {
    // iOS授权弹窗关闭后会触发onShow，此时重新拉取未成功加载的数据
    if (!configLoaded) {
        console.log('[app] onShow: config未加载，重新拉取')
        getConfig().then(() => {
            configLoaded = true
        })
    }
})

// #ifdef APP-PLUS
/**
 * 把版本号字符串(1.0.12)转为版本数字(1012)
 * 规则：主×100+次×10+修订；修订≥10时为主×1000+次×100+修订
 */
const versionNameToCode = (name: string): number => {
    const parts = String(name || '')
        .split('.')
        .map((v) => parseInt(v, 10))
    if (parts.length !== 3 || parts.some((n) => isNaN(n) || n < 0)) return 0
    const [major, minor, patch] = parts
    return patch >= 10 ? major * 1000 + minor * 100 + patch : major * 100 + minor * 10 + patch
}

const openUpgradePopup = (info: any) => {
    const packageInfo = {
        title: info.title || '发现新版本',
        subTitle: '发现新版本',
        version: info.version_name,
        contents: info.update_content || '',
        url: info.download_url,
        type: info.package_type === 1 ? 'wgt' : 'native_app',
        platform: info.platform === 2 ? ['iOS'] : ['Android'],
        is_mandatory: info.update_type === 2,
        is_silently: false,
        store_list: null
    }
    const storageKey = 'app_upgrade_info'
    uni.setStorageSync(storageKey, packageInfo)
    uni.navigateTo({
        url: `/uni_modules/uni-upgrade-center-app/pages/upgrade-popup?local_storage_key=${storageKey}`,
        fail: (err) => {
            console.error('[upgrade] 升级弹窗打开失败:', err)
            uni.removeStorageSync(storageKey)
        }
    })
}

const checkAppUpdate = () => {
    console.log('[upgrade] 开始检测App版本更新...')
    const systemInfo = uni.getSystemInfoSync()
    const appId = systemInfo.appId
    const platform = systemInfo.platform === 'ios' ? 2 : 1 // 1=Android 2=iOS
    plus.runtime.getProperty(appId, async (widgetInfo: any) => {
        // wgt 当前版本（资源包版本，热更后会更新）
        const wgtVersionName = widgetInfo.version || systemInfo.appVersion
        const wgtVersionCode = versionNameToCode(wgtVersionName)
        console.log(
            '[upgrade] platform:',
            platform,
            '| wgtVersion:',
            wgtVersionName,
            '->',
            wgtVersionCode
        )
        if (wgtVersionCode <= 0) {
            console.warn('[upgrade] 版本号格式异常，跳过检测')
            return
        }
        try {
            const res: any = await checkAppVersion({
                platform,
                version_code: wgtVersionCode
            })
            console.log('[upgrade] 接口返回:', JSON.stringify(res))
            if (res?.has_update) {
                openUpgradePopup(res)
            }
        } catch (e) {
            console.error('[upgrade] 检测失败:', e)
        }
    })
}
// #endif
</script>

<template>
    <view />
</template>
<style lang="scss">
//
</style>
