import api from "@/api/api";
import dataHandling from './dataHandling'
import { initJssdkShare, setWechatShare } from '@/util/fiveshare';
import { shareURL } from "@/environments/environment";
import wx from 'weixin-js-sdk'
//只要是未登录状态，想要跳转到名单内的路径时，直接跳到登录页
// 页面白名单，不受拦截
const whiteList = [
	'/myPackageA/login/login',
	'/myPackageA/businessCard/businessCard',
	'/pages/invitationRegister/invitationlogin',
	'/myPackageA/applyFranchise/applyFranchise',
	'/pages/applyFranchise/applyFranchise',
	'/myPackageA/ruleAndContract/clause',
	'/pages/orderDetail/orderDetail',
	'/pages/courseDetail/courseDetail',
	'/pages/courselist/courselist',
	'/pages/personalCenter/helpCenter',
	'/pages/index/index',
	'pages/lanch/index',
	'/myPackageA/poster/poster',
]
// 作为h5内嵌到小小程序时，自定义页面分享内容得页面
let shareCustomPageList = [
	'/pages/courselist/courselist',
	'/myPackageA/businessCard/businessCard',
]
export default function initApp() {
	let date = Date.now()
	
	uni.addInterceptor('navigateTo', {
		// 页面跳转前进行拦截, invoke根据返回值进行判断是否继续执行跳转
		invoke(e) {
			
			let userInfo = {}
			if (uni.getStorageSync('cffp_userInfo')) {
				userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
			}

			let pages = getCurrentPages()
			let pagesLength = pages.length
			if (shareCustomPageList.indexOf(e.url) == -1) {
				if (dataHandling.h5RuntimeEnv() == 'wechat-miniprogram') {
					let shareInfo = {
						title: '成为银盾合伙人，分享商品赚不停',
						desc: `资源+伙伴，共赢未来！`,
						link: `${shareURL}/pages/index/index?miniShare=1`, //分享链接
						imgUrl: `${shareURL}/myPackageA/static/images/logo3.png`, //图片
						commonId: uni.getStorageSync('cffp_userId'),
						sharePage: 'index' //分享出去得页面
					}
					wx.miniProgram.postMessage({
						data: {
							type: 'share',
							shareData: JSON.stringify(shareInfo)
						}

					})
					return
				}
			}
			
			if (whiteList.indexOf(e.url) == -1 && !uni.getStorageSync('loginType')) {

				uni.setStorageSync('loginType', 'visitor')
				uni.navigateTo({
					url: '/myPackageA/login/login'
				})
			}
			if (uni.getStorageSync('cffp_userId')) {
				api.queryInfo({ userId: uni.getStorageSync('cffp_userId') }).then(res => {
					if (!res['success']) {
						uni.setStorageSync('loginType', 'visitor')
						uni.navigateTo({
							url: '/myPackageA/login/login'
						})
						return true
					}
					// 保存用户得个人信息
					if (res['success']) {
						delete res.data.commonResult
						const cffp_userInfo = {
							...res.data
						}
						// 账号禁用用户
						if(res.data.userIsActive&&res.data.userIsActive==2){
							
							uni.setStorageSync('userIsActive',String(res.data.userIsActive))
							return
						}
						if(res.data.userIsActive&&res.data.userIsActive!=2){
							
							uni.removeStorageSync('userIsActive')
						}
						uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo))
					}
					

				})
			}
			if (userInfo.userIsActive == 2 && uni.getStorageSync('loginType') == 'codelogin') {
				const currentPage = getCurrentPages()[getCurrentPages().length - 1];
				currentPage.$refs.restrictedTip.open()

				return false; // 返回对象而不是布尔值
			}
			let whiteArr = ['index', 'personalCenter', 'courselist', 'product']
			// 1. 解析 URL 中的 from 参数
			const getQueryParam = (url, key) => {
				const queryString = url.split('?')[1];
				if (!queryString) return null;
				const params = new URLSearchParams(queryString);
				return params.get(key);
			};

			const fromParam = getQueryParam(e.url, 'from');
			if (!hasPermission(e.url)) {
				// 如果 from 参数在 whiteArr 中，说明是tabbar页带着tabbar的标志参数跳转到登录页，以便未登录状态下回到对应的tabbar页
				if (fromParam && whiteArr.includes(fromParam)) {
					uni.redirectTo({
						url: `/myPackageA/login/login?from=${fromParam}`
					})
				} else {
					uni.redirectTo({
						url: '/myPackageA/login/login'
					})
				}

				return false
			}
			//当页面栈的个数大于10个时，不入页面栈
			if (pagesLength >= 10) {
				//临时处理，跟换调整方式
				uni.redirectTo({
					url: e.url
				})
			} else {
				if (date) {
					//如果时间戳存在 那么记录此页面的停留时间
					dataHandling.pocessTracking(
						'停留',
						`用户在此页面停留${(Date.now() - date) / 1000}秒`,
						'进入页面后离开页面',
						2
					)
				}
				date = Date.now()
			}
			return true
		},
		success(e) {}
	})
	uni.addInterceptor('switchTab', {
		// tabbar页面跳转前进行拦截
		invoke(e) {
			// 账号禁用用户不让跳转
			if(uni.getStorageSync('userIsActive')&&uni.getStorageSync('userIsActive')==2){
				
				return false
			}
			
			if (shareCustomPageList.indexOf(e.url) == -1) {
				if (dataHandling.h5RuntimeEnv() == 'wechat-miniprogram') {
					let shareInfo = {
						title: '成为银盾合伙人，分享商品赚不停',
						desc: `资源+伙伴，共赢未来！`,
						link: `${shareURL}/pages/index/index?miniShare=1`, //分享链接
						imgUrl: `${shareURL}/myPackageA/static/images/logo3.png`, //图片
						commonId: uni.getStorageSync('cffp_userId'),
						sharePage: 'index' //分享出去得页面
					}
					wx.miniProgram.postMessage({
						data: {
							type: 'share',
							shareData: JSON.stringify(shareInfo)
						}

					})
					return
				}
			}
			if (date) {
				//如果时间戳存在 那么记录此页面的停留时间
				dataHandling.pocessTracking(
					'停留',
					`用户在此页面停留${(Date.now() - date) / 1000}秒`,
					'进入页面后离开页面',
					2
				)
			}
			date = Date.now()
			return true
		},
		success(e) {}
	})
	uni.addInterceptor('reLaunch', {
		//页面跳转前拦截
		invoke(e) {
			// 账号禁用用户不让跳转
			if(uni.getStorageSync('userIsActive')&&uni.getStorageSync('userIsActive')==2){
				
				return false
			}
			if (shareCustomPageList.indexOf(e.url) == -1) {
				if (dataHandling.h5RuntimeEnv() == 'wechat-miniprogram') {
					let shareInfo = {
						title: '成为银盾合伙人，分享商品赚不停',
						desc: `资源+伙伴，共赢未来！`,
						link: `${shareURL}/pages/index/index?miniShare=1`, //分享链接
						imgUrl: `${shareURL}/myPackageA/static/images/logo3.png`, //图片
						commonId: uni.getStorageSync('cffp_userId'),
						sharePage: 'index' //分享出去得页面
					}
					wx.miniProgram.postMessage({
						data: {
							type: 'share',
							shareData: JSON.stringify(shareInfo)
						}

					})
					return
				}
			}
			if (date) {
				//如果时间戳存在 那么记录此页面的停留时间
				dataHandling.pocessTracking(
					'停留',
					`用户在此页面停留${(Date.now() - date) / 1000}秒`,
					'进入页面后离开页面',
					2
				)
			}
			date = Date.now()
			return true
		},
		//页面跳转后缓存当前页路由
		success(e) {}
	})
}

function hasPermission(url) {
	let islogin = uni.getStorageSync("isLogin"); //在这可以使用token、vuex
	// islogin = Boolean(Number(islogin));//返回布尔值
	// 在白名单中或有登录判断条件可以直接跳转

	if (whiteList.indexOf(url.slice(0, url.indexOf('?'))) !== -1 || islogin) {
		return true
	}
	return false
}