import verify from "./verify.js"

//工具类
let util = {}

//预览图片
// this.$util.preview('http://....png')
// this.$util.preview('../../test.png')
// this.$util.preview(['http://....png', '../../test.png'])
util.preview = async (src) => {
		const urls = typeof src === 'string' ? [src] : src
		const filePath = async src => src.match(/^http/) ? src : (await uni.compressImage({
			src,
			quality: 100
		}))[1].tempFilePath
		for (let i = 0; i < urls.length; i++) {
			urls[i] = await filePath(urls[i])
		}
		uni.previewImage({
			urls
		})
	},

	//复制
	util.copy = content => {
		uni.setClipboardData({
			data: content
		});
	}


util.formatHtml = (str) => {
	return decodeURIComponent(str).replace(/<[^>]+>/g, "");
}


util.dealAccountNo = account => {
		if (account.startsWith('1')) {
			if (account.length >= 17) {
				account = account.substring(0, 4) + " **** **** " + account.substring(account.length - 4);
			}
		}
		if (account.startsWith('6')) {
			if (account.length >= 16) {
				account = account.substring(0, 4) + " **** **** " + account.substring(account.length - 4);
			}
		}
		return account
	},

	util.calculateDistance = (lat1, lng1, lat2, lng2) => {
		console.log(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) / 10; //单位米
		return s
	},


	util.showModal = (content, title = '提示') => {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: title,
				content: content,
				success: (res) => {
					resolve(res)
				}
			});
		})
	}

//拨打电话
util.callPhone = (phone) => {
	if (!verify.isLandline(phone) || !verify.isMobile(phone)) {
		uni.showToast({
			title:"联系方式不正确",
			icon:"none"
		})
		return
	}
	uni.showModal({
		title: '提示',
		content: `确定要拨打电话：${phone}吗?`,
		success: function(res) {
			if (res.confirm) {
				uni.makePhoneCall({
					phoneNumber: phone //仅为示例
				});
			}
		}
	});
}

//四舍五入保留2位小数（不够位数，则用0替补）
util.keepTwoDecimalFull = num => {
	var result = parseFloat(num)
	if (isNaN(result)) {
		return false
	}
	result = Math.round(num * 100) / 100
	var s_x = result.toString()
	var pos_decimal = s_x.indexOf('.')
	if (pos_decimal < 0) {
		pos_decimal = s_x.length
		s_x += '.'
	}
	while (s_x.length <= pos_decimal + 2) {
		s_x += '0'
	}
	return s_x
}

/**
 * 数组去重
 * @param {Array} arr 源数组
 * 
 * @return {Array} newArr 去重后的数组
 */
util.uniqueArray = (arr) => {
	return [...new Set(arr)]
}

/**
 * 获取url参数
 */
util.getUrlParams = (p) => {
	let url = decodeURIComponent(p);
	let param = {};
	// 把参数按&拆分成数组
	let index = url.indexOf("?");
	let query = url.substring(index + 1, index.length);
	var param_arr = query.split("&");
	for (var i = 0; i < param_arr.length; i++) {
		var pair = param_arr[i].split("=");
		param[pair[0]] = pair[1];
	}
	return param
}

/**
 * 对象键复制
 */
util.objectCopy = (target, source) => {
	Object.keys(target).forEach(key => {
		target[key] = source[key]
	})
}


util.objectKeyIsEmpty = (obj) => {
	let empty = false;
	for (const key in obj) {
		if (obj.hasOwnProperty(key)) {
			if (obj[key] === null || obj[key] === '') {
				empty = true;
			} else {
				empty = false;
				break;
			}
		}
	}
	return empty;
}



//获取某一个页面上下文 context
util.getPageCtx = (idx = 0) => {
	let pages = getCurrentPages()
	if (pages.length > 0) {
		return pages[pages.length - 1 - idx] || {}
	}
	return {}
}

//获取当前页面路由
util.getCurrentRoute = () => {
	let page = util.getPageCtx()
	if (page.route) {
		return page.route
	}
	return ''
}

//回到上一页刷新页面
util.isReloadAndBack = () => {
	let prePage = util.getPageCtx(1)
	prePage.setData({
		"reload": true
	})
	uni.navigateBack({
		delta: 1
	})
}
//onshow方法通过刷新mescroll数据
util.reload = (mescroll) => {
	let page = util.getPageCtx()
	if (page.data.reload) {
		mescroll.resetUpScroll();
		page.data.reload = false
	}
}

/**
 * vue中加载script
 */
util.loadScriptFunc = (url, callback) => {
	callback = typeof callback === 'function' ? callback : function() {};
	var head = document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	script.onreadystatechange = function() {
		if (this.readyState == "loaded" || this.readyState == "complete") {
			callback();
		}
	}
	script.onload = callback;
	head.appendChild(script);
}

util.loadScript = (src) => {
	var script = document.createElement('script');
	script.src = src;
	document.body.appendChild(script);
}


export default util
