import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
	return VueRouterPush.call(this, to).catch(err => err)
}

//标题js
import getPageTitle from "@/utils/title-config";

const Index = () => import('views/index/index')
const Recommend = () => import('views/index/recommend/Recommend')
const Collect = () => import('views/index/collect/Collect')
const AllSections = () => import('views/index/allSections/AllSections')
const search = () => import('views/search/search')
const SearchResult = () => import('views/search/searchResult/SearchResult')
const user = () => import('views/user/user')
const userIndex = () => import('views/user/UserIndex')
const detail = () => import('views/detail/detail')
const detailIndex = () => import('views/detail/detailIndex')

const routes = [
	{
		// 首页
		// path: '*',
		path: '/',
		name: 'Index',
		redirect: "/recommend",
		component: Index,
		children: [
			{
				path: '/recommend',
				name: 'Recommend',
				component: Recommend,
				meta: {
					title: "推荐版块"
				}
			},
			{
				path: '/collect',
				name: 'Collect',
				component: Collect,
				meta: {
					title: "收藏的版块"
				}
			},
			{
				path: '/allSections',
				name: 'AllSections',
				component: AllSections,
				meta: {
					title: "全部版块"
				}
			},
		]
	}, {
		path: '/searchResult',   // 搜索结果
		name: 'search',
		redirect: "/searchResult",
		component: search,
		children: [
			{
				path: '/searchResult',
				name: 'Recommend',
				component: SearchResult,
				meta: {
					title: "搜索帖子"
				}
			},
		]
	}, {
		path: '/user',   // 我的
		name: 'user',
		redirect: "/userIndex",
		component: user,
		children: [
			{
				path: '/userIndex',
				name: 'userIndex',
				component: userIndex,
				meta: {
					title: "我的寄托"
				}
			},
		]
	}, {
		path: '/detail',   // 帖子详情
		name: 'detail',
		redirect: "/detailIndex",
		component: detail,
		children: [
			{
				path: '/detailIndex',
				name: 'detailIndex',
				component: detailIndex,
				meta: {
					title: "帖子详情"
				}
			},
		]
	}
]

const router = new VueRouter({
	mode: 'history',
	// mode: 'hash',
	// mode: process.env.NODE_ENV == "development" ? 'hash' : 'history',
	// base: process.env.BASE_URL,
	routes
})

// 判断是不是首次 加载
let isInitialNavigation = true

router.beforeEach(async (to, from, next) => {
	if (to.meta.title) document.title = getPageTitle(to.meta.title);

	if (isInitialNavigation) {
		isInitialNavigation = false
	} else {
		if (window._hmt) {
			if (to.path) {
				window._hmt.push(['_trackPageview', '/#' + to.fullPath])
			}
		}

		if (window._czc) {
			let location = window.location
			let contentUrl = location.pathname + location.hash
			let refererUrl = "/"
			// 用于发送某个URL的PV统计请求
			window._czc.push(["_trackPageview", contentUrl, refererUrl])
		}

	}

	next();
});

export default router
