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

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

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

    // 是否有历史页面
    const hasHistory = () => {
        const state = animateRouter.getState()
        return state.historyRoutes.length > 1
    }

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

    // 获取参数字符串----废弃待优化
    const getParamString = (name: string) => {
        // https://github.com/vuejs/router/releases/tag/v4.1.0
        return route.params[name] ?? ''
    }

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

    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>(name: string, params?: T) => {
    //     const { state } = animateRouter
    //     const total = state.history.length - 1
    //     const index = state.history.findIndex(((e) => e.name === name))

    //     if (total > -1) {
    //         if (index > -1) {
    //             setGlobalUrlParams(params)
    //             const delta = total - index
    //             if (delta > 0) {
    //                 router.go(-delta)
    //             } else {
    //                 router.replace({ name })
    //             }
    //         }
    //     } else {
    //         router.replace({ name })
    //     }
    // }

    // 返回主页
    const backHome = () => {
        const state = animateRouter.getState()
        const delta = state.historyRoutes.length - 1
        if (delta > 0) {
            router.go(-delta)
        } else {
            const page = state.historyRoutes[0]
            if (page?.name !== 'HomeIndex') {
                router.replace({ name: 'HomeIndex' })
            }
        }
    }

    // 返回上个页面
    const routerBack = <T extends object>(params?: T) => {
        setGlobalUrlParams(params)
        if (hasHistory()) {
            router.back()
        } else {
            router.replace({ path: '/' })
        }
    }

    // 路由跳转
    const routerTo = (name: string, replace = false) => {
        if (replace) {
            router.replace({ name })
        } else {
            router.push({ name })
        }
    }

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

    return {
        route,
        router,
        hasHistory,
        setGlobalUrlParams,
        getGlobalUrlParams,
        getParamString,
        getQueryString,
        getQueryStringToNumber,
        backHome,
        routerBack,
        routerTo,
        beforeRouteLeave,
    }
}