function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

var getQuery=function(name){
  return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
 }

/* 登录判断 */
var persistLogin=function(_this) {
	 disableTurnPage();
	let storageState = uni.getStorageSync('storage_state');
	//console.info('_this.$store',_this.$store);
	if(_this.$store.state){
		if (!_this.$store.state.isLogin) { //缓存中有值，重新赋值
		   
			if (storageState.isLogin) {
				console.info("缓存中storageState isLogin为真有值重新给状态赋值");
				setState(_this,storageState);
				
				
			} else { //缓存中没值，跳转到登录页面
				//console.info("当前页面路径:" + _this.route);
				console.info("缓存中storageState isLogin为假");
				if (_this.route !== "/" && _this.route.toLocaleLowerCase() !== "/pages/login/login") {
					console.info('util重新登录');
					uni.navigateTo({
						url: '/'
					});
				}
			}
		} else {
			console.info("_this.$store.state.isLogin为真")
			setStateFromStorage(_this,storageState);
		}
		
	}
	else{
		console.info('_this.$store.state=null');
		setStateFromStorage(_this);
	}
}

function setStateFromStorage(_this,storageState){
	if (storageState) {
		let obj = _this.$store.state;
		for (let key in obj) {
			if (obj[key]) {
				//设置状态中的各种值
				if (key == 'token') {
					_this.$store.commit('setToken', storageState.token);
				}
				if (key == 'avatar') {
					_this.$store.commit('setAvatar', storageState.avatar);
				}
				if (key == 'name') {
					_this.$store.commit('setName', storageState.name);
				}
				if (key == 'introduction') {
					_this.$store.commit('setIntroduction', storageState.introduction);
				}
				if (key == 'roles') {
					_this.$store.commit('setRoles', storageState.roles);
				}
				if (key == 'user') {
					_this.$store.commit('setUser', storageState.user);
				}
				if (key == 'stationName') {
					_this.$store.commit('setStationName', storageState.stationName);
				}
				if (key == 'stationCode') {
					_this.$store.commit('setStationCode', storageState.stationCode);
				}
				if (key == 'departmentName') {
					_this.$store.commit('setDepartmentName', storageState.departmentName);
				}
				if (key == 'departmentCode') {
					_this.$store.commit('setDepartmentCode', storageState.departmentCode);
				}
				if (key == 'projectCode') {
					_this.$store.commit('setProjectCode', storageState.projectCode);
				}
			
			}
		}
			
	}
	else{
		//console.info("当前页面路径:" + _this.route);
		if (_this.route !== "/" && _this.route.toLocaleLowerCase() !== "/pages/login/login") {
			console.info('util重新登录');
			uni.navigateTo({
				url: '/'
			});
		}
	}
}
/* 设置状态值 */
function setState(_this,storageState){
	if(storageState){
		//设置状态中的各种值
		_this.$store.commit('setIsLogin', storageState.isLogin);
		_this.$store.commit('setToken', storageState.token);
		_this.$store.commit('setAvatar', storageState.avatar);
		_this.$store.commit('setName', storageState.name);
		_this.$store.commit('setIntroduction', storageState.introduction);
		_this.$store.commit('setRoles', storageState.roles);
		_this.$store.commit('setUser', storageState.user);
		_this.$store.commit('setStationName', storageState.stationName);
		_this.$store.commit('setStationCode', storageState.stationCode);
		_this.$store.commit('setDepartmentName', storageState.departmentName);
		_this.$store.commit('setDepartmentCode', storageState.departmentCode);
		_this.$store.commit('setProjectCode', storageState.projectCode);
	}	
}
/* 获取状态值 */
function getState(_this,key){
	let storageState=uni.getStorageSync("storage_state");
	if(key==='isLogin'){
		if(!_this.$store.state.isLogin){
			if(storageState){
				_this.$store.commit('setIsLogin', storageState.isLogin);
			}
			
		}
		 return _this.$store.state.isLogin;
	}
	if(key==='userCode'){
		if(!_this.$store.state.user||!_this.$store.state.user.userCode){
			if(storageState){
				_this.$store.commit('setUser', storageState.user);
			}
			
		}
		 return _this.$store.state.user.userCode;
	}
	if (key == 'projectCode') {
		if(!_this.$store.state.projectCode){
			if(storageState){
				_this.$store.commit('setProjectCode', storageState.projectCode);
			}
			
		}
		return _this.$store.state.projectCode;
	}
	return ""; 
}
/* 日期格式 */
var getDate=function(type) {
	const date = new Date();

	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();

	if (type === 'start') {
		year = year - 60;
	} else if (type === 'end') {
		year = year + 2;
	}
	month = month > 9 ? month : '0' + month;;
	day = day > 9 ? day : '0' + day;

	return `${year}-${month}-${day}`;
}
/* 禁用左右翻页 */
function disableTurnPage(){
	document.addEventListener("touchstart",function(e){
	    startX = e.touches[0].pageX;
	
	    startY = e.touches[0].pageY;
	
	});
	document.addEventListener('touchmove', function(event) {
		//console.info('左右滑动',event);
		//当屏幕有多个touch或者页面被缩放过，就不执行move操作
		if (event.targetTouches.length > 1 || event.scale && event.scale !== 1) return;
		var touch = event.targetTouches[0];
		
		endPos = {
			x: touch.pageX - startX,
			y: touch.pageY - startY
		};
		isScrolling = Math.abs(endPos.x) < Math.abs(endPos.y) ? 1 : 0; //isScrolling为1时，表示纵向滑动，0为横向滑动
		if (isScrolling === 0) {    //横向滑动
			// alert(0);
			event.preventDefault(); //阻止触摸事件的默认行为，即阻止滚屏
			
		}
	}, { passive: false });
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	getQuery:getQuery ,      //获取url的某个参数
	persistLogin:persistLogin,
	getDate:getDate,
	setState:setState,       //自storage中获取状态值，重新给状态赋值
	getState:getState 
	 
}
