// import { random, omit } from 'lodash';
// import moment from 'moment';
// import { color } from 'html2canvas/dist/types/css/types/color';  //wyw 这个会影响


export function timeFix() {
	const time = new Date()
	const hour = time.getHours()
	return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(Y)、月(m)、日(d)、小时(H)、分(M)、秒(S) 可以用 1-2 个占位符，
 * 例子：
 * dateFormat('YYYY-mm-dd HH:MM:SS', new Date()) ==> 2020-01-01 08:00:00
 */
export const dateFormat = (fmt, date) => {
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	let ret
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt)
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt
}

export function handleScrollHeader(callback) {
	let timer = 0

	let beforeScrollTop = window.pageYOffset
	callback = callback || function() {}
	window.addEventListener(
		'scroll',
		event => {
			clearTimeout(timer)
			timer = setTimeout(() => {
				let direction = 'up'
				const afterScrollTop = window.pageYOffset
				const delta = afterScrollTop - beforeScrollTop
				if (delta === 0) {
					return false
				}
				direction = delta > 0 ? 'down' : 'up'
				callback(direction)
				beforeScrollTop = afterScrollTop
			}, 50)
		},
		false
	)
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
	if (id === '') {
		return
	}
	setTimeout(() => {
		document.body.removeChild(document.getElementById(id))
	}, timeout)
}

