//脱敏
export let desensitization = (str, beginLen, endLen) => {
	let len = str.length;
	let firstStr = str.substr(0, beginLen);
	let lastStr = str.substr(endLen);
	let middleStr = str.substring(beginLen, len - Math.abs(endLen)).replace(/[\s\S]/ig, '*');
	let tempStr = firstStr + middleStr + lastStr;
	return tempStr;
}

export let uploadFile = (params,file, successCallback) => {
	for (let i = 0; i < file.length; i++) {
		UploadSelfFile(JSON.stringify(params),file[i], successCallback)
	}
}

//获取base64格式路径
export let urlTobase64 = (file, suc) => {
	uni.getFileSystemManager().readFile({
		filePath: file, //选择图片返回的相对路径
		encoding: 'base64', //编码格式
		success: (res) => { //成功的回调
			let data = res.data;
			let base64 = 'data:image/png;base64,' + data
			suc(base64);
		}
	});
}


/**
 * 上传文件 
 */
export function UploadSelfFile(params, file, callback, configObj) {
	if(file.url.indexOf('xls')==-1&&file.url.indexOf('xlsx')==-1){
		uni.showModal({
			title:'请上传xls、xlsx格式的文件'
		})
		return
	}
	uni.showLoading({
		title: '文件上传中...'
	});
	UploadFileToSystem(params, file, callback, configObj);
	return
	if (uploadConfig) {
		switch (uploadConfig.StoreType) {
			//上传文件到腾讯云
			case 1:
				newPath += "/" + timestamp1 + "" + suffix;
				UploadFileToTencent(uploadConfig, newPath, file, callback);
				break;
				//上传文件到阿里云
			case 2:
				newPath += "/" + timestamp1 + "" + suffix;
				UploadFileToALi(uploadConfig, newPath, file, callback);
				break;
				//上传文件到自己文件服务器
			case 3:
				UploadFileToSystem(uploadConfig, newPath, file, callback, configObj);
				break;
		}
	}
}

/**
 * 上传文件到本地文件系统
 */
export function UploadFileToSystem(paramsObj, fileObj, successCall, configObj) {
	console.log(paramsObj,'-----paramsObj')
	let host = ''
	if (process.env.NODE_ENV === "development") {
		host = 'http://192.168.10.36:8082/api'
	} else {
		host = 'https://eduapi.oytour.com/api'
	}
	uni.uploadFile({
		url: host+'/Upload/UploadStuExamScore',
		filePath: fileObj.url,
		name: 'file',
		formData: {
			'myfile': fileObj,
			params: paramsObj
		},
		success(res) {
			uni.hideLoading();
			let jsonObj = JSON.parse(res.data)
			let uploadResult = {
				Message: jsonObj.Message
			}
			successCall(uploadResult);
		},
		fail(err) {
			console.log("uploadErr", err)
		}
	});
}
/**
 * 上传文件到阿里云
 */
export function UploadFileToALi(uploadConfig, fileFullPath, fileObj, successCall) {
	//     var OSS = require('ali-oss');
	//     var oss = new OSS({
	//         region: uploadConfig.Region,
	//         accessKeyId: uploadConfig.SecretId,
	//         accessKeySecret: uploadConfig.SecretKey,
	//         bucket: uploadConfig.Bucket
	//     })
	//     var result = oss.multipartUpload(fileFullPath, fileObj, {
	//         progress: function* (p) { }
	//     }).then(res => {
	//         uni.hideLoading()
	//         var uploadResult = {
	//             Code: 1,
	//             FileName: fileObj.name,
	//             FileUrl: res.res.requestUrls[0].split('?')[0].replace('http', 'https')
	//         }
	//         if (successCall) {
	//             successCall(uploadResult);
	//         }
	//     })
}

/**
 * 上传文件到腾讯云
 */
export function UploadFileToTencent(uploadConfig, fileFullPath, fileObj, successCall) {
	// var COS = require('cos-js-sdk-v5');
	// var cos = new COS({
	//     SecretId: uploadConfig.SecretId,
	//     SecretKey: uploadConfig.SecretKey,
	// });
	// cos.putObject({
	//     Bucket: uploadConfig.Bucket,
	//     Region: uploadConfig.Region, //存储桶所在地域，必须字段
	//     Key: fileFullPath, //文件名
	//     StorageClass: 'STANDARD',
	//     Body: fileObj, // 上传文件对象
	//     onProgress: function (progressData) { }
	// }, function (err, data) {
	//     uni.hideLoading()
	//     if (data && data.statusCode == 200) {
	//         var uploadResult = {
	//             Code: 1,
	//             FileName: fileObj.name,
	//             FileUrl: "https://" + data.Location
	//         }
	//         if (successCall) {
	//             successCall(uploadResult);
	//         }
	//     } else {
	//         /*上传文件异常*/
	//         console.log(err || data);
	//     }
	// });
}

