// 判断arr是否为一个数组，返回一个bool值
function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]';
}

// 深度克隆
function deepClone(obj) {
	// 对常见的“非”值，直接返回原来值
	if ([null, undefined, NaN, false].includes(obj)) return obj;
	if (typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
		return obj;
	}
	var o = isArray(obj) ? [] : {};
	for (let i in obj) {
		if (obj.hasOwnProperty(i)) {
			o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
		}
	}
	return o;
}

// JS对象深度合并
function deepMerge(target = {}, source = {}) {
	target = deepClone(target);
	if (typeof target !== 'object' || typeof source !== 'object') return false;
	for (var prop in source) {
		if (!source.hasOwnProperty(prop)) continue;
		if (prop in target) {
			if (typeof target[prop] !== 'object') {
				target[prop] = source[prop];
			} else {
				if (typeof source[prop] !== 'object') {
					target[prop] = source[prop];
				} else {
					if (target[prop].concat && source[prop].concat) {
						target[prop] = target[prop].concat(source[prop]);
					} else {
						target[prop] = deepMerge(target[prop], source[prop]);
					}
				}
			}
		} else {
			target[prop] = source[prop];
		}
	}
	return target;
}

// 转成十六进制
function formatToUnit16Array(file) {
	return new Promise((resolve, reject) => {
		const _this = this
		const reader = new FileReader()
		reader.readAsArrayBuffer(file)
		let strArr = []
		reader.onload = function(e) {
			let unitArray = new Uint8Array(this.result)
			for (let i = 0; i < unitArray.length; i++) {
				let u_arr16 = unitArray[i].toString(16).toLocaleUpperCase()
				if (u_arr16.length < 2) {
					u_arr16 = '0' + u_arr16
				}
				strArr.push(u_arr16)
			}
			resolve(strArr.join(''))
		}
	})
}

// 16 进制字符串转换成整型数组
function hexToBytes(hexStr) {
	let bytes = []
	for (let c = 0; c < hexStr.length; c += 2) {
		bytes.push(parseInt(hexStr.substr(c, 2), 16))
	}
	return bytes
}

// 取得 16 进制字符串 file
function sapDownloadFile(file, filename) {
	let uint8Array = new Uint8Array(hexToBytes(file))
	let blob = new Blob([uint8Array], {
		type: 'application/octet-stream'
	})
	return blob
}

export {
	deepClone,
	deepMerge,
	formatToUnit16Array,
	sapDownloadFile
};
