export const currentTimeStamp = () => new Date().getTime()

export const unixTimeStamp = (val) => new Date(val).getTime()

//今天多少天之前的时间
export const beforeTimeStamp = (dayCount) => {
	let dd = new Date()
	dd.setDate(dd.getDate() - dayCount)
	let time = dd.getTime()
	return time
}

//今天多少天之后的时间
export const afterTimeStamp = (dayCount, date) => {
	if (date) {
		var dd = new Date(date);
	} else {
		var dd = new Date();
	}
	dd.setDate(dd.getDate() + dayCount)
	let time = dd.getTime()
	return time
}

//今天多少年之后的时间
export const afterYearTimeStamp = (yearCount, date) => {
	if (date) {
		var dd = new Date(date);
	} else {
		var dd = new Date();
	}
	dd.setFullYear(dd.getFullYear() + yearCount)
	let time = dd.getTime()
	return time
}

//计算某日期距当前的时间秒数
export const secondsDistance = (date) => {
	var now = new Date().getTime();
	date = new Date(date).getTime();
	var seconds = parseInt((now - date) / 1000);
	return seconds;
}

//计算两个时间的相差天数
export const daysDistance = (date1, date2) => {
	date1 = Date.parse(replaceTime(date1));
	date2 = Date.parse(replaceTime(date2));
	var ms = date2 - date1;
	ms = ms < 0 ? 0 : ms;
	var days = parseInt(Math.floor(ms / (24 * 3600 * 1000)));
	return days;
}

function replaceTime(time) {
	if (time == null) {
		return time;
	}
	return time.replace(/\-/g, "\/");
}
//计算两个时间的相差小时数
export const hourDistanceArr = (date1, date2) => {
	if (!date1 || !date2) {
		return '-';
	}
	date1 = Date.parse(replaceTime(date1));
	date2 = Date.parse(replaceTime(date2));
	var ms = date2 - date1;
	ms = ms < 0 ? 0 : ms;
	ms = ms / 1000; //s
	var Hour = parseInt(Math.floor(ms / (60 * 60)));
	var Fen = parseInt(Math.floor(ms % (60 * 60) / 60));
	var s = parseInt(Math.floor(ms % (60)));
	//600000
	return [Hour, Fen, s]
}
//计算两个时间的相差小时数
export const hourDistance = (date1, date2) => {
	if (!date1 || !date2) {
		return '-';
	}
	date1 = Date.parse(date1);
	date2 = Date.parse(date2);
	var ms = date2 - date1;
	ms = ms < 0 ? 0 : ms;
	ms = ms / 1000; //s
	var Hour = parseInt(Math.floor(ms / (60 * 60)));
	var Fen = parseInt(Math.floor(ms % (60 * 60) / 60));
	var s = parseInt(Math.floor(ms % (60)));
	//600000
	return Hour + '小时' + Fen + '分钟' + s + '秒';
}

export const parseUnixTime = (time, cFormat) => {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (('' + time).length === 10) time = parseInt(time) * 1000
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})

	return time_str
}

//微信获取code
export const getWeixinRedirectURI = (appid, url) =>
	`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`

//支付宝获取code
export const getAlipayRedirectURI = (appid2, url2) =>
  `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${appid2}&scope=auth_base&redirect_uri=${encodeURIComponent(url2)}`


//获取链接的?参数
export const getUrlParam = (name) => {
	var reg = new RegExp(name + "=([^&]*)(&|$)");
	var r = window.location.href.match(reg);
	var strValue = "";
	if (r != null) {
		strValue = unescape(r[1]);
	}
	return strValue;
}


//将base64图片码转file
export const dataUrlToFile = (dataurl, filename) => {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}

//将canvas转换为image的src
export const convertCanvasToImage = (canvas) => {
	return canvas.toDataURL("image/png");;
}

//验证身份证
export const checkIdCard = (value) => {
	var identNumber = value;

	if (identNumber != null) {
		identNumber = (identNumber + "").toUpperCase();
	}

	if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(identNumber))) {
		return '身份证格式错误';
	}
	//身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。  
	if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(identNumber))) {
		return '身份证格式错误';
	}
	//校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
	//下面分别分析出生日期和校验位
	var len, re;
	len = identNumber.length;
	//判断18位身份证号码，现在在国家统一身份证为18位。
	if (len == 18) {
		re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
		var arrSplit = identNumber.match(re);


		//检查生日日期是否正确
		var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
		var bGoodDay;
		bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) &&
			(dtmBirth.getDate() == Number(arrSplit[4]));
		if (!bGoodDay) {
			return '身份证号码日期不匹配';
		} else {
			//检验18位身份证的校验码是否正确。
			//校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
			var valnum;
			var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
			var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
			var nTemp = 0,
				i;
			for (i = 0; i < 17; i++) {
				nTemp += identNumber.substr(i, 1) * arrInt[i];
			}
			valnum = arrCh[nTemp % 11];
			if (valnum != identNumber.substr(17, 1)) {
				return '身份证号码校验位不正确';
			}
			return true;
		}
	} else {
		return '身份证号码位数不足';
	}
}

