/**
 * Created by rockyl on 2019-12-10.
 */

export let queryParams: any = {};

let search = window.location.search;
try {
	search = top.location.search;  //尝试获取顶层的链接
} catch (e) {
}

for (let item of search.replace('?', '').split('&')) {
	let arr = item.split('=');
	queryParams[arr[0]] = arr.length === 1 ? true : decodeURIComponent(arr[1]);
}

/**
 * 添加一个script
 * @param script
 * @param parent
 */
export function appendScript(script, parent = document.body) {
	if (!script) {
		return;
	}

	if (script.indexOf('<script') === 0) {
		let temp = document.createElement('div');
		temp.innerHTML = script;

		for (let i = 0, li = temp.children.length; i < li; i++) {
			const child: any = temp.children[i];

			if (child.src) {
				parent.appendChild(child);
				i--;
				li--;
			} else {
				_appendScript(child.innerHTML, parent);
			}
		}
	} else {
		_appendScript(script, parent);
	}
}

function _appendScript(scriptContent, parent) {
	let scriptEl = document.createElement('script');
	scriptEl.innerHTML = scriptContent;
	parent.appendChild(scriptEl);
}

export function windowVisibility(callback?: (visible: boolean) => void) {
//设置隐藏属性和改变可见属性的事件的名称
	let visibilityChange;
	if (typeof document.hidden !== 'undefined') {
		visibilityChange = 'visibilitychange';
	} else if (typeof document['msHidden'] !== 'undefined') {
		visibilityChange = 'msvisibilitychange';
	} else if (typeof document['webkitHidden'] !== 'undefined') {
		visibilityChange = 'webkitvisibilitychange';
	}

	const handleVisibilityChange = (e) => {
		callback && callback(document.visibilityState == "visible");
	};

	document.addEventListener(
		visibilityChange,
		handleVisibilityChange,
		false
	);
}
