import { routerMode } from '@/config/env';

export function deepMerge(a, b) {
	let k;
	for (k in b) {
		a[k] =
			a[k] && a[k].toString() === '[object Object]' ? deepMerge(a[k], b[k]) : (a[k] = b[k]);
	}
	return a;
}

export function numberGap(value, options) {
	const { max = 10000000, min = 0 } = options || {};
	let [a, b] = value || [];

	if (a === undefined && b === undefined) {
		return [];
	} else {
		if (a != undefined && b == undefined) {
			value = [a, max];
		}

		if (a == undefined && b != undefined) {
			value = [min, b];
		}
	}

	return value;
}

export function orderBy(list, key) {
	return list.sort((a, b) => a[key] - b[key]);
}

export function deepTree(list) {
	let newList = [];
	let map = {};

	list.forEach(e => (map[e.id] = e));

	list.forEach(e => {
		let parent = map[e.parentId];

		if (parent) {
			(parent.children || (parent.children = [])).push(e);
		} else {
			if (!e.parentId) {
				newList.push(e);
			}
		}
	});

	const fn = list => {
		list.map(e => {
			if (e.children instanceof Array) {
				e.children = orderBy(e.children, 'orderNum');

				fn(e.children);
			}
		});
	};

	fn(newList);

	return orderBy(newList, 'orderNum');
}

export function firstMenu(list) {
	let path = '';

	const fn = arr => {
		arr.forEach(e => {
			if (e.type == 1) {
				if (!path) {
					path = e.path;
				}
			} else {
				fn(e.children);
			}
		});
	};

	fn(list);

	return path || '/404';
}

export const revisePath = path => {
	if (!path) {
		return '';
	}

	if (path[0] == '/') {
		return path;
	} else {
		return `/${path}`;
	}
};

export function getUrlParam(name) {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return decodeURIComponent(r[2]);
	return null;
}

export function href(path, newWindow) {
	let { search, origin } = window.location;

	let url = '';

	if (routerMode == 'history') {
		url = origin + path;
	} else {
		url = origin + search + '#' + path;
	}

	if (newWindow) {
		window.open(url);
	} else {
		window.location.href = url;
	}
}

export function contains(parent, node) {
	if (document.documentElement.contains) {
		return parent !== node && parent.contains(node);
	} else {
		while (node && (node = node.parentNode)) if (node === parent) return true;
		return false;
	}
}

export function isPc() {
	const userAgentInfo = navigator.userAgent;
	const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
	let flag = true;
	for (var v = 0; v < Agents.length; v++) {
		if (userAgentInfo.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
}