// 数字转汉字
export let changeNumToHan = (num) => {
	var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千',
		'亿'); //可继续追加更高位转换值
	if (!num || isNaN(num)) {
		return "零";
	}
	var english = num.toString().split("")
	var result = "";
	for (var i = 0; i < english.length; i++) {
		var des_i = english.length - 1 - i; //倒序排列设值
		result = arr2[i] + result;
		var arr1_index = english[des_i];
		result = arr1[arr1_index] + result;
	}
	//将【零千、零百】换成【零】 【十零】换成【十】
	result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
	//合并中间多个零为一个零
	result = result.replace(/零+/g, '零');
	//将【零亿】换成【亿】【零万】换成【万】
	result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
	//将【亿万】换成【亿】
	result = result.replace(/亿万/g, '亿');
	//移除末尾的零
	result = result.replace(/零+$/, '')
	//将【零一十】换成【零十】
	//result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
	//将【一十】换成【十】
	result = result.replace(/^一十/g, '十')
	return result;
}
// 判断登录
export const isLogin = () => {
	const userinfo = uni.getStorageSync('userInfo');
	if (userinfo && userinfo.Id > 0) {
		return true
	}
	else{
		return false
	}
}
export let getImageColor = async (canvasID, imgID, imgSrc) => {
	let res = {
		r: 1,
		g: 1,
		b: 1
	}
	const canvas = uni.createCanvasContext(canvasID)
	let imgWidth
	let imgHeight

	await new Promise(resolve => {
		uni.createSelectorQuery().select("#" + imgID).boundingClientRect(res => {
			imgWidth = res?.width ?? 100;
			imgHeight = res?.height ?? 100;
			resolve()
		}).exec()
	})
	canvas.fillRect(0, 0, imgWidth, imgHeight)
	let base64Img = await netUrlTobase64(imgSrc)
	canvas.drawImage(base64Img, 0, 0, imgWidth, imgHeight)
	res = await new Promise((resolve, reject) => {
		canvas.draw(true, (e) => {
			// 获取像素数据
			uni.canvasGetImageData({
				// #ifdef MP-WEIXIN
				canvasId: canvas.canvasId,
				// #endif
				// #ifndef MP-WEIXIN
				canvasId: canvas.id,
				// #endif
				x: 0,
				y: 0,
				width: imgWidth,
				height: imgHeight,
				success: (res) => {
					let data = res.data;
					var r = 1,
						g = 1,
						b = 1;
					// 取所有像素的平均值
					for (var row = 0; row < imgHeight; row++) {
						for (var col = 0; col < imgWidth; col++) {
							if (row == 0) {
								r += data[((imgWidth * row) + col)];
								g += data[((imgWidth * row) + col) + 1];
								b += data[((imgWidth * row) + col) + 2];
							} else {
								r += data[((imgWidth * row) + col) * 4];
								g += data[((imgWidth * row) + col) * 4 + 1];
								b += data[((imgWidth * row) + col) * 4 + 2];
							}
						}
					}
					// 求取平均值
					r /= (imgWidth * imgHeight);
					g /= (imgWidth * imgHeight);
					b /= (imgWidth * imgHeight);
					// 将最终的值取整
					r = Math.round(r);
					g = Math.round(g);
					b = Math.round(b);
					let obj = {
						r,
						g,
						b
					}
					resolve(obj);
				},
				fail: (fail) => {
					reject(fail);
				}
			}, this);
		})
	})
	return res
}
// 网络图片转base64
export let netUrlTobase64 = async (url, suc) => {
	let toBase64Url = "";
	let newUrl = url
	let flag = url.indexOf('https')
	if (flag == -1) {
		newUrl = url.replace(/http/, 'https')
	}
	toBase64Url = await new Promise(resolve => {
		uni.request({
			url: newUrl,
			method: 'GET',
			responseType: 'arraybuffer',
			success(res) {
				const base64 = wx.arrayBufferToBase64(res.data); //把arraybuffer转成base64
				const conType = res.header['Content-Type']
				toBase64Url = 'data:' + conType + ';base64,' + base64;
				resolve(toBase64Url)
			}
		});
	})
	return toBase64Url
}