// 节流
// 思路： 第一次先设定一个变量true，
// 第二次执行这个函数时，会判断变量是否true，
// 是则返回。当第一次的定时器执行完函数最后会设定变量为flase。
// 那么下次判断变量时则为flase，函数会依次运行。
export function throttle(fn, delay = 100) {
	// 首先设定一个变量，在没有执行我们的定时器时为null
	var timer = null
	return function() {
		// 当我们发现这个定时器存在时，则表示定时器已经在运行中，需要返回
		if (timer) return
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}

// 防抖
// 首次运行时把定时器赋值给一个变量， 第二次执行时，
// 如果间隔没超过定时器设定的时间则会清除掉定时器，
// 重新设定定时器， 依次反复， 当我们停止下来时，
// 没有执行清除定时器， 超过一定时间后触发回调函数。
export function debounce(fun, delay) {
	return function(args) {
		// 获取函数的作用域和变量
		const that = this
		const _args = args
		// 每次事件被触发，都会清除当前的timeer，然后重写设置超时调用
		clearTimeout(fun.id)
		fun.id = setTimeout(function() {
			fun.call(that, _args)
		}, delay)
	}
}

/**
 * 判断是否为空对象
 * @param {*} object 源对象
 */
export function isEmptyObject(object) {
	return Object.keys(object).length === 0
}

/**
 * 判断是否为对象
 * @param {*} object
 */
export function isObject(object) {
	return Object.prototype.toString.call(object) === '[object Object]'
}

/**
 * 判断是否为对象
 * @param {*} array
 */
export function isArray(array) {
	return Object.prototype.toString.call(array) === '[object Array]'
}

/**
 * 判断是否为空
 * @param {*} object 源对象
 */
export function isEmpty(value) {
	if (isArray(value)) {
		return value.length === 0
	}
	if (isObject(value)) {
		return isEmptyObject(value)
	}
	return !value
}

/**
 * 判断是否在数组中
 * @param {*} search
 * @param {*} array
 */
export function inArray(search, array) {
	return array.includes(search)
}

/**
 * 获取指定天数的日期
 * @param day
 * @returns {string}
 */
export function getDateByDay(day) {
	var today = new Date()
	var targetdaySeconds = today.getTime() + 1000 * 60 * 60 * 24 * day
	today.setTime(targetdaySeconds) // 注意，这行是关键代码
	return today.getFullYear() + '-' + zeroFillLeft(today.getMonth() + 1) + '-' + zeroFillLeft(today.getDate())
}

/**
 * 左侧补0
 * @param value
 * @returns {*}
 */
export function zeroFillLeft(value) {
	return (value.toString().length === 1) ? ('0' + value) : value
}

/**
 * 批量给指定对象赋值
 * @param obj obj 指定的对象,一般为vue实例
 * @param obj assignment 赋值的元素 { a: '123' }
 */
export function assignment(obj, assignment) {
	Object.keys(assignment).forEach(key => {
		obj[key] = assignment[key]
	})
}

/**
 * 对象转URL
 * @param {object} obj
 */
export const urlEncode = (obj = {}) => {
	const result = []
	for (const key in obj) {
		const item = obj[key]
		if (!item) {
			continue
		}
		if (isArray(item)) {
			item.forEach(val => {
				result.push(key + '=' + val)
			})
		} else {
			result.push(key + '=' + item)
		}
	}
	return result.join('&')
}

export const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * 生成url (带参数)
 * @param {string} path 链接
 * @param {object} params query参数
 */
export function buildUrL(path, params) {
	const queryStr = urlEncode(params)
	if (!isEmpty(queryStr)) {
		return path + '?' + queryStr
	}
	return path
}

const RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';

// export function uuid(placeholder) {
//   return RFC4122_TEMPLATE.replace(/[xy]/g, function () {
//     let value = random(15)
//     value = placeholder === 'x' ? value : (value & 0x3 | 0x8)
//     return value.toString(16)
//   })
// }

export function Base64_Encode(str) { // base64转换
	let c1, c2, c3;
	let base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	let i = 0;
	let len = str.length;
	let string = '';

	while (i < len) {
		c1 = str.charCodeAt(i++) & 0xff;
		if (i === len) {
			string += base64EncodeChars.charAt(c1 >> 2);
			string += base64EncodeChars.charAt((c1 & 0x3) << 4);
			string += "==";
			break;
		}
		c2 = str.charCodeAt(i++);
		if (i === len) {
			string += base64EncodeChars.charAt(c1 >> 2);
			string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
			string += base64EncodeChars.charAt((c2 & 0xF) << 2);
			string += "=";
			break;
		}
		c3 = str.charCodeAt(i++);
		string += base64EncodeChars.charAt(c1 >> 2);
		string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
		string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
		string += base64EncodeChars.charAt(c3 & 0x3F);
	}
	return string;
}

export function guid() {
	function S4() {
		return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
	}
	return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
}

export function extend(obj1, obj2) {
	if (typeof(obj2) === 'object')
		for (let p in obj2) obj1[p] = obj2[p];
}

export function extendRule(obj, filed, op, value, isSysParam) { //查询条件
	let data = {};
	if (value === null) {
		value = '';
	}
	data['Field'] = filed;
	data['Operate'] = op;
	data['Value'] = isSysParam ? value.toString() : value;
	if (isSysParam) {
		data["IsSysParamRule"] = true;
	}

	if (!obj.FilterGroup) {
		obj.FilterGroup = {};
	}
	if (!obj.FilterGroup.Rules) {
		obj.FilterGroup.Rules = [];
	}
	obj.FilterGroup.Rules.push(data);
}

export function initFilterGroup(IsAnd = true) {
	return {
		IsAnd,
		Rules: [],
		Groups: [],
	}
}

export function extendFilterGroup(obj, obj2) {

	if (!obj.FilterGroup) {
		obj.FilterGroup = {};
	}
	if (!obj.FilterGroup.Groups) {
		obj.FilterGroup.Groups = [];
	}
	obj.FilterGroup.Groups.push(obj2);
}

export function extendChildGroup(obj, obj2) {
	if (!obj.Groups) {
		obj.Groups = [];
	}
	obj.Groups.push(obj2);
}

export function extendGroupRule(obj, filed, op, value, isSysParam) { //查询条件
	let data = {};
	if (value === null) {
		value = '';
	}
	data['Field'] = filed;
	data['Operate'] = op;
	data['Value'] = isSysParam ? value.toString() : value;
	if (isSysParam) {
		data["IsSysParamRule"] = true;
	}

	if (!obj.Rules) {
		obj.Rules = [];
	}
	obj.Rules.push(data);

}

export function initQueryFilter(OrgId, PageIndex, Limit, Sort, Order) {
	return {
		OrgId,
		PageIndex,
		Limit,
		Start: (PageIndex - 1) * Limit,
		Sort,
		Order: (Order === '' ? 0 : Order),
		RuleCount: 0,
		IncludeCount: 0,
		OrderCount: 0,
		FilterGroupCount: 0,
		Include: [],
		Orders: [],
		FilterGroup: {
			Rules: [],
			Groups: []
		}
	};
}

export function initFilter(OrgId, Keyword = "", Sort, Order, PageIndex = 1, Parameter1, Parameter2, Parameter3,
	Parameter4, Parameter5, Parameter6) {
	return {
		Keyword,
		Parameter1,
		Parameter2,
		Parameter3,
		Parameter4,
		Parameter5,
		Parameter6,
		OrgId,
		PageIndex,
		Limit: 10,
		Start: (PageIndex - 1) * 10,
		Sort,
		Order: (Order === '' ? 0 : Order),
		RuleCount: 0,
		IncludeCount: 0,
		OrderCount: 0,
		FilterGroupCount: 0,
		Include: [],
		Orders: [],
		FilterGroup: {
			Rules: [],
			Groups: []
		},
		SelectField: [],
		DataRule: [],
		IgnoreDataRule: false
	};
	// let params = $("#search-form").elFilterParam();
	// extend(json, params);
}

export function extendInclude(obj, clude) {

	if (!obj.Include) {
		obj.Include = [];
	}
	obj.Include.push(clude);
}

//wyw 添加 子表过滤条件
export function extendFilterGroupGroupRules(obj, filed, op, value, isSysParam) { //查询条件
	let data = {};
	if (value === null) {
		value = '';
	}
	data['Field'] = filed;
	data['Operate'] = op;
	data['Value'] = isSysParam ? value.toString() : value;
	if (isSysParam) {
		data["IsSysParamRule"] = true;
	}
	if (!obj.FilterGroup) {
		obj.FilterGroup = {};
	}
	if (!obj.FilterGroup.Groups) {
		obj.FilterGroup.Groups = [];
	}

	if (obj.FilterGroup.Groups.length == 0) {
		let groupGroup = initFilterGroup(false)
		obj.FilterGroup.Groups.push(groupGroup)
	}

	if (!obj.FilterGroup.Groups[0].Rules) {
		obj.FilterGroup.Groups[0].Groups = [];
		obj.FilterGroup.Groups[0].Rules = [];
		obj.FilterGroup.Groups[0].IsAnd = false;
	}
	obj.FilterGroup.Groups[0].Rules.push(data);
}

export function extendOrder(obj, filed, order) {
	var data = {};
	data["Field"] = filed;
	data["Order"] = order;
	if (!obj.Orders) {
		obj.Orders = [];
	}
	obj.Orders.push(data);
}
export function extendIgnoreDataRule(obj) {
	obj.IgnoreDataRule = true
}

function trim(str) { // ?
	for (var i = 0; i < str.length && str.charAt(i) == "  "; i++)
	;
	for (var j = str.length; j > 0 && str.charAt(j - 1) == "  "; j--)
	;
	if (i > j)
		return "";
	return str.substring(i, j);
}

export function empty(v, allowZero) {
	if (v === "null" || v === undefined || v === "") return true;
	switch (typeof v) {
		case 'undefined':
			return true;
		case 'string':
			if (trim(v).length == 0)
				return true;
			break;
		case 'boolean':
			if (!v)
				return true;
			break;
		case 'number':
			if (0 === v && !allowZero)
				return true;
			break;
		case 'object':
			if (null === v)
				return true;
			if (undefined !== v.length && v.length == 0)
				return true;
			for (var k in v) {
				return false;
			}
			return true;
		default:
			return false;
	}
}

export function strConvert(target, def) { // 点字符串转对象
	// str为需要转换的值, def为有固定的最后一个属性值
	let splitFiles = target.split('.');
	let str = '';
	let len = splitFiles.length;
	splitFiles.forEach(item => {
		str += '{\"' + item + '\":'
	});
	str += "" + def + ""
	for (let j = 0; j < len; j++) {
		str += '}'
	}
	let mat = JSON.parse(str);
	return mat
}

//仅仅获取对象的基础属性，不包含属性中的对象
export function getOnlyPropertyData(data, isGetSysParam) {
	let result = {};
	Object.keys(data).forEach((n) => {
		if (n.indexOf('.') !== -1) return;
		if (isGetSysParam && n === 'Nav_SysParams') {
			result[n] = data[n];
		} else if (Array.isArray(data[n])) {
			result[n] = data[n];
		} else if (typeof(data[n]) !== "object") {
			result[n] = data[n];
		}
	});
	return result;
}

//仅仅获取对象的基础属性及列表，不包含属性中的对象
export function getPropertyData(data, isSetDelete) {
	let result = {};
	Object.keys(data).forEach((n) => {
		if (n.indexOf('.') != -1) return;
		if (typeof(data[n]) !== "object") {
			result[n] = data[n];
		} else if (data[n] && data[n].length) {
			const array = [];
			data[n].forEach(nx => {
				const d = getPropertyData(nx, isSetDelete);
				array.push(d);
			});
			result[n] = array;
		}
		if (isSetDelete) {
			result['IS_DELETED'] = true;
		}
	});
	return result;
}

// 取导航属性的最后一个字段
export function dataIndexName(field) {
	const valueValid = field ? field.split('.') : [];
	return valueValid[valueValid.length - 1]
}

export function splitEnum(str) {
	let newArr = [];
	let oArr = str ? str.split(',') : [];
	oArr.forEach(item => {
		let n = item.split(':');
		newArr.push({
			label: n[0],
			value: n[1]
		})
	});
	return newArr
}

export function getDataFieldValueByCol(data, field, defaultValue) {
	if (!data || !field) return null;
	let opIndex = field.lastIndexOf('/');
	let op = 0;
	if (opIndex === -1) {
		opIndex = field.indexOf('*');
		if (opIndex === -1) {
			opIndex = field.indexOf('+');
			if (opIndex === -1) {
				opIndex = field.lastIndexOf('-');
				if (opIndex !== -1) {
					op = 2;
				}
			} else {
				op = 1;
			}
		} else {
			op = 3;
		}
	} else {
		op = 4;
	}

	let controlValue = null;
	if (opIndex !== -1) {
		const leftField = field.substring(0, opIndex);
		const rightField = field.substring(opIndex + 1);
		const leftText = getDataFieldValueByCol(data, leftField);
		const rigthText = getDataFieldValueByCol(data, rightField);
		if (leftText !== '' && rigthText !== '' && !isNaN(leftText) && !isNaN(rigthText)) {
			if (op === 1) {
				controlValue = (+leftText) + (+rigthText);
			} else if (op === 2) {
				controlValue = (+leftText) - (+rigthText);
			} else if (op === 3) {
				controlValue = (+leftText) * (+rigthText);
			} else if (op === 3 && (+rigthText) !== 0) {
				controlValue = (+leftText) / (+rigthText);
			}
		}
	} else {
		controlValue = getDataFieldValue(data, field, defaultValue);
	}
	return controlValue;
}

function innerGetDataFieldValue(data, field, defaultValue) {
	if (!data || !field) return null;
	const valueValid = field ? field.split('.') : [];
	let controlValue = null;
	let tmp = {
		...data
	};
	if (tmp) {
		for (let j = 0; j < valueValid.length; j++) {
			if (j < valueValid.length - 1) {
				if (!Array.isArray(tmp)) {
					if (tmp && tmp.hasOwnProperty(valueValid[j])) {
						tmp = tmp[valueValid[j]];
					} else {
						tmp = null;
					}
				} else {
					let arrayTmp = [];
					tmp.forEach(item => {
						if (item && item.hasOwnProperty(valueValid[j])) {
							arrayTmp.push(item[valueValid[j]]);
						}
					})
					tmp = arrayTmp;
				}
			} else {
				if (!Array.isArray(tmp)) {
					if (tmp && tmp.hasOwnProperty(valueValid[j])) {
						controlValue = tmp[valueValid[j]];
					}
				} else {
					controlValue = '';
					tmp.forEach(item => {
						controlValue += item[valueValid[j]] + ",";
					})
					if (controlValue && controlValue.indexOf(',') > 0) {
						controlValue = controlValue.substring(0, controlValue.length - 1);
					}
				}
			}
		}
	}
	if (controlValue == null && defaultValue !== undefined) {
		return defaultValue;
	}
	return controlValue;
}

export function getDataFieldValue(data, field, defaultValue) {
	if (!data || !field) {
		if (defaultValue !== undefined) {
			return defaultValue;
		}
		return null;
	}
	const key = 'Nav_SysParams';
	const index = field.indexOf(key);
	if (index === -1) {
		return innerGetDataFieldValue(data, field, defaultValue);
	} else {
		const f1 = index > 0 ? field.substring(0, index - 1) : null;
		const f2 = field.substring(index + key.length + 1);
		let temp = null;
		if (f1) {
			temp = innerGetDataFieldValue(data, f1);
		} else {
			temp = data;
		}
		if (temp) {
			let sysParams = temp[key];
			if (sysParams) {
				let paramRecord = sysParams.filter(t => t.CODE === f2)[0];
				if (paramRecord) {
					return paramRecord.VALUE;
				}
			}
		}
	}
	if (defaultValue !== undefined) {
		return defaultValue;
	}
	return null;
}

function innerSetDataFieldValue(data, field, value) {
	let tmp = data;
	const valueValid = field ? field.split('.') : [];
	for (let j = 0; j < valueValid.length; j++) {
		if (j < valueValid.length - 1) {
			if (!tmp.hasOwnProperty(valueValid[j]) || !tmp[valueValid[j]]) {
				tmp[valueValid[j]] = {};
			}
			let tmpData = tmp[valueValid[j]];
			if (!tmpData) {
				tmpData = {};
			}
			tmp = tmpData;
		} else {
			tmp[valueValid[j]] = value;
		}
	}
	return data;
}

export function setDataFieldValue(data, field, value) {
	if (!data || !field) return data;
	const key = 'Nav_SysParams';
	const index = field.indexOf(key);
	if (index === -1) {
		innerSetDataFieldValue(data, field, value);
	} else {
		const f1 = index > 0 ? field.substring(0, index - 1) : null;
		const f2 = field.substring(index + key.length + 1);
		let temp = null;
		if (f1) {
			temp = innerGetDataFieldValue(data, f1);
			if (!temp) {
				temp = {};
				innerSetDataFieldValue(data, f1, temp);
			}
		} else {
			temp = data;
		}
		let sysParams = temp[key];
		if (!sysParams) {
			sysParams = [];
			temp[key] = sysParams;
		}
		let paramRecord = sysParams.filter(t => t.CODE === f2)[0];
		if (!paramRecord) {
			paramRecord = {
				ID: guid(),
				CODE: f2,
				ENTITY_ID: temp.ID,
			}
			sysParams.push(paramRecord);
		}
		paramRecord.VALUE = value;
	}
	return data;
}

export function permissionUtils(login) {
	const checkPermission = (formId, keyId, type) => {
		if (login.userType == 99 || !formId) return true; //管理员
		let hasPermission = false;
		const currActivatedMenu = login.currActivatedMenu || {}
		if (login.rolePerm && login.rolePerm.Nav_RolePermForms && login.rolePerm.Nav_RolePermForms
			.length) { //只要一个角色有权限就有权限
			/**
			 * hasPermssion 判断为 true 之后，必须直接赋值为 true，
			 * 不能用条件判断（比如：hasPermission = matchForm;）去赋值
			 * 因为一直在循环，满足 if 条件后，可能 hasPermission 又被置为 false 了
			 */
			login.rolePerm.Nav_RolePermForms.forEach((n1, i1) => {
				if (!currActivatedMenu.ID) {
					hasPermission = true
				} else {
					if (n1.PermFormId === formId) {
						const matchForm = (n1.MenuId === currActivatedMenu.ID || !currActivatedMenu.ID)
						if (type == 0 && matchForm) { //表单权限
							hasPermission = true;
						} else if (type == 1) { //按钮权限
							if (n1.Nav_Btns && n1.Nav_Btns.length) {
								n1.Nav_Btns.forEach((n2, i2) => {
									const matchBtn = (n2.MenuId === currActivatedMenu.ID || !
										currActivatedMenu.ID)
									if (n2.BtnId === keyId && matchBtn) {
										hasPermission = true;
									}
								});
							}
						} else if (type == 2) { //行权限
							if (n1.Nav_Columns && n1.Nav_Columns.length) {
								n1.Nav_Columns.forEach((n2, i2) => {
									const matchRow = (n2.MenuId === currActivatedMenu.ID || !
										currActivatedMenu.ID)
									if (n2.ColumnId === keyId && matchRow) {
										hasPermission = true;
									}
								});
							}
						}
					}
				}


			});
		}
		return hasPermission;
	};
	return {
		checkBtn: (formId, btnId) => {
			return checkPermission(formId, btnId, 1);
		},
		checkColumn: (formId, columnId) => {
			return checkPermission(formId, columnId, 2);
		},
		checkForm: (formId) => {
			return checkPermission(formId, '', 0);
		},
	};
}

//根据枚举字符串获取枚举列表
export function getEnums(str) {
	let newArr = {};
	let oArr = str ? str.split(',') : [];
	oArr.forEach(item => {
		let n = item.split(':');
		newArr[[n[1]]] = n[0];
	});
	return newArr
}

export function getCustomParams(customParamsStr) {
	const customParams = {};
	if (customParamsStr && typeof customParamsStr === 'string') {
		let arrays = customParamsStr.split('|');
		arrays.forEach(function(n, i) {
			let paris = n.split("=");
			if (paris.length >= 2) {
				customParams[paris[0]] = paris[1];
			} else {
				customParams[paris[0]] = null;
			}
		});
	}
	return customParams;
}

export function getGroupByQueryFields(fields, groups, parentId, parent, list) {
	if (groups && groups.length) {
		const tempGroups = groups.filter(t => t.PARENT_ID === parentId);
		if (tempGroups && tempGroups.length) {
			tempGroups.forEach(t => {
				const group = {
					rules: [],
					childGroups: [],
					isAnd: t.RELATION_TYPE !== 1,
				};
				if (fields && fields.length) {
					const tempFields = fields.filter(t1 => t1.USER_C_C_QUERY_GROUP_ID === t.ID);
					if (tempFields && tempFields.length) {
						group.rules = getRulesByQueryFields(tempFields, group.childGroups);
					}
				}
				if (parent) {
					parent.childGroups.push(group)
				} else {
					list.push(group);
				}
				getGroupByQueryFields(fields, groups, t.ID, group, list);
			});
		}
	}
}

export function getRuleAndGroupsByQueryFields(queryFields, queryGroups) {
	const result = {};
	if (queryFields != null && queryFields.length) {
		const sysFields = queryFields.filter(t => !t.USER_C_C_QUERY_GROUP_ID);
		result.groups = [];
		result.rules = getRulesByQueryFields(sysFields, result.groups);
		getGroupByQueryFields(queryFields, queryGroups, null, null, result.groups);
	}
	return result;
}

export function locationQuery(query) {
	if (!query) return {};
	let querys = query.split('?')[1];
	let pair = querys.split('&');
	let obj = {};
	for (let i = 0; i < pair.length; i++) {
		let propertys = pair[i].split('=');
		obj[propertys[0]] = propertys[1]
	}
	return obj;
}

export function addChildGroups(list, group) {
	if (list && list.length) {
		list.forEach(t => {
			const tempGroup = initFilterGroup(t.isAnd);
			if (t.rules && t.rules.length) {
				t.rules.forEach(t1 => {
					extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam);
				});
			}
			if (t.childGroups && t.childGroups.length) {
				addChildGroups(t.childGroups, tempGroup);
			}
			extendChildGroup(group, tempGroup);
		});
	}
}

