/**
 * Created by rockyl on 2020/9/21.
 */
import {httpRequest} from "./net";
import {appID, projectID} from "./init";

export function cleanNewUser() {
	if(!localStorage) return;
	let key = 'nu_' + appID + '_' + projectID;
	localStorage.removeItem(key);
}

export function accessLog(pageBizId, params?) {
	let p = {
		pageBizId,
	};
	injectProp(p, params);
	return httpRequest('buriedPoint', 'get', p);
}

/**
 * 属性注入方法
 * @param target 目标对象
 * @param data 被注入对象
 * @param callback 自定义注入方法
 * @param ignoreMethod 是否忽略方法
 * @param ignoreNull 是否忽略Null字段
 *
 * @return 是否有字段注入
 */
export function injectProp(target: any, data?: any, callback?: Function, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean {
	if(!target || !data) {
		return false;
	}

	let result = false;
	for(let key in data) {
		let value: any = data[key];
		if((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) {
			if(callback) {
				callback(target, key, value);
			} else {
				try {
					target[key] = value;
				} catch(e) {

				}
			}

			result = true;
		}
	}
	return result;
}

/**
 * 数组查找
 * @param arr
 * @param predicate
 */
export function arrayFind(arr, predicate) {
	if(!arr) {
		return;
	}
	for(let i = 0, li = arr.length; i < li; i++) {
		const item = arr[i];

		if(predicate(item, i, arr)) {
			return item;
		}
	}
}

/**
 * 对象转query字符串
 * @param obj
 */
export function obj2query(obj: any): string {
	if(!obj) {
		return '';
	}
	const arr: string[] = [];
	for(const key in obj) {
		arr.push(key + (key ? '=' : '') + obj[key]);
	}
	return arr.join('&');
}
