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('.')
	}
}

function distanceByLnglat(lat1, lng1, lat2, lng2) {
	var radLat1 = lat1 * Math.PI / 180.0;
	var radLat2 = lat2 * Math.PI / 180.0;
	var a = radLat1 - radLat2;
	var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
		.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	return s
};

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 date = 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.getDay()) + '-' +
			_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 currentFormatDate = {
	formatDate: function(nows, type) {
		var now = new Date(nows * 1000);
		var year = now.getFullYear(); //取得4位数的年份
		var month = now.getMonth() + 1; //取得日期中的月份，其中0表示1月，11表示12月
		var date = now.getDate(); //返回日期月份中的天数（1到31）
		var hour = now.getHours(); //返回日期中的小时数（0到23）
		var minute = now.getMinutes(); //返回日期中的分钟数（0到59）
		var second = now.getSeconds(); //返回日期中的秒数（0到59）
		// return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
		if (type == 1) {
			return year + "-" + this._format(month) + "-" + this._format(date);
		} else {
			return year + "-" + this._format(month) + "-" + this._format(date) + " " + this._format(hour) +
				":" + this._format(
					minute);
		}
	},

	_format: function(number) {
		return (number < 10 ? ('0' + number) : number);
	},
}

var formatDates = {
	formatDate: function(nows) {
		var now = new Date(nows * 1000);
		var year = now.getFullYear(); //取得4位数的年份
		var month = now.getMonth() + 1; //取得日期中的月份，其中0表示1月，11表示12月
		var date = now.getDate(); //返回日期月份中的天数（1到31）
		var hour = now.getHours(); //返回日期中的小时数（0到23）
		var minute = now.getMinutes(); //返回日期中的分钟数（0到59）
		var second = now.getSeconds(); //返回日期中的秒数（0到59）
		// return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
		// return year + "-" + this._format(month) + "-" + this._format(date) + " " + this._format(hour) + ":" + this._format(
		// 	minute);

		return this._format(month) + "/" + this._format(date) + " " + this._format(hour) + ":" + this._format(
			minute);
	},

	_format: function(number) {
		return (number < 10 ? ('0' + number) : number);
	},
}

function getNumber(num, total) {
	var num = parseFloat(num);
	var total = parseFloat(total);
	if (isNaN(num) || isNaN(total)) {
		return;
	}
	return (Math.round((total - num) / total * 100))
}

var getUrlArgs = function() {
	// var argStr = window.location.href ? window.location.href.substring(1) : "";
	var argStr = window.location.search ? window.location.search.substring(1) : "";
	var argObj = {},
		item = null,
		value = null,
		key = null,
		argArr = argStr.length > 0 ? argStr.split("&") : [];
	for (var i = 0, len = argArr.length; i < len; i++) {
		item = argArr[i].split("=");
		key = item[0];
		value = item[1];
		argObj[key] = value;
	}
	return argObj;
}

let _debounceTimeout = null,
	_throttleRunning = false

/**
 * 防抖
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms   
 */
export const debounce = (fn, delay = 500) => {
	clearTimeout(_debounceTimeout);
	_debounceTimeout = setTimeout(() => {
		fn();
	}, delay);
}

/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms  
 */
const throttle = (fn, delay = 500) => {
	if (_throttleRunning) {
		return;
	}
	_throttleRunning = true;
	fn();
	setTimeout(() => {
		_throttleRunning = false;
	}, delay);
}

/**
 * 检查登录
 * @return {Boolean}
 */
export const isLogin = (options = {}) => {
	const token = uni.getStorageSync('token');
	if (token) {
		return true;
	}
	if (options.nav !== false) {
		uni.navigateTo({
			url: '/pages/auth/login'
		})
	}
	return false;
}

/**
 * 获取页面栈
 * @param {Number} preIndex为1时获取上一页
 * @return {Object} 
 */
const prePage = (preIndex = 1) => {
	const pages = getCurrentPages();
	const prePage = pages[pages.length - (preIndex + 1)];

	return prePage.$vm;
}

/**
 * 格式化时间戳 Y-m-d H:i:s
 * @param {String} format Y-m-d H:i:s
 * @param {Number} timestamp 时间戳   
 * @return {String}
 */
export const date = (format, timeStamp) => {
	if ('' + timeStamp.length <= 10) {
		timeStamp = +timeStamp * 1000;
	} else {
		timeStamp = +timeStamp;
	}
	let _date = new Date(timeStamp),
		Y = _date.getFullYear(),
		m = _date.getMonth() + 1,
		d = _date.getDate(),
		H = _date.getHours(),
		i = _date.getMinutes(),
		s = _date.getSeconds();

	m = m < 10 ? '0' + m : m;
	d = d < 10 ? '0' + d : d;
	H = H < 10 ? '0' + H : H;
	i = i < 10 ? '0' + i : i;
	s = s < 10 ? '0' + s : s;

	return format.replace(/[YmdHis]/g, key => {
		return {
			Y,
			m,
			d,
			H,
			i,
			s
		} [key];
	});
}

//二维数组去重
export const getUnique = array => {
	let obj = {}
	return array.filter((item, index) => {
		let newItem = item + JSON.stringify(item)
		return obj.hasOwnProperty(newItem) ? false : obj[newItem] = true
	})
}

// 判断类型集合
const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str)
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^([a-zA-Z0-9_]){6,18}$/.test(str)
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str)
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
				/^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		default:
			return true;
	}
}

/**
 * toast
 */
export const msg = (title = '', param = {}) => {
	if (!title) return;
	uni.showToast({
		title,
		duration: param.duration || 1500,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}

/**
 * getDate
 */
export const getDate = (type) => {
	const date = new Date();

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

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

	return `${year}-${month}-${day}`;
}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	distanceByLnglat: distanceByLnglat,
	dateUtils: dateUtils,
	getNumber: getNumber,
	currentFormatDate: currentFormatDate,
	getUrlArgs: getUrlArgs,
	checkStr: checkStr,
	throttle: throttle,
	isLogin: isLogin,
	debounce: debounce,
	prePage: prePage,
	date: date,
	msg: msg,
	getDate: getDate
}