// 字符串截取 包含对中文处理,str需截取字符串,start开始截取位置,n截取长度
export const substrMb = (str, start, n) => {
	if (str.replace(/[\u4e00-\u9fa5]/g, '**').length <= n) {
		return str;
	}
	let len = 0;
	let tmpStr = '';
	for (let i = start; i < str.length; i++) { // 遍历字符串
		if (/[\u4e00-\u9fa5]/.test(str[i])) { // 中文 长度为两字节
			len += 2;
		} else {
			len += 1;
		}
		if (len > n) {
			break;
		} else {
			tmpStr += str[i];
		}
	}
	return tmpStr;
}

//验证手机号
export const checkPhone = (value) => {
	if (!value) {
		return '手机号不能为空';
	} else {
		const reg = /^1[3-9]\d{9}$/
		var result = reg.test(value);

		if (result) {
			return true;
		} else {
			return '请输入正确的手机号';
		}
	}
};

//是否为微信浏览器
export const isWeiXin = () => {
	return /MicroMessenger/.test(window.navigator.userAgent)
}

//获取当前根链接
export const getBaseUrl = () => {
	return window.location.href.split("#")[0]
}

//获取指定日期是否在指定时间之间
export const inDateBetwen = (d, d1, d2) => {
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
	var dateEnd = new Date(d2.replace(/-/g, "/")); //将-转化为/，使用new Date
	//var dateBegin = new Date(d1);//将-转化为/，使用new Date
	//var dateEnd = new Date(d2);//将-转化为/，使用new Date
	var dateNow = new Date(d.replace(/-/g, "/")); //获取当前时间

	var beginDiff = dateNow.getTime() - dateBegin.getTime(); //时间差的毫秒数       
	var beginDayDiff = Math.floor(beginDiff / (24 * 3600 * 1000)); //计算出相差天数

	var endDiff = dateEnd.getTime() - dateNow.getTime(); //时间差的毫秒数
	var endDayDiff = Math.floor(endDiff / (24 * 3600 * 1000)); //计算出相差天数       
	if (endDayDiff < 0) {
		//已过期
		return false
	}
	if (beginDayDiff < 0) {
		//没到开始时间
		return false;
	}
	return true;
}

//type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
export const getWeekTime = (type, dates) => {
	var now = new Date();
	var nowTime = now.getTime();
	var day = now.getDay();
	var longTime = 24 * 60 * 60 * 1000;
	var n = longTime * 7 * (dates || 0);
	if (type == "s") {
		var dd = nowTime - (day) * longTime + n;
	};
	if (type == "e") {
		var dd = nowTime + (7 - day - 1) * longTime + n;
	};
	dd = new Date(dd);
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1;
	var d = dd.getDate();
	m = m < 10 ? "0" + m : m;
	d = d < 10 ? "0" + d : d;
	var day = y + "-" + m + "-" + d;
	return day;
}

export const getDiffDate = (stime, etime) => {
	//初始化日期列表，数组
	var diffdate = new Array();
	var i = 0;
	//开始日期小于等于结束日期,并循环
	while (stime <= etime) {
		diffdate[i] = stime;

		//获取开始日期时间戳
		var stime_ts = new Date(stime).getTime();
		//console.log('当前日期：' + stime + '当前时间戳：' + stime_ts);

		//增加一天时间戳后的日期
		var next_date = stime_ts + (24 * 60 * 60 * 1000);

		//拼接年月日，这里的月份会返回（0-11），所以要+1
		var next_dates_y = new Date(next_date).getFullYear() + '-';
		var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (
			new Date(next_date).getMonth() + 1) + '-';
		var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();

		stime = next_dates_y + next_dates_m + next_dates_d;

		//增加数组key
		i++;
	}
	return diffdate;
}

export const isJSON = (str) => {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == 'object' && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			console.log('error：' + str + '!!!' + e);
			return false;
		}
	}
}

//手机号隐藏中间4位
export const showTel = (tel) => {
	if(!tel){
		return '';
	}
	tel = '' + tel;
	return tel.substr(0, 3) + "****" + tel.substr(7);
}