// export function getRandomCode(len) {
//   len = len || 32;
//   var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678=-*&@#$%!~+,./?\;:|'    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
//   var maxPos = $chars.length;
//   var pwd = '';
//   for (var i = 0; i < len; i++) {
//     pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
//   }
//   return pwd;
// }

export function addRuleAndGroups(json, ruleAndGroupJson) {
	if (json && ruleAndGroupJson) {
		if (ruleAndGroupJson.rules && ruleAndGroupJson.rules.length) {
			ruleAndGroupJson.rules.forEach(t => {
				if (t.isCustom) { //自定义字段

					if (t.field.indexOf(',') > -1) //modify by陈昌雨 2020/6/4
					{
						var splitFileds = t.field.split(',');
						let values = null;
						if (typeof(t.value) === 'number' && t.value !== undefined && t.value != null) {
							values = t.value.toString().split(',');
						} else {
							values = t.value.split(',');
						}

						if (splitFileds && values) {
							splitFileds.forEach((n, i) => {
								json[n] = values[i];
							});
						}
					} else {
						json[t.field] = t.value;
					}


				} else {
					extendRule(json, t.field, t.operator, t.value, t.isSysParam);
				}
			});
		}

		if (ruleAndGroupJson.groups && ruleAndGroupJson.groups.length) {
			ruleAndGroupJson.groups.forEach(t => {
				const tempGroup = initFilterGroup(t.isAnd);
				if (t.rules && t.rules.length) {
					t.rules.forEach(t1 => {
						extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam);
					});
				}
				if (t.childGroups && t.childGroups.length) {
					addChildGroups(t.childGroups, tempGroup);
				}
				extendFilterGroup(json, tempGroup);
			});
		}
		if (ruleAndGroupJson.orgType) {
			json.OrgType = ruleAndGroupJson.orgType;
		}
		if (ruleAndGroupJson.menuParameter) {
			json.MenuParameter = ruleAndGroupJson.menuParameter
		}
	}
}

