const formatTime = date => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	var t1 = [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(
		':');
	var t2 = [year, month, day].map(formatNumber).join('-');
	var time = {
		t1: t1,
		t2: t2
	};
	return time;
};

function formatTimeComm(date, format) {
	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
	var returnArr = [];
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));
	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));
	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}
	return format;
}



/**
 * 获取上一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
 */


const getPreMonth = date => {
	var arr = date.split('-');
	var year = arr[0]; //获取当前日期的年份

	var month = arr[1]; //获取当前日期的月份

	var day = arr[2]; //获取当前日期的日

	var days = new Date(year, month, 0);
	days = days.getDate(); //获取当前日期中月的天数

	var year2 = year;
	var month2 = parseInt(month) - 1;

	if (month2 == 0) {
		//如果是1月份，则取上一年的12月份
		year2 = parseInt(year2) - 1;
		month2 = 12;
	}

	var day2 = day;
	var days2 = new Date(year2, month2, 0);
	days2 = days2.getDate();

	if (day2 > days2) {
		//如果原来日期大于上一月的日期，则取当月的最大日期。比如3月的30日，在2月中没有30
		day2 = days2;
	}

	if (month2 < 10) {
		month2 = '0' + month2; //月份填补成2位。
	}

	var t1 = year + '-' + month;
	var t2 = year2 + '-' + month2;
	var time = {
		t1: t1,
		t2: t2
	};
	return time;
};

const formatNumber = n => {
	n = n.toString();
	return n[1] ? n : '0' + n;
};

const formatTimes = t => {
	let second = t % 60;
	let minute = parseInt(t / 60 % 60);
	let hour = parseInt(t / 60 / 60);
	return formatNumber(hour) + ':' + formatNumber(minute) + ":" + formatNumber(second);
};

const formatDayTimes = t => {
	let second = t % 60;
	let minute = parseInt(t / 60 % 60);
	let hour = parseInt(t / 60 / 60 % 24);
	let day = parseInt(t / 60 / 60 / 24);
	return formatNumber(day) + '天' + formatNumber(hour) + ':' + formatNumber(minute) + ":" + formatNumber(second);
};
/**
 * 判断此对象是否是Object类型
 * @param {Object} obj  
 */


function isObject(obj) {
	return Object.prototype.toString.call(obj) === '[object Object]';
}

;
/**
 * 判断此类型是否是Array类型
 * @param {Array} arr 
 */

function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]';
}

;
/**
 *  深度比较两个对象是否相同
 * @param {Object} oldData 
 * @param {Object} newData 
 */

function equalsObj(oldData, newData) {
	// 类型为基本类型时,如果相同,则返回true
	if (oldData === newData) return true;

	if (isObject(oldData) && isObject(newData) && Object.keys(oldData).length === Object.keys(newData).length) {
		// 类型为对象并且元素个数相同
		// 遍历所有对象中所有属性,判断元素是否相同
		for (const key in oldData) {
			if (oldData.hasOwnProperty(key)) {
				if (!equalsObj(oldData[key], newData[key])) // 对象中具有不相同属性 返回false
					return false;
			}
		}
	} else if (isArray(oldData) && isArray(oldData) && oldData.length === newData.length) {
		// 类型为数组并且数组长度相同
		for (let i = 0, length = oldData.length; i < length; i++) {
			if (!equalsObj(oldData[i], newData[i])) // 如果数组元素中具有不相同元素,返回false
				return false;
		}
	} else {
		// 其它类型,均返回false
		return false;
	} // 走到这里,说明数组或者对象中所有元素都相同,返回true


	return true;
}

; //时间戳转化

function transTime(date) {
	var date = new Date(parseInt(date) * 1000);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

; // 节流

function throttle(fn, gapTime) {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 1500;
	}

	let _lastTime = null; // 返回新的函数

	return function() {
		let _nowTime = +new Date();

		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments); //将this和参数传给原函数

			_lastTime = _nowTime;
		}
	};
};

