import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import animateRouter from '@mobile/router/animateRouter'

export function useNavigation() {
    const route = useRoute()
    const router = useRouter()

    // 缓存全局Url参数
    const setGlobalUrlParams = (params: unknown) => {
        sessionStorage.setItem('globalUrlParams', JSON.stringify(params))
    }

    // 获取全局Url参数(只能获取一次)
    const getGlobalUrlParams = () => {
        const params = sessionStorage.getItem('globalUrlParams')
        if (params) {
            sessionStorage.removeItem('globalUrlParams')
            return JSON.parse(params)
        } else {
            return {}
        }
    }

    // 获取查询字符串
    const getQueryString = (name: string) => {
        const qs = route.query[name]
        if (qs) {
            return qs.toString()
        }
        return ''
    }

    const getQueryStringToNumber = (name: string) => {
        const reg = /^[0-9]+.?[0-9]*/
        const value = getQueryString(name)
        return reg.test(value) ? Number(value) : 0
    }

    // 返回指定页面
    const backTo = <T extends object>(to: string, params?: T) => {
        const { state } = animateRouter
        const total = state.history.length - 1
        const index = state.history.findIndex(((e) => e.name === to))

        if (index > -1) {
            const delta = total - index
            if (delta > 0) {
                setGlobalUrlParams(params ?? {})
                router.go(-delta)
            }
        }
    }

    // 路由跳转
    const routerTo = (to: string) => {
        router.push({ name: to })
    }

    // 导航守卫
    const beforeRouteLeave = (callback: () => boolean) => {
        onBeforeRouteLeave((to, from, next) => {
            if (callback()) {
                next()
            } else {
                next(false)
            }
        })
    }

    return {
        route,
        router,
        setGlobalUrlParams,
        getGlobalUrlParams,
        getQueryString,
        getQueryStringToNumber,
        backTo,
        routerTo,
        beforeRouteLeave,
    }
}