import w_md5 from "./w_md5.js";
import store from "../store/index.js";

export const copyThis = (str) => {
	uni.setClipboardData({
		data: str, //要被复制的内容
		success: () => { //复制成功的回调函数
			uni.showToast({ //提示
				title: "复制成功"
			})
		}
	});
}

export const goPath = (path,type) => {
	uni.navigateTo({
		url:path,
		fail(e) {
			console.log(e)
		}
	})
}

export const md5 = (bStr,type = 2) => {
	type = parseInt(type)
	let str  = ''
	switch(type){
		case 0:
			str = w_md5.hex_md5_16(bStr)//16位小写
			break;
		case 1:
			str = w_md5.hex_md5_16Upper(bStr)//16位大写
			break;
		case 2:
			str = w_md5.hex_md5_32(bStr);//32位小写
			break;
		case 3:
			str = w_md5.hex_md5_32Upper(bStr);//32位大写
			break;
	}
	return str
}

export const getPwd = (str) => {
	if(str == ''){
		return ''
	}
	return md5('bmsc-'+str)
}

export const makeSign = (obj,serverTime) => {
	obj = JSON.parse(JSON.stringify(obj));
	let app_key = 'm58c97';
	let app_secret = 'e9c0a04382655dfgb3c98d11477ad547';
	// let serverTime = (store.getters['api/getServerTime'] == 0?(parseInt(Date.now() /1000)):store.getters['api/getServerTime'])
	obj.app_key = app_key
	obj.timestamp = serverTime
	let arr = Object.keys(obj)
	arr.sort()
	let o = {}
	arr.forEach((v,i) => {
		o[v] = obj[v]
	})
	let arr2 = Object.keys(o)
	let str = ''
	
	arr2.forEach((v,i) => {
		if(o[v] !== ''){
			if (typeof(o[v]) == 'object') {
				o[v] = JSON.stringify(o[v]);
			}
			str += v + '=' + o[v] + '&'
		}
	})
	if(str != ''){
		str = str.substr(0,str.length - 1)
	}
	let md = md5(str + app_secret)
	return md
}

// APP下执行
export const DeviceType = () => {
	let platform = uni.getSystemInfoSync().platform;
	if (platform == 'ios') {
		return 'ios'
	} else if (platform == 'android'){
		return 'android'
	}
}

// 地址 标题名 分页跳转类型
export const EasyPay = (url, title, pageType) => {
	// #ifdef APP-PLUS
	uni.navigateTo({
		url: `/pages/user/pay_webview/pay_webview?title=${title}&urlLink=${encodeURIComponent(url)}&pageType=${pageType}`
	})
	// #endif
	
	// #ifdef H5
	location.href = url; 
	// #endif
}

// 保存图片
export const saveImg = (img) => {
	let arr = [];
	arr.push(img);
	uni.previewImage({
		urls: arr ,    //预览图片的地址，必须要数组形式
		longPressActions: {
			itemList:['保存图片'],
			success: res=> {
				uni.downloadFile({
					url: img,
					success(data) {
						if (data.statusCode == 200) {
							uni.saveImageToPhotosAlbum({
								filePath:data.tempFilePath,
								success: function() {
									uni.showToast({
										title: '保存成功',
										icon: "success"
									})
								}
							})
						}
					}
				})
			}
		}
	})
}

// 数组去空
export const trimSpace = (array) => {
	var newArr = [];
	for (var i = 0; i < array.length; i++) {  
	    if(array[i] !== undefined && array[i] !== null && array[i] !== '') {
	        newArr.push(array[i]);
	    }  
    }  
	return newArr;
}

// 时间转换(时间格式（2021-07-02 12：12：12） 显示为几分钟前，几小时前等)
export const timeChange = (dateTimeStamp) => {
	var dateTimeStamp = Date.parse(dateTimeStamp.replace(/-/gi, "/"));
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	var diffValue = now - dateTimeStamp; //时间差
	if (diffValue < 0) {
		return '刚刚';
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	var result = "2";
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 4) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear(); {}
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}

//检测utf16emoji表情 转换为实体字符以供后台存储
export const utf16toEntities = (str) => {
	var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
	str = str.replace(patt, function(char) {
		var H, L, code;
		if (char.length === 2) { //辅助平面字符（我们需要做处理的一类）
			H = char.charCodeAt(0); // 取出高位
			L = char.charCodeAt(1); // 取出低位
			code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
			return "&#" + code + ";";
		} else {
			return char;
		}
	});
	return str;
}

// base64转二进制文件
export const base64ToBlob = (urlData, type) => {
	let arr = urlData.split(',');
	let mime = arr[0].match(/:(.*?);/)[1] || type;
	// 去掉url的头，并转化为byte
	let bytes = window.atob(arr[1]);
	// 处理异常,将ascii码小于0的转换为大于0
	let ab = new ArrayBuffer(bytes.length);
	// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
	let ia = new Uint8Array(ab);
	for (let i = 0; i < bytes.length; i++) {
	  ia[i] = bytes.charCodeAt(i);
	}
	return new Blob([ab], {
	  type: mime
	});
}

export const userLeave = (value) => {
	if (value == 2) {
		return '管理员'
	} else if (value == 1) {
		return '群主'
	} else if (value == 0) {
		return '普通群员'
	}
}

// 时间戳转日期
export const timestampToTime = (timestamp) => {
	// 时间戳为10位需*1000，时间戳为13位不需乘1000
	var date = new Date(timestamp * 1000);
	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());
	return Y + M + D + h + m + s;
}

export const isDateTimeBetween = (startDateTime, endDateTime, currentDateTime) => {
	const startDate = new Date(startDateTime);
	const endDate = new Date(endDateTime);
	const currentDate = new Date(currentDateTime);

	if (startDate <= endDate) {
		return currentDate >= startDate && currentDate <= endDate;
	} else {
		// 处理跨天的情况
		return currentDate >= startDate || currentDate <= endDate;
	}
}

export const areAllIdsEmpty = (arr) => {
	// 遍历数组中的每个对象  
	for (let i = 0; i < arr.length; i++) {  
		console.log(arr[i].ids)
		// 如果对象的ids属性不是空数组，则立即返回true  
		if (arr[i].ids && arr[i].ids.length > 0) {  
			return true; // 至少有一个ids不是空的，返回true  
		}  
	}
}


export const getArrMaxValue = (arr) => {
    if (!arr || arr.length === 0) {
		return '--'; // 值是0或空就不显示
    }
    var max = arr[0];
    for (var i = 1; i < arr.length; i++) {
		if (arr[i] > max) {
			max = arr[i];
		}
    }
    return max;
}


export default {
	copyThis,
	goPath,
	md5,
	makeSign,
	getPwd,
	DeviceType,
	EasyPay,
	saveImg,
	trimSpace,
	timeChange,
	utf16toEntities,
	userLeave,
	timestampToTime,
	isDateTimeBetween,
	areAllIdsEmpty,
	getArrMaxValue
}