import { userLogin, updateLocation} from '../api/apiList'
import { APP_ID , ENV_MODEL, TokenPrefix} from '../publicConfig/config'

module.exports = {
	methods: {
		//获取微信token
		getWxToken() {
			uni.login({
				success: (res) => {
					this.login(res.code)
				}
			})
		},
		// 获取H5 Code
		getH5Code() {
			let url = encodeURIComponent(window.location.href)
			let code = this.getQueryString('code');
			let time = new Date().getTime();
			let appId = ''
			if(process.env.NODE_ENV === 'development'){
				appId = APP_ID.h5Dev
			} else {
				switch(ENV_MODEL.model){				
					case 'UAT':
					appId = APP_ID.h5Uat
					break;
					default:
					appId = APP_ID.h5Prod
				}
			}		
			if (code) {
				return { code, time }
			} else { //用户从公众号的会话或者自定义菜单进入本公众号的网页授权页，即使是scope为snsapi_userinfo，也是静默授权，用户无感知。
				let href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
				window.location.href = href
			}
		},

		//用户登录
		login(code) {
			const _this = this
			const { loginAction, projectMini } = getApp().globalData
			try {
				let { pagePath, route } = this.getPathRoute(1) //获取跳转前当前页面完整路径及路由
				// #ifdef H5
				pagePath = window.location.href.split('#')[1] //获取跳转前当前页面完整路径及路由
				route = pagePath.split('?')[0]
				// #endif				
				userLogin(loginAction, code, { entryName: projectMini }).then(res => {
					let XSRFToken = ''
					//#ifdef MP  
					if (res.header['Set-Cookie']) {
						XSRFToken = res.header['Set-Cookie'].split(';')[0].split('=')[1]
						uni.setStorageSync(`${TokenPrefix}_XSRFToken`, XSRFToken);
					}
					//#endif

					// #ifdef H5
					XSRFToken = _this.getCookies('XSRF-TOKEN')
					uni.setStorageSync(`${TokenPrefix}_XSRFToken`, XSRFToken);
					// #endif

					const messageType = res.data.messageType
					if (messageType === 'success') {
						let token = res.data.renewedToken
						uni.setStorageSync(`${TokenPrefix}_token`, token);
						// #ifdef MP
						uni.setStorageSync('cookies', res.cookies)
						// #endif
						if (route && route !== 'pages/login/login' && route !== '/') {
							uni.reLaunch({ url: pagePath, }) //可跳转至任意页面
						} else {
							uni.switchTab({
								url: '/pages/index/index',
							})
						}
						// #ifdef MP
						// _this.onUpdateLocation()
						// #endif
					}
				}).catch(err => {
					if (route && route !== 'pages/login/login' && route !== '/') { //非登录页认证，则跳转至登录页面
					    getApp().globalData.backPagePath = pagePath //当需要跳转登录页面，跳转前记录当前页面，作为回退页面
					 	uni.navigateTo({
							url: '/pages/login/login'
						})
					}
					uni.showToast({
						title: err.message,
						icon: 'none',
						duration: 3000
					})
				})
			} catch (err) {}
		},
		//获取页面完整路径及路由， pageIndex为页面索引,
		getPathRoute(pageIndex) {
			let pagePath = ''
			let route = '' //当前页面完整路径及路由
			const pages = getCurrentPages() // 获取所有页面实例,以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。在onLaunch时获取为空，因为页面还未加载
			const currentPage = pages[pages.length - pageIndex] //获取当前页面实例
			if (currentPage) {
				pagePath = currentPage.$page.fullPath
				route = currentPage.route
			}
			return { pagePath, route }
		},

		// 开始地理位置监听
		onUpdateLocation() {
			uni.startLocationUpdateBackground({
				success: res => {
					console.log('开启小程序接收位置消息成功')
					uni.onLocationChange(function(res) {
						const { longitude, latitude, speed } = res
						const timestamp = new Date().getTime()
						const data = {
							aux: {
								map: {
									gpsDevice: {
										licensePlateNo: '沪TESTM01',
										deviceType: 'MiniApp'
									},
									gpsDataList: [{ longitude, latitude, speed, timestamp }]
								}
							}
						}
						updateLocation(data)
					});
				},
				fail: err => console.log('开启小程序接收位置消息失败：', err),
			})
		},

		getCookies(cName) { // 调用函数let  cookie_val = getCookie(cookie的名字);
			var name = cName + "=";
			var ca = document.cookie.split(';');
			for (var i = 0; i < ca.length; i++) {
				var c = ca[i].trim();
				if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
			}
			return "";
		},

		getQueryString(name) {
			let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			let r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
			let context = "";
			if (r != null)
				context = decodeURIComponent(r[2]);
			reg = null;
			r = null;
			return context == null || context == "" || context == "undefined" ? "" : context;
		},
	}
};
