// 自定义路由钩子
// 没有使用到 改为重写了router的push方法 详情见utils/interceptRouterMethod.js
import router from "@/router";
import store from '@/store'


const getToRoute=(path)=>{
    // 找到要跳转到的那个路由信息
    const allRoutes=router.getRoutes()
    let routesItem={}
    allRoutes.forEach(route => {
        if(route.path===path){
            routesItem=route
        }
    });
    return routesItem
}

export default function(){

    // 路由跳转方法
    const push=({path,query})=>{
        
        // 判断是否已经存在面包屑中 
        let index=-1
        store.state.breadCrumbList.forEach((item,e) => {
            if(item.path === path){
              index=e
            }
        });
        if(index==-1){
            const routesItem=getToRoute(path)
            store.commit('setBreadCrumb', routesItem)
            router.push({
                path:path,
                query:query
            })
        }else{
            console.log('走返回逻辑',path,query);
            const _index=index-(store.state.breadCrumbList.length-1)
            router.go(_index)
            setTimeout(() => {
                router.replace({
                    query:query
                })
            }, 10);
        }
    }

    const replace=({path,query})=>{
        if(path){
            router.replace({
                path:path,
                query:query
            })
        }else{
            router.replace({
                query:query
            })
        }
    }

    const go=(num)=>{
        // let index=num+(store.state.breadCrumbList.length-1)
        // const path=store.state.breadCrumbList[index].path
        // const routesItem=getToRoute(path)
        // store.commit('setBreadCrumb', routesItem)
        router.go(num)
    }

    return {push,replace,go}
}

export const listenRouterBack=()=>{
    if(window.history&&window.history.pushState){{
        $(window).on('popstate',()=>{
            console.log('路由后退');
            const path=window.location.pathname
            const routesItem=getToRoute(path)
            store.commit('setBreadCrumb', routesItem)
        })
    }}
}