// 获取当前page
export function getCurrentPage() {
	const pages = getCurrentPages() // 获取加载的页面
	const currentPage = pages[pages.length - 1] // 获取当前页面的对象
	return currentPage
}

export function getLastPage() {
	const pages = getCurrentPages() // 获取加载的页面
	const lastPage = pages[pages.length - 2] // 获取当前页面的对象
	return lastPage
}

// 获取当前页面Url
export function getCurrentPageUrl() {
	const currentPage = getCurrentPage()
	const url = currentPage.route
	return url
}

// 获取当前页面Url带参数
export function getCurrentPageUrlWithArgs() {
	const currentPage = getCurrentPage()
	let url = currentPage.route
	let options = currentPage.options
	// 拼接url的参数
	let urlWithArgs = url + '?'
	for (let key in options) {
		let value = options[key]
		if (value) {
			urlWithArgs += key + '=' + value + '&'
		}
	}
	if (urlWithArgs.indexOf('&') !== -1) {
		urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
	}
	return urlWithArgs
}

// 解析url
export function parseQuery() {
	const currentPage = getCurrentPage()
	const res = {
		path: currentPage.route,
		query: currentPage.options
	}
	return res
}

// url参数处理
export function handleUrlParam(path) {
	let req = new Object()
	if (path.includes('?')) {
		let url = path.split('?')[1] // 获取url中"?"符后的字串
		let strs = url.split('&')
		for (let i = 0; i < strs.length; i++) {
			req[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
		}
	}
	return req
}

// 处理二维码链接
export function handleQrCode() {
	let param = parseQuery()['q']
	if (!param) {
		return ''
	}

	if (param.indexOf('%3F') != -1) {
		param = param
			.split('%3F')[1] // ?
			.replace(/%3D/g, ':') // =
			.replace(/%26/g, ',') // &
			.split(',')
			.map((item, index) => {
				item = item.split(':')
				return `"${item[0]}":"${item[1]}"`
			})
			.join(',')
		param = JSON.parse('{' + param + '}')
		return param
	} else {
		return handleUrlParam(param)
	}
}

// 复制剪贴板
export const copyClipboard = data => {
	if (!data) {
		return
	}
	// 只能复制字符串，数值不生效
	data = data + ''
	uni.setClipboardData({
		data: data,
		success: res => {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
				duration: 2000,
			})
		},
	})
}

// 克隆对象
export function clone(obj) {
	return JSON.parse(JSON.stringify(obj));
}

// 处理数据库存储null
export function fixNullVal(val) {
	val = fixZeroVal(val)
	val = !val || val === 'null' ? '' : val
	return val
}

// 处理数据库无法存储 数值：0
export function fixZeroVal(val) {
	val = val === '0' || val === 0 ? '0' : val
	return val
}
