var tools = {

	tokenKey: "token",
	shopInfoKey: "shopInfo",

	getToken() {
		try {
			const value = uni.getStorageSync(this.tokenKey);
			// console.log('[getToken]', value);
			return value
		} catch (e) {
			console.log('[getToken] fail', e);
			return "";
		}
	},

	setToken(token) {
		try {
			uni.setStorageSync(this.tokenKey, token);
		} catch (e) {
			console.log('[setToken] fail', e);
		}
	},

	getShopInfo() {
		try {
			const value = uni.getStorageSync(this.shopInfoKey);
			// console.log('[getShopInfo]', value);
			return value
		} catch (e) {
			console.log('[getShopInfo] fail', e);
			return "";
		}
	},

	setShopInfo(shopinfo) {
		try {
			uni.setStorageSync(this.shopInfoKey, shopinfo);
		} catch (e) {
			console.log('[setShopInfo] fail', e);
		}
	},

	// 检测token
	checkToken(token) {
		const regex = /^[0-9A-Za-f]{32}$/;
		if (regex.test(token)) {
			return true;
		} else { // 未登录
			console.log('checkToken err! token: ', token);
			uni.showToast({
				title: `您尚未登录`,
				icon: 'none',
				duration: 3000
			});

			uni.navigateTo({
				url: '/pages/login/login'
			});
			return false;
		}
	},

	// 判断赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
	checkMcState(beginSecond, endSecond) {
		let mcState = 0; // 未开始
		if (beginSecond > 0 && endSecond > 0) {
			const now = Date.now() / 1000;
			const dif1 = beginSecond - now;
			const dif2 = endSecond - now;
			// const dif = 3600*24 - 60;
			if (dif1 > 0) {
				console.log("活动未开始");
				mcState = 0; // 未开始
			} else if (dif2 > 0) {
				console.log("活动进行中");
				mcState = 1; // 进行中
			} else {
				console.log("活动已结束");
				mcState = 2; // 已结束
			}
		}
		return mcState;
	},

	// 动态创建<style>标签，将CSS代码插入到文档中
	loadCssCode(cssCode) {
		this.removeCssCode();

		const styleId = "css-custom";
		var style = window.document.createElement("style");
		style.type = "text/css";
		style.id = styleId;
		if (style.styleSheet) {
			// This is required for IE8 and below.
			style.styleSheet.cssText = cssCode;
		} else {
			style.appendChild(document.createTextNode(cssCode));
		}
		document.getElementsByTagName("head")[0].appendChild(style);
		// console.log("head:", document.getElementsByTagName("head")[0]);
		// console.log("head:", document.getElementById(styleId));
		// console.log("style:", style);
	},

	// 删除之前动态创建的<style>标签
	removeCssCode() {
		const styleId = "css-custom";
		var oldCss = document.getElementById(styleId);
		// console.log("oldCss:", oldCss);
		if (oldCss != null) {
			document.getElementsByTagName("head")[0].removeChild(oldCss);
			console.log("oldCss 已移除");
		}
	},

	// uni-data-select 组件，根据选中的值获取对应的文本
	getSelectedText(obj, value) {
		const selectedOption = obj.find(option => option.value === value);
		return selectedOption ? selectedOption.text : '';
	},

	objectToQueryString(obj) {
		return Object.keys(obj).map(k => k + '=' + obj[k]).join('&');
	},

	// 秒数转换成 XX天XX小时
	convertSecondsToDHM(seconds) {
		var days = Math.floor(seconds / (3600 * 24));
		var hours = Math.floor((seconds % (3600 * 24)) / 3600);
		var minutes = Math.floor((seconds % (3600 * 24)) % 3600 / 60);
		if (days > 0)
			// return `${days.toString().padStart(2, '0')}天${hours.toString().padStart(2, '0')}小时`;
			return `${days}天${hours.toString().padStart(2, '0')}小时`;
		else
			return `${hours.toString().padStart(2, '0')}小时${minutes.toString().padStart(2, '0')}分钟`;
	},

	// 秒数转换成时分秒
	// style:  0 [01:02:03]  1 [1h:02'3"]
	convertSecondsToHMS(seconds, style = 0) {
		var hours = Math.floor(seconds / 3600);
		var minutes = Math.floor((seconds % 3600) / 60);
		var remainingSeconds = Math.floor(seconds % 60);
		// return hours + ":" + minutes + ":" + remainingSeconds;
		if (style == 0)
			return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
		else if (style == 1) {
			if (hours > 0)
				return `${hours}h:${minutes}′${remainingSeconds}″`;
			else
				return `${minutes}′${remainingSeconds}″`;
		}
	},

	// 计算（中英文混合）字符串长度
	calStrLen(str) {
		var length = 0;
		for (var i = 0; i < str.length; i++) {
			// 将字符转换为 Unicode 编码
			var charCode = str.charCodeAt(i);
			if (charCode >= 0 && charCode <= 128) {
				length++;
			} else {
				length += 2;
			}
		}

		return length;
	},

	// 集合对象去重
	unique(arr, field) {
		var map = {};
		var res = [];
		for (var i = 0; i < arr.length; i++) {
			if (!map[arr[i][field]]) {
				map[arr[i][field]] = 1;
				res.push(arr[i]);
			}
		}
		return res;
	},

	// 正则取出html标签
	repalceHtml(str) {
		var dd = str.replace(/<\/?.+?>/g, "");
		var dds = dd.replace(/ /g, ""); //dds为得到后的内容
		return dds;
	},

	// 判断身份证号    
	isSfz(idcard) {
		var id =
			/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
		if (idcard === '') {
			uni.showToast({
				title: '请输入身份证号',
				icon: 'none'
			})
		} else if (!id.test(idcard)) {
			uni.showToast({
				title: '身份证号格式不正确!',
				icon: 'none'
			})
			return false
		} else {
			return false
		}
	},

	// 判断是否是手机号   
	isPhone(val) {
		var patrn = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/
		if (!patrn.test(val) || val === '') {
			uni.showToast({
				title: '手机号格式不正确',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},

	// 判断邮箱
	isEmail(email) {
		if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
			return true;
		else
			return false;
	},

	//获取随机数
	getSuiji() {
		var Range = Max - Min;
		var Rand = Math.random();
		return (Min + Math.round(Rand * Range));
	},

	// 获取指定时间内指定数量的年月列表
	getMonthList(monthNum=6, timestamp = "") {
		var data = null;
		
		if (timestamp > 0)
			data = new Date(timestamp);
		else
			data = new Date();
			
		var year = data.getFullYear();
		var mon = data.getMonth() + 1;
		var arry = new Array();
		for (var i = 0; i < monthNum; i++) {
			if (mon <= 0) {
				year = year - 1;
				mon = mon + 12;
			}
			if (mon < 10) {
				mon = "0" + mon;
			}
			arry[i] = year + "-" + mon;
			mon = mon - 1;
		}

		return arry;
	},

	//计算多长时间前
	getDateDiff(dateTimeStamp) {
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var halfamonth = day * 15;
		var month = day * 30;
		var year = day * 365;
		var now = new Date().getTime();
		var diffValue = now - dateTimeStamp;
		if (diffValue < 0) {
			return;
		}
		var yearC = diffValue / year;
		var monthC = diffValue / month;
		var weekC = diffValue / (7 * day);
		var dayC = diffValue / day;
		var hourC = diffValue / hour;
		var minC = diffValue / minute;
		if (yearC >= 1) {
			result = "" + parseInt(yearC) + "年前";
		}
		if (monthC >= 1) {
			result = "" + parseInt(monthC) + "月前";
		} else if (weekC >= 1) {
			result = "" + parseInt(weekC) + "周前";
		} else if (dayC >= 1) {
			result = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else
			result = "刚刚";
		return result;
	},

	// 时间戳转时间
	timestampToTime(timestamp, i) {
		var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		// console.log(date, timestamp)
		var Y = date.getFullYear();
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		if (i == 1) {
			return Y + '-' + M + '-' + D;
		} else if (i == 2) {
			return Y + '年' + M + '月' + D + '日';
		} else if (i == 3) {
			return Y + '-' + M + '-' + D + ' ' + h + ':' + m;
		} else if (i == 4) {
			return Y + '-' + M;
		}
		return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
	},

	// 是否是汉字
	isHanzi(str) {
		let reg = /\p{Unified_Ideograph}/ug;
		return reg.test(str);
	},

	// 是否是字母数字
	isStringAndNumber(str) {
		let regNumber = new RegExp(/^[0-9A-Za-z]+$/);
		return regNumber.test(str)
	},

	// var arr3 = [30,10,111,35,1899,50,45];
	// 集合排序  元素数字
	listSort(list) {
		arr3.sort(function(a, b) {
			return a - b;
		})
	},

	// var arr5 = [{id:10},{id:5},{id:6},{id:9},{id:2},{id:3}];
	// 元素  对象
	listObjectSort(arr) {
		arr.sort(function(a, b) {
			return a.id - b.id
		})
		return arr;
	},

	/*
	 * 忽略大小写判断字符串是否相同
	 * @param str1
	 * @param str2
	 * @returns {Boolean}
	 */
	isEqualsIgnorecase: function(str1, str2) {
		if (str1.toUpperCase() == str2.toUpperCase()) {
			return true;
		} else {
			return false;
		}
	},

	/**
	 * 判断是否是数字
	 * @param value
	 * @returns {Boolean}
	 */
	isNum: function(value) {
		if (value != null && value.length > 0 && isNaN(value) == false) {
			return true;
		} else {
			return false;
		}
	},

	/**
	 * 判断是否是中文
	 * @param str
	 * @returns {Boolean}
	 */
	isChine: function(str) {
		var reg = /^([u4E00-u9FA5]|[uFE30-uFFA0])*$/;
		if (reg.test(str)) {
			return false;
		}
		return true;
	},

	/*验证是否为图片*/
	tmCheckImage: function(fileName) {
		return /(gif|jpg|jpeg|png|GIF|JPG|PNG)$/ig.test(fileName);
	},

	/*验证是否为视频*/
	tmCheckVideo: function(fileName) {
		return /(mp4|mp3|flv|wav)$/ig.test(fileName);
	},

	/**
	 * 去除字符串两边的空格
	 * @param str
	 * @returns {number|Number}
	 * 调用方法：var str = utils.trim("abcd")
	 */
	trim: function(str) {
		String.prototype.trim = function() {
			return str.replace(/(^\s*)|(\s*$)/g, "");
		}
	},

	// 判断密码是否符合 至少6位,包括大小写字母、数字、特殊字符
	isPassword(val) {
		var reg = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{8,16}$/;
		if (val === '') {
			uni.showToast({
				title: '请输入密码',
				icon: 'none'
			})
		} else if (!reg.test(val)) {
			uni.showToast({
				title: '至少6位,包括大小写字母、数字、特殊字符',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},

	// 电话匿名
	noPassByMobile(str) {
		if (null != str && str != undefined) {
			var pat = /(\d{3})\d*(\d{4})/;
			return str.replace(pat, '$1****$2');
		} else {
			return "";
		}
	},

	// 获取两点间的距离
	//进行经纬度转换为距离的计算
	Rad(d) {
		return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
	},

	/*
	 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
	 默认单位km
	*/
	getMapDistance(lat1, lat2, lng1, lng2) {
		lat1 = lat1 || 0;
		lng1 = lng1 || 0;
		lat2 = lat2 || 0;
		lng2 = lng2 || 0;

		var rad1 = lat1 * Math.PI / 180.0;
		var rad2 = lat2 * Math.PI / 180.0;
		var a = rad1 - rad2;
		var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
		var r = 6378137;
		var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) *
			Math.pow(Math.sin(b / 2), 2)));
		// console.log(lat1, lng1, lat2, lng2);
		// console.log(distance);
		return Math.round(distance) / 1000;
	},

	// 预览图片
	yulanImg(item) {
		let arr = [item]
		uni.previewImage({
			urls: arr,
		});
	},

}

export default tools;