export function constructStandardTreeData(data, cascader) {
	data.forEach(item => {
		const {
			Node,
			Children
		} = item
		const {
			NAME,
			ID
		} = Node
		if (cascader) {
			item.label = NAME
			item.value = ID
			Array.isArray(Children) && Children.length && (item.children = Children)
			for (let key in Node) {
				item[key] = Node[key]
			}
		} else {
			item.title = NAME
			item.key = ID
			item.value = ID
			item.children = Children
		}
		if (Array.isArray(Children) && Children.length) {
			constructStandardTreeData(Children, cascader)
		}
	})
}

// 树搜索
// export function flatTreeData(tree = [], data = []) {
//   if (Array.isArray(tree) && tree.length) {
//     tree.forEach(item => {
//       data.push(omit(item, ['children']))
//       flatTreeData(item.children, data)
//     })
//   }
// }

export function digTreeData(arr, target) {
	for (let i = 0, j = arr.length; i < j; i++) {
		if (arr[i].Node && arr[i].Node.ID === target) return arr[i]
		if (Array.isArray(arr[i].Children) && arr[i].Children.length) {
			const result = digTreeData(arr[i].Children, target)
			if (result) return result
		}
	}
}

export function toFixed(num, base = 2, notCeil = true) {
	if (typeof num !== 'number') return num
	let str = num.toFixed(notCeil ? base + 1 : base)
	base === 0 && notCeil && (str = str.substring(0, str.length - 1)) // 防止出现 120. 这类多一个点的字符串
	return str.substring(0, notCeil ? str.length - 1 : str.length)
}

