/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
	{ path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
	{ path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
	path: '/',
	component: _import('main'),
	name: 'main',
	redirect: { name: 'home' },
	meta: { title: '主入口整体布局' },
	children: [
		// 通过meta对象设置路由展示方式
		// 1. isTab: 是否通过tab展示内容, true: 是, false: 否
		// 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
		// 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
		{ path: '/home', component: _import('common/home'), name: 'home', meta: { title: '首页' } },
		{ path: '/userList', component: _import('user/userList'), name: 'userList', meta: { title: '用户列表', isTab: true } },
		{ path: '/allocationList', component: _import('allocation/allocationList'), name: 'allocationList', meta: { title: '配置列表', isTab: true } },
		{ path: '/financeList', component: _import('finance/financeList'), name: 'financeList', meta: { title: '财务中心', isTab: true } },
		{ path: '/message', component: _import('message/message'), name: 'message', meta: { title: '消息中心', isTab: true } },
		{ path: '/taskConfig', component: _import('taskConfig/taskConfig'), name: 'taskConfig', meta: { title: '任务配置', isTab: true } },
		{ path: '/bannerList', component: _import('banner/bannerList'), name: 'bannerList', meta: { title: '首页装修', isTab: true } },
		{ path: '/materialPackage', component: _import('materialPackage/materialPackage'), name: 'materialPackage', meta: { title: '物料包', isTab: true } },
		{ path: '/HistoryOfMaterialPackage', component: _import('materialPackage/HistoryOfMaterialPackage'), name: 'HistoryOfMaterialPackage', meta: { title: '物料包历史记录', isTab: true } },
		{ path: '/mission', component: _import('mission/mission'), name: 'mission', meta: { title: '项目列表', isTab: true } },
		{ path: '/system', component: _import('mission/system'), name: 'system', meta: { title: '系统任务', isTab: true } },
		{ path: '/missionsye', component: _import('sysmission/missionsye'), name: 'missionsye', meta: { title: '活动派送', isTab: true } },
		{ path: '/materialsList', component: _import('materials/materialsList'), name: 'materialsList', meta: { title: '帮助中心', isTab: true } },
		{ path: '/missionAdd', component: _import('mission/missionAdd'), name: 'missionAdd', meta: { title: '发布任务', isTab: false } },
		{ path: '/missionRedact', component: _import('sysmission/missionRedact'), name: 'missionRedact', meta: { title: '修改任务', isTab: false } },
		{ path: '/userDetail', component: _import('user/userDetail'), name: 'userDetail', meta: { title: '用户详情', isTab: false } },
		{ path: '/userDetail1', component: _import('user/userDetail1'), name: 'userDetail1', meta: { title: '用户详情', isTab: false } },
		{ path: '/missionDetails', component: _import('mission/missionDetails'), name: 'missionDetails', meta: { title: '任务详情', isTab: false } },
		{ path: '/fitmentList', component: _import('fitment/fitmentList'), name: 'fitmentList', meta: { title: '升级配置', isTab: false } },
		{ path: '/integral', component: _import('integral/integral'), name: 'integral', meta: { title: '积分推送', isTab: true } },
		{ path: '/integralDetail', component: _import('integral/integralDetail'), name: 'integralDetail', meta: { title: '活动详情', isTab: false } },
		{ path: '/campus', component: _import('campus/campus'), name: 'campus', meta: { title: '片区列表', isTab: true } },
		{ path: '/missionComplain', component: _import('mission/missionComplain'), name: 'missionComplain', meta: { title: '任务投诉', isTab: true } },
		{ path: '/feedback', component: _import('mission/feedback'), name: 'feedback', meta: { title: '反馈中心', isTab: true } },
		{ path: '/autonym', component: _import('autonym/autonym'), name: 'autonym', meta: { title: '师傅认证', isTab: true } },
		{ path: '/locality', component: _import('locality/locality'), name: 'locality', meta: { title: '项目中心', isTab: true } },
		{ path: '/materialLink', component: _import('locality/materialLink'), name: 'materialLink', meta: { title: '素材链接', isTab: true } },
		{ path: '/orderCenter', component: _import('orderCenter/orderCenter'), name: 'orderCenter', meta: { title: '订单列表', isTab: true } },
		{ path: '/vueMchat', component: _import('vueMchat/vueMchat'), name: 'vueMchat', meta: { title: '聊天会话', isTab: true } },
		{ path: '/memberDetails', component: _import('members/memberDetails'), name: 'memberDetails', meta: { title: '会员配置', isTab: true } },
		{ path: '/vipPrivilege', component: _import('user/vipPrivilege'), name: 'vipPrivilege', meta: { title: '会员特权', isTab: true } },
		// {path: '/vipPrivilege', component: _import('vipPrivilege/vipPrivilege'), name: 'vipPrivilege', meta: { title: '会员特权',isTab: true} },
		{ path: '/app', component: _import('app/app'), name: 'app', meta: { title: '升级配置', isTab: true } },
		{ path: '/chatRecord', component: _import('chatRecord/chatRecord'), name: 'chatRecord', meta: { title: '聊天记录', isTab: true } },
		{ path: '/cardMarketing', component: _import('cardMarketing/cardMarketing'), name: 'cardMarketing', meta: { title: '优惠卡券管理', isTab: true } },
		{ path: '/applyList', component: _import('applyList/applyList'), name: 'applyList', meta: { title: '师傅申请列表', isTab: true } },

		// 2023.01.04 按摩3.0版本新增
		{ path: '/shifuScheduling', component: _import('riderScheduling/shifuScheduling'), name: 'shifuScheduling', meta: { title: '师傅地图', isTab: true } },
		{ path: '/skynetCenter', component: _import('skynetCenter/skynetCenter'), name: 'skynetCenter', meta: { title: '天网中心', isTab: true } },
		{ path: '/couponYhq', component: _import('campus/couponYhq'), name: 'couponYhq', meta: { title: '优惠券', isTab: true } },
		{ path: '/couponYhqList', component: _import('campus/couponYhqList'), name: 'couponYhqList', meta: { title: '优惠券列表', isTab: true } },
		{ path: '/couponissue', component: _import('campus/couponissue'), name: 'couponissue', meta: { title: '已发布优惠券', isTab: true } },
		{ path: '/couponuser', component: _import('campus/couponuser'), name: 'couponuser', meta: { title: '优惠券领取记录', isTab: true } },
		{ path: '/coupon', component: _import('campus/coupon'), name: 'coupon', meta: { title: '卡密管理', isTab: true } },
		{ path: '/IntegralGoods', component: _import('integral/IntegralGoods'), name: 'IntegralGoods', meta: { title: '充值配置', isTab: true } },
		{ path: '/exchangeList', component: _import('integral/exchangeList'), name: 'exchangeList', meta: { title: '充值记录', isTab: true } },
		{ path: '/comment', component: _import('comment/comment'), name: 'comment', meta: { title: '评价中心', isTab: true } },
		{ path: '/business', component: _import('business/business'), name: 'business', meta: { title: '投诉中心', isTab: true } },
		{ path: '/emergencyHelp', component: _import('business/emergencyHelp'), name: 'emergencyHelp', meta: { title: '紧急求助', isTab: true } },
		{ path: '/travel', component: _import('taskConfig/travel'), name: 'travel', meta: { title: '开放城市', isTab: true } },
		{ path: '/agent', component: _import('recruit/agent'), name: 'agent', meta: { title: '推广代理', isTab: true } },

		// 2023.02.16 按摩 4.0版本 新增
		{ path: '/cityVoting', component: _import('cityVoting/cityVoting'), name: 'cityVoting', meta: { title: '城市投票', isTab: true } },
		{ path: '/signIn', component: _import('applyList/signIn'), name: 'signIn', meta: { title: '签到记录', isTab: true } },
		{ path: '/technician', component: _import('applyList/technician'), name: 'technician', meta: { title: '师傅列表', isTab: true } },
		{ path: '/riderTop', component: _import('riderTop/riderTop'), name: 'riderTop', meta: { title: '收益排行榜', isTab: true } },
		{ path: '/czlTop', component: _import('riderTop/czlTop'), name: 'czlTop', meta: { title: '排行榜', isTab: true } },
		// 2023.02.27 4.5版本 新增

		{ path: '/masterPosition', component: _import('business/masterPosition'), name: 'masterPosition', meta: { title: '师傅位置记录', isTab: true } },
		{ path: '/orderInService', component: _import('business/orderInService'), name: 'orderInService', meta: { title: '服务中订单', isTab: true } },


		// 2023.02.16 按摩 5.0 版本 新增
		// 采购商城
		{ path: '/classifyAdmin', component: _import('purchaseShop/classifyAdmin'), name: 'classifyAdmin', meta: { title: '商品分类', isTab: true } },
		{ path: '/orderAdmin', component: _import('purchaseShop/orderAdmin'), name: 'orderAdmin', meta: { title: '自营订单', isTab: true } },
		{ path: '/shopAdmin', component: _import('purchaseShop/shopAdmin'), name: 'shopAdmin', meta: { title: '商品管理', isTab: true } },
		{ path: '/fenxiaoOrder', component: _import('purchaseShop/fenxiaoOrder'), name: 'fenxiaoOrder', meta: { title: '分销订单', isTab: true }, },
		{ path: '/disposeOrder', component: _import('purchaseShop/disposeOrder'), name: 'disposeOrder', meta: { title: '待处理订单', isTab: true }, },
		{ path: '/shopConfig', component: _import('purchaseShop/shopConfig'), name: 'shopConfig', meta: { title: '商城配置', isTab: true } },
		{ path: '/shopPublish', component: _import('purchaseShop/shopPublish'), name: 'shopPublish', meta: { title: '发布商品', isTab: false } },
		{ path: '/shopAmend', component: _import('purchaseShop/shopAmend'), name: 'shopAmend', meta: { title: '修改商品', isTab: false } },
		{ path: '/specification', component: _import('purchaseShop/specification'), name: 'specification', meta: { title: '商品规格', isTab: true } },
		{ path: '/orderDetails', component: _import('purchaseShop/orderDetails'), name: 'orderDetails', meta: { title: '订单详情', isTab: false } },
		{ path: '/taskConfig1', component: _import('purchaseShop/taskConfig'), name: 'taskConfig1', meta: { title: '商城配置', isTab: true } },
		{ path: '/discuss', component: _import('purchaseShop/discuss'), name: 'discuss', meta: { title: '评价列表', isTab: true } },
		{ path: '/addressAamin', component: _import('purchaseShop/addressAamin'), name: 'addressAamin', meta: { title: '地址管理', isTab: true } },
		// { path: '/integralPackage', component: _import('purchaseShop/integralPackage'), name: 'integralPackage', meta: { title: '积分包管理',isTab: true} },
		{ path: '/integralist', component: _import('purchaseShop/integralist'), name: 'integralist', meta: { title: '积分商品', isTab: true } },
		{ path: '/intepublich', component: _import('purchaseShop/intepublich'), name: 'intepublich', meta: { title: '添加积分商品', isTab: false } },
		{ path: '/inteAmend', component: _import('purchaseShop/inteAmend'), name: 'inteAmend', meta: { title: '修改积分商品', isTab: false } },
		{ path: '/allocationJifen', component: _import('purchaseShop/allocationJifen'), name: 'allocationJifen', meta: { title: '积分配置', isTab: true } },
		// 商家管理
		{ path: '/merchantList', component: _import('business/merchantList'), name: 'merchantList', meta: { title: '商家管理', isTab: true } },
		{ path: '/profitList', component: _import('business/profitList'), name: 'profitList', meta: { title: '商家收益统计', isTab: false } },
		{ path: '/merchantDetailList', component: _import('business/merchantDetailList'), name: 'merchantDetailList', meta: { title: '商家信息', isTab: true } },
		// 2023.03.13 新增
		{ path: '/top', component: _import('riderTop/top'), name: 'top', meta: { title: '信用分排行榜', isTab: true } },
		{ path: '/creditScore', component: _import('riderTop/creditScore'), name: 'creditScore', meta: { title: '信用分明细', isTab: true } },
		// 2023.03.23
		{ path: '/conversionRate', component: _import('conversionRate/conversionRate'), name: 'conversionRate', meta: { title: '转化率列表', isTab: true } },
		// 2024.06.05
		{ path: '/massagePackage', component: _import('bl/massage/massagePackage'), name: 'massagePackage', meta: { title: '服务包列表', isTab: true } },
		// 2024.07.17
		{ path: '/massageActivity', component: _import('bl/activity/massageActivity'), name: 'massageActivity', meta: { title: '活动列表', isTab: true } },
		// 2024.06.08
		{ path: '/packageOrder', component: _import('bl/order/packageOrder'), name: 'packageOrder', meta: { title: '服务包订单', isTab: true } },
		{ path: '/dlssqjl', component: _import('dlssqjl/dlssqjl'), name: 'dlssqjl', meta: { title: '代理商申请', isTab: true } },
		{ path: '/travelConf', component: _import('travelConf/index'), name: 'travelConf', meta: { title: '出行配置', isTab: true } },
		{ path: '/fxyConfig', component: _import('bl/commission/fxy/fxyConfig'), name: 'fxyConfig', meta: { title: '分销员设置', isTab: true } },
		{ path: '/fxyApply', component: _import('bl/commission/fxy/fxyApply'), name: 'fxyApply', meta: { title: '分销员审核', isTab: true } },
		{ path: '/fxyData', component: _import('bl/commission/fxy/fxyData'), name: 'fxyData', meta: { title: '分销员数据', isTab: true } },
		{ path: '/fxyOrder', component: _import('bl/commission/fxy/fxyOrder'), name: 'fxyOrder', meta: { title: '分销员门槛订单', isTab: true } },
		{ path: '/jjrConfig', component: _import('bl/commission/jjr/jjrConfig'), name: 'jjrConfig', meta: { title: '经纪人设置', isTab: true } },
		{ path: '/jjrConfigLevel', component: _import('bl/commission/jjr/jjrConfigLevel'), name: 'jjrConfigLevel', meta: { title: '经纪人等级', isTab: true } },
		{ path: '/jjrApply', component: _import('bl/commission/jjr/jjrApply'), name: 'jjrApply', meta: { title: '经纪人审核', isTab: true } },
		{ path: '/jjrData', component: _import('bl/commission/jjr/jjrData'), name: 'jjrData', meta: { title: '经纪人数据', isTab: true } },
		{ path: '/ywyConfig', component: _import('bl/commission/ywy/ywyConfig'), name: 'ywyConfig', meta: { title: '业务员设置', isTab: true } },
		{ path: '/ywyApply', component: _import('bl/commission/ywy/ywyApply'), name: 'ywyApply', meta: { title: '业务员审核', isTab: true } },

		{ path: '/qdsConfig', component: _import('bl/commission/qds/qdsConfig'), name: 'qdsConfig', meta: { title: '渠道商设置', isTab: true } },
		{ path: '/qdsApply', component: _import('bl/commission/qds/qdsApply'), name: 'qdsApply', meta: { title: '渠道商审核', isTab: true } },
		{ path: '/qdsCode', component: _import('bl/commission/qds/qdsCode'), name: 'qdsCode', meta: { title: '渠道码管理', isTab: true } },
		{ path: '/qdsData', component: _import('bl/commission/qds/qdsData'), name: 'qdsData', meta: { title: '渠道码统计', isTab: true } },
		{ path: '/qdsLm', component: _import('bl/commission/qds/qdsLm'), name: 'qdsLm', meta: { title: '渠道商类目', isTab: true } },
		{ path: '/artificerAchievementIntegral', component: _import('bl/artificer/artificerAchievementIntegral'), name: 'artificerAchievementIntegral', meta: { title: '技师业绩积分关系列表', isTab: true } },
		{ path: '/artificerPartitioningDetails', component: _import('bl/artificer/artificerPartitioningDetails'), name: 'artificerPartitioningDetails', meta: { title: '技师分成明细配置列表', isTab: true } },
		{ path: '/artificerRechargeReward', component: _import('bl/artificer/artificerRechargeReward'), name: 'artificerRechargeReward', meta: { title: '技师充值奖励配置列表', isTab: true } },
		{ path: '/blPingjiaTag', component: _import('bl/pingjiaTag/blPingjiaTag'), name: 'blPingjiaTag', meta: { title: '用户评价标签', isTab: true } },
		{ path: '/shipinquan', component: _import('bl/shipinquan/shipinquan'), name: 'shipinquan', meta: { title: '视频圈', isTab: true } },
	],
	beforeEnter(to, from, next) {
		let token = Vue.cookie.get('token')
		if (!token || !/\S/.test(token)) {
			clearLoginInfo()
			next({ name: 'login' })
		}
		next()
	}
}

const router = new Router({
	mode: 'history', //  hash
	scrollBehavior: () => ({ y: 0 }),
	isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
	routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
	// 添加动态(菜单)路由
	// 1. 已经添加 or 全局路由, 直接访问
	// 2. 获取菜单列表, 添加并保存本地存储
	if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
		next()
	} else {
		http({
			url: http.adornUrl('/sys/menu/nav'),
			method: 'get',
			params: http.adornParams()
		}).then(({ data }) => {
			if (data && data.code === 0) {
				fnAddDynamicMenuRoutes(data.menuList)
				router.options.isAddDynamicMenuRoutes = true
				sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
				sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
				next({ ...to, replace: true })
			} else {
				sessionStorage.setItem('menuList', '[]')
				sessionStorage.setItem('permissions', '[]')
				next()
			}
		}).catch((e) => {
			// console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
			router.push({ name: 'login' })
		})
	}
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
	var temp = []
	for (var i = 0; i < globalRoutes.length; i++) {
		if (route.path === globalRoutes[i].path) {
			return 'global'
		} else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
			temp = temp.concat(globalRoutes[i].children)
		}
	}
	return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
	var temp = []
	for (var i = 0; i < menuList.length; i++) {
		if (menuList[i].list && menuList[i].list.length >= 1) {
			temp = temp.concat(menuList[i].list)
		} else if (menuList[i].url && /\S/.test(menuList[i].url)) {
			menuList[i].url = menuList[i].url.replace(/^\//, '')
			var route = {
				path: menuList[i].url.replace('/', '-'),
				component: null,
				name: menuList[i].url.replace('/', '-'),
				meta: {
					menuId: menuList[i].menuId,
					title: menuList[i].name,
					isDynamic: true,
					isTab: true,
					iframeUrl: ''
				}
			}
			// url以http[s]://开头, 通过iframe展示
			if (isURL(menuList[i].url)) {
				route['path'] = `i-${menuList[i].menuId}`
				route['name'] = `i-${menuList[i].menuId}`
				route['meta']['iframeUrl'] = menuList[i].url
			} else {
				try {
					route['component'] = _import(`modules/${menuList[i].url}`) || null
				} catch (e) {
				}
			}
			routes.push(route)
		}
	}
	if (temp.length >= 1) {
		fnAddDynamicMenuRoutes(temp, routes)
	} else {
		mainRoutes.name = 'main-dynamic'
		mainRoutes.children = routes
		router.addRoutes([
			mainRoutes,
			{ path: '*', redirect: { name: '404' } }
		])
		sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
		// console.log('\n')
		// console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
		// console.log(mainRoutes.children)
		// console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
	}
}

export default router