const isMobile = (value) => {
	var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则

	var flag = reg.test(value);

	if (!flag) {
		return false
	} else {
		return true
	}
}

const convertUrlObj = (data) => {
	var _result = [];
	for (var key in data) {
		var value = data[key];
		if (value.constructor == Array) {
			value.forEach(function(_value) {
				_result.push(key + "=" + _value);
			});
		} else {
			_result.push(key + '=' + value);
		}
	}
	return _result.join('&');
}

// 隐藏手机号中间四位
function styleHintText(tel) {
	if (tel) {
		var reg = /^(\d{3})\d{4}(\d{4})$/;
		return tel.replace(reg, "$1****$2");
	}
	return '';

}

function getDateDiff(dateTimeStamp) {
	var minute = 1000 * 60;
	var hour = minute * 60;
	var day = hour * 24;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime();
	var diffValue = now - dateTimeStamp;
	if (diffValue < 0) {
		return;
	}
	var monthC = diffValue / month;
	var weekC = diffValue / (7 * day);
	var dayC = diffValue / day;
	var hourC = diffValue / hour;
	var minC = diffValue / minute;
	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;
}

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 removeHtml(content) {
	var temp = content.replace(/<\/?.+?>/g, "");
	var result = temp.replace(/ /g, "");
    var test = result.replace(/<br>/ig, "");
	var text = test.replace(/&nbsp;/ig, "");
	return text;
}

function styleDistanceKm(distance) {
	var distanceS = '';
	var disFloat = parseFloat(distance);
	if (disFloat > 1000) {
		disFloat = disFloat / 1000;
		distanceS = disFloat.toFixed(2) + 'km';
	} else {
		distanceS = distance + 'm';
	}
	return distanceS;
}

// 隐藏身份证
function hideCard(content) {
	var card = content;
	var strcard = card.replace(/^(.{4})(?:\d+)(.{4})$/, "$1******$2");

	return strcard;
}

//判断时间是否大于当前时间
function checkDate(date) {
	var myDate = new Date();
	var now = myDate.valueOf();
	var time = new Date(date).valueOf();
	if (now > time) {
		return false;
	} else {
		return true;
	}
}

/*比较t1 t2*/
function getTimeSpan(str1, str2) {
	var data = {
		day: 0,
		hour: 0,
		minutes: 0,
		seconds: 0,
		isExp: true
	};

	function cut2(t) {
		return t.toString().length > 1 ? t : 0 + "" + t;
	}
	if (!str1 || !str2) {
		data.isExp = false;
		return data;
	}
	var t1 = new Date((str1 * 1));
	var t2 = new Date((str2 * 1));
	if (t2 >= t1) {
		data.isExp = false;
		return data;
	}
	data.isExp = true;
	var dateDiff = t1 - t2; //时间差的毫秒数
	data.day = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
	var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
	data.hour = cut2(Math.floor(leave1 / (3600 * 1000))) //计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	data.minutes = cut2(Math.floor(leave2 / (60 * 1000))) //计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000);
	data.seconds = cut2(Math.round(leave3 / 1000))
	return data;
}

function preText(pretext) {
	if(pretext){
		return pretext.replace(/\r\n/g, '<br/>')
			.replace(/\n/g, '<br/>')
			// .replace(/\s/g, '&nbsp;')
	}else{
		return '';
	}
}

module.exports = {
	formatTime: formatTime,
	formatTimes: formatTimes,
	formatTimeComm: formatTimeComm,
	formatDayTimes: formatDayTimes,
	equalsObj: equalsObj,
	isObject: isObject,
	isArray: isArray,
	transTime: transTime,
	throttle: throttle,
	getPreMonth: getPreMonth,
	isMobile: isMobile,
	convertUrlObj: convertUrlObj,
	getDateDiff: getDateDiff,
	styleHintText: styleHintText,
	formatLocation: formatLocation,
	removeHtml: removeHtml,
	styleDistanceKm: styleDistanceKm,
	hideCard: hideCard,
	checkDate: checkDate,
	getTimeSpan: getTimeSpan,
	preText: preText
};