//排序
export function compare(obj1, obj2) {
	var val1 = obj1.num;
	var val2 = obj2.num;
	if (val1 < val2) {
		return -1;
	} else if (val1 > val2) {
		return 1;
	} else {
		return 0;
	}
}

export function validUUID(value) {
	if (!value) return false
	if (value.toString().split('-').length === 4 && value.toString().length === 32) return true
	if (value.toString().split('-').length === 5 && value.toString().length === 36) return true
	return false
}

//显示用户签名
export function showUsersSign(listUsers, imgHost, width, height) {
	var result = []
	if (width == undefined) {
		width = 200
	}
	if (height == undefined) {
		height = 50
	}
	listUsers = listUsers.sort(function(a, b) {
		if (a.CREATE_TIME > b.CREATE_TIME) {
			return 1
		} else {
			return -1
		}
	})

	// listUsers?.map((item, i) => {
	// 			if (item.Nav_User != null && item.Nav_User.Nav_UserSignFiles != null && item.Nav_User.Nav_UserSignFiles.length > 0) {
	// 				result.push( < img width = {
	// 						width
	// 					}
	// 					style = {{margin: "0 0 0 5px",
	// 							maxHeight: "100px"
	// 						}
	// 					}
	// 					src = {
	// 						imgHost + item.Nav_User?.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH
	// 					}
	// 					title = {
	// 						item.Nav_User?.NAME
	// 					}
	// 					alt = {
	// 						item.Nav_User?.NAME
	// 					}
	// 					/>)
	// 				}
	// 				else {
	// 					result.push( < img width = {
	// 							width
	// 						}
	// 						style = {
	// 							{
	// 								margin: "0 0 0 5px",
	// 								maxHeight: "100px"
	// 							}
	// 						}
	// 						src = ''
	// 						title = {
	// 							item.Nav_User?.NAME
	// 						}
	// 						alt = {
	// 							item.Nav_User?.NAME
	// 						}
	// 						/>)
	// 					}

	// 				})
	return result
}

