import { useUserStore } from '@/stores/user'
import cache from '@/utils/cache'
import { BACK_URL } from '@/enums/constantEnums'

/**
 * 检查是否已登录，未登录则弹窗确认后跳转登录页
 * @returns Promise<boolean> true=已登录可继续，false=未登录已拦截
 */
export function checkLogin(): Promise<boolean> {
    return new Promise((resolve) => {
        const userStore = useUserStore()
        if (userStore.isLogin) {
            resolve(true)
            return
        }
        uni.showModal({
            title: '提示',
            content: '该功能需要登录，是否前往登录？',
            confirmText: '去登录',
            cancelText: '取消',
            success: (res) => {
                if (res.confirm) {
                    // 记录当前页面，登录后可返回
                    const pages = getCurrentPages()
                    const current = pages[pages.length - 1]
                    if (current) {
                        const route = '/' + current.route
                        const options = (current as any).options || {}
                        const query = Object.keys(options)
                            .map((k) => `${k}=${options[k]}`)
                            .join('&')
                        cache.set(BACK_URL, query ? `${route}?${query}` : route)
                    }
                    uni.navigateTo({ url: '/pages/login/login' })
                }
                resolve(false)
            }
        })
    })
}
