import carhelp from '@/apis/utils/mixin.js'

import * as API_WeiXin from '@/apis/weixin.js'

import {
	getUrlParam,
	getWeixinRedirectURI,
	isWeiXin
} from '@/apis/utils'
var checkOpenId = true; //是否需要获取openId
var openId = carhelp.getOpenId();

var app = {
	initTest: function() {
		// isWeiXin()|| 
		if(isWeiXin() ){
			console.log("?/////////")
			if (!openId) {
				this.getOpenId();
			} else {
				this.getPersion(openId)
			}
			
		}else{
			alert("请使用微信打开本页面")
			
		}
		
		
	},
	init: function() {
		// isWeiXin()|| 
		if(!(process.env.NODE_ENV === "development") ){
			if (isWeiXin()) {
				if (checkOpenId) {
					if (!openId) {
						this.getOpenId();
					} else {
						this.getPersion(openId)
					}
				}
			} else{
				var NODE_NAME=  process.env['NODE_NAME']
				if(NODE_NAME=="production"){
					alert("请使用微信打开本页面")
				}
			}
		}else{
			carhelp.setOpenId(process.car.openId)
			this.getPersion(process.car.openId)
		}
		
		
	},
	 getPersion(thisopenId){
		 console.log("init")
		 var tdate=new Date( +new Date() + 8 * 3600 * 1000 ).toJSON().substr(0,15).replace("T"," ")
		 var token_tdate=carhelp.get("token_tdate");//每10分钟存储一次token
		 
		  if(token_tdate&&token_tdate==tdate){
			return
		  }
		  
		 var loginurl="/mobile/employeeUser/findByOpenId"
		  
		 uni.request({
		 	method:'get',
		 	url: process.car.BASE_URL + loginurl,
		 	data: {
		 		openId:thisopenId,
		 	},
		 	header: {
		 		'Content-Type': 'application/x-www-form-urlencoded',
		 		'X-Requested-With': 'XMLHttpRequest',
		 		//'Authorization':token
		 	}
		 }).then((response) => {
		 	let [error, res] = response;
		 	
		 	if (res.data.code == 200&&res.data.result) {
		 		
		 		var token = res ? res.data.data.token : '';
		 		carhelp.setPersonInfo(res.data.data.regUser );
		 		carhelp.setPersonInfoPlus(res.data.data );
		 		
		 		carhelp.setToken(token);
		 	 
		 	}else{
				carhelp.logoff();
			}
		 }).catch(error => {
		 	
		 	
		 })
	 },
	getOpenId() {
		
		const code = getUrlParam('code');
		var openId = carhelp.getOpenId()
		if (!openId) {
			if (!code) {
				var url = document.URL;
				var getUrl= getWeixinRedirectURI(process.car.VUE_APP_WXAPPID, url);
				 
				window.location.href = getUrl;
			} else {
				
				API_WeiXin.getDataByCode(code).then(response => {
					
					carhelp.setOpenId(response.data.openid)
					openId = response.data.openid;
					carhelp.set("xpgj_wx_user_info",response.data)
					
					 location.reload();
				}).catch(error => {
					console.log(error);
				});
			}
		}
	}
}
module.exports = app