//显示用户签名
export function showUserSign(user, imgHost, width, height) {
	var result = []
	if (width == undefined) {
		width = 200
	}
	if (height == undefined) {
		height = 50
	}
	// height={height}
	// if (user != null && user.Nav_UserSignFiles != null && user.Nav_UserSignFiles.length > 0) {
	// result.push( < img width = {
	// 		width
	// 	}
	// 	style = {
	// 		{
	// 			margin: "0 0 0 5px",
	// 			maxHeight: "100px"
	// 		}
	// 	}
	// 	src = {
	// 		imgHost + user?.Nav_UserSignFiles[0]?.Nav_ImgFile.Nav_File.FILE_PATH
	// 	}
	// 	title = {
	// 		user.NAME
	// 	}
	// 	alt = {
	// 		user.NAME
	// 	}
	// 	/>)
	// }
	// else {
	// 	result.push( < img width = {
	// 			width
	// 		}
	// 		style = {
	// 			{
	// 				margin: "0 0 0 5px",
	// 				maxHeight: "100px"
	// 			}
	// 		}
	// 		src = ''
	// 		title = {
	// 			user.NAME
	// 		}
	// 		alt = {
	// 			user.NAME
	// 		}
	// 		/>)
	// 	}
	return result
}

//判断是PC还是移动端
export function getIsPC() {
	if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/WebOS/i) || navigator
		.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent
		.match(/iPod/i) || navigator.userAgent.match(/Windows Phone/i)) {
		return false
	} else {
		return true
	}
}

