// #ifdef APP-PLUS
import { useUserStoreWithOut } from '@/store/modules/user'
import checkVersion from '@/uni_modules/uni-upgrade-center-app/utils/check-update'

// #endif

export async function checkUpgrade(toast = false): Promise<void> {
    const userStore = useUserStoreWithOut()

    // 审核模式，直接跳过更新检查
    if (userStore.isAuditMode) {
        return Promise.resolve()
    }

    // #ifdef APP-PLUS
    // 版本更新检查
    if (toast) {
        Message.loading('正在检查更新...')
    }
    try {
        const res = await checkVersion()
        if (toast && res?.code === 0) {
            Message.toast('已是最新版本~')
        }
    } finally {
        if (toast) {
            Message.hideLoading()
        }
    }
    // #endif
}

/**
 * 关闭 splashscreen 并检查更新
 */
export function closeSplashscreenAndChechUpgrade() {
    return new Promise<void>((resolve, reject) => {
        // FIXED: pages 第一路由页面为登录页，加上 splashscreen 配置控制使得用户体验更好
        // #ifdef APP-PLUS
        nextTick(() => {
            // FIX: 延时执行，解决安卓环境下可能意外看到登录页的问题
            const { platform } = uni.getSystemInfoSync()
            const isAndroid = platform === 'android'
            setTimeout(
                async () => {
                    plus.navigator.closeSplashscreen()
                    try {
                        // 检查更新
                        await checkUpgrade()
                        resolve()
                    } catch (e) {
                        reject(e)
                    }
                },
                isAndroid ? 200 : 50,
            )
        })
        // #endif
        // #ifndef APP-PLUS
        resolve()
        // #endif
    })
}
