function toArray(data) {
	if (!data) return []
	if (data instanceof Array){
		return data
	} else {
		return [data]
	}
}

function generateUUID() {
  return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function generateRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function generateLightRandomColor() {
  const min = 150; 
  const range = 105;
  const r = Math.floor(Math.random() * range + min);
  const g = Math.floor(Math.random() * range + min);
  const b = Math.floor(Math.random() * range + min);
  const color = 'rgb(' + r + ',' + g + ',' + b + ')';
  return color;
}

function verificationAll(data, msg){
	
	if (!msg){
		console.log(msg);
		return false
	}
	
	if (!data){
		uni.showToast({
			title: '表单数据未填写',
			icon: "none"
		})
	}
	
	for (let key in msg) {
	    if (!data[key]) {
			uni.showToast({
				title: msg[key],
				icon: "none"
			})
			return true
	    }
	}
	return false
}

//验证手机号是否合法
function verificationPhone(phone){
	if(!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)){
		return false
	}
	return true
}

//获取url中参数的方法
export function getHrefParams(name) {
	var url = window.location.href;
	try {
		var cs = url.split('?')[1]; //获取?之后的参数字符串
		var cs_arr = cs.split('&'); //参数字符串分割为数组
		for (var i = 0; i < cs_arr.length; i++) { //遍历数组，拿到json对象
			if (cs_arr[i].split('=')[0] == name) {
				return cs_arr[i].split('=')[1];
			}
		}
		return "";
	} catch {
		return "";
	}
}


// 将字符串中的文本格式化html
export function stringFormatHtml(str){
	return str && str.replace(/\n/gi, '<br>')
	.replace(/ /gi, ' ')
}



//深度对比合并两个对象，相同属性b会覆盖a
export function deepMergeObject(a, b){
	let data = JSON.parse(JSON.stringify(a))
	function mergeObject(obj1, obj2){
		for(let key in obj2){
			if(typeof obj1[key] == 'object'){
				obj1[key] = mergeObject(obj1[key], obj2[key])
			}else{
				obj1[key] = obj2[key]
			}
		}
		return obj1
	}
	return mergeObject(data, b)
}

//复制内容
export function copyText(content) {
	uni.setClipboardData({
		data: content,
		success: () => {
			uni.showToast({
				title: '复制成功',
				icon: 'none'
			})
		}
	})
}

function params(url){
	if(typeof url == 'object'){
		return url
	}
	
	let data = {
		url
	}
	
	if(!data.url.includes('/pages')){
		data.url = '/pages' + data.url
	}
	
	return data
}


export function navigateTo(...args){
	uni.navigateTo(params(...args))
}

export function navigateBack(num = -1){
	uni.navigateBack(num)
}

export function redirectTo(...args){
	uni.redirectTo(params(...args))
}

export default {
	toArray,
	generateUUID,
	verificationAll,
	generateRandomColor,
	generateLightRandomColor,
	verificationPhone,
	getHrefParams,
	deepMergeObject,
	navigateTo,
	navigateBack,
	redirectTo,
	copyText,
	stringFormatHtml
}