//task未空的onBeforeSaveHandleRecord事件日志
export function onBeforeSaveHandleRecordLog(params, formCode, title) {
	if (params.data.TaskID == '00000000-0000-0000-0000-000000000000' || params.data.id ==
		'00000000-0000-0000-0000-000000000000') {
		var orgId = params.login.OrgId; //登录后有存储登录信息
		let json = initFilter(orgId, null, null, null, null, formCode, title, params.data.TaskID,
			" params.pageCode:[" + params.pageCode + "] params.data.id:[" + params.data.id +
			"] UserId:[" + params.login.loginInfo.User.ID + "] params.data.taskCode: [" + params
			.data.taskCode + "] homeReload: [" + params.data.homeReload + "]");
		params.dispatch({
			type: 'app/getDataByPost',
			url: 'PF/PFSysLog/addLog',
			payload: json,
			onlyData: false,
			onComplete: (ret) => {}
		})
	}
}

//显示附件
export function showFiles(Nav_Files, imgHost) {
	var result = []
	// Nav_Files && Nav_Files?.map((item, i) => {
	// 		result.push( < a width = {
	// 				'20%'
	// 			}
	// 			title = {
	// 				item.Nav_ImgFile.FILE_NAME
	// 			}
	// 			target = '_blank'
	// 			href = {
	// 				imgHost + item.Nav_ImgFile.Nav_File.FILE_PATH
	// 			} > {
	// 				item.Nav_ImgFile.FILE_NAME
	// 			} < /a>)
	// 		}) 
	return result
}

export function ShowDateTime(datetime, fmt) {
	if (datetime == undefined || datetime == null || datetime.length < 1) {
		return ''
	} else {
		if (fmt == undefined || fmt == null || fmt.length < 1)
			fmt = 'yyyy-MM-dd'
		return new Date(datetime).Format(fmt)
	}
}

export function downLoad(imgHost, fileName) {
	if (fileName) {
		let link = document.createElement('a')
		link.href = imgHost + '/' + fileName
		document.body.appendChild(link)
		window.open(link)
	} else {
		alert('获取参数配置失败！')
	}
}

Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"H+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 -
		RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1
			.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}


export function ShowPrintClose(props) {
	if (typeof props.data.onCancel != "undefined" && typeof props.data.onCancel == 'function')
		props.data.onCancel();
}


//附件数据结构转换
export function fileStructChange(files) {
	let result = []
	files.forEach(e => {
		result.push({
			...e,
			remotePath: e.Nav_ImgFile.Nav_File.FILE_PATH,
			name: e.Nav_ImgFile.FILE_NAME
		})
	})
	return result
}

//查重
export function duplicated(array) {
	for (let j = 0; j < array.length; j++) {
		if (array.indexOf(array[j]) < array.lastIndexOf(array[j])) {
			return true
		}
	}
	return false;
}
export function isChinaMobilePhone(phone) {
	// 2024
	var reg = new RegExp(/^(13[0-9]|14[05679]|15[012356789]|16[2567]|17[01235678]|18[0-9]|19[012356789])[0-9]{8}$/)
	return reg.test(phone)
}
export function easyCheckID(code) {
	return /^([0-9a-zA-Z]{15}|[0-9a-zA-Z]{18})$/.test(code)
}
export function IsChinese(str) {
		// var reg = /^[\u0391-\uFFE5]+$/;
		var reg =/[^\u4e00-\u9fa5]/
		if (reg.test(str)) {
			return false
		} else {
			return true
		}
	
}
export function checkIDCard(code) {
	// 校验非空
	if (!code) {
		return false
	}
	// 校验长度
	if (code.length != 15 && code.length != 18) {
		return false
	}
	// 定义判别用户身份证号的正则表达式（15位或者18位，最后一位可以为字母）
	//假设18位身份证号码:41000119910101123X  410001 19910101 123X
	//^开头
	//[1-9] 第一位1-9中的一个      4
	//\\d{5} 五位数字           10001（前六位省市县地区）
	//(18|19|20)                19（现阶段可能取值范围18xx-20xx年）
	//\\d{2}                    91（年份）
	//((0[1-9])|(10|11|12))     01（月份）
	//(([0-2][1-9])|10|20|30|31)01（日期）
	//\\d{3} 三位数字            123（第十七位奇数代表男，偶数代表女）
	//[0-9Xx] 0123456789Xx其中的一个 X（第十八位为校验值）
	//$结尾

	//假设15位身份证号码:410001910101123  410001 910101 123
	//^开头
	//[1-9] 第一位1-9中的一个      4
	//\\d{5} 五位数字           10001（前六位省市县地区）
	//\\d{2}                    91（年份）
	//((0[1-9])|(10|11|12))     01（月份）
	//(([0-2][1-9])|10|20|30|31)01（日期）
	//\\d{3} 三位数字            123（第十五位奇数代表男，偶数代表女），15位身份证不含X
	//$结尾

	var reg = new RegExp(/(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/)
	var matches = reg.test(code)
	if (matches) {
		// 15位的身份证，直接返回合法
		if (code.length == 15) {
			return true
		}
		// 18位的进一步校验
		try {
			// TODO:
			if (/^([0-9a-zA-Z]{18})$/.test(code)) {
				return true
			} else {
				return false
			}

		} catch (e) {
			console.error(e)
			return false
		}

	}
	return matches
}
export function getNowFormatDate() {
  let date = new Date(),
    year = date.getFullYear(), //获取完整的年份(4位)
    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
    strDate = date.getDate() // 获取当前日(1-31)
  if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
  if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
 
  return `${year}-${month}-${strDate}`
}