// 节流函数
export function throttle(fn, gaptime) {
	if (gaptime == null || gaptime == undefined) {
		gaptime = 200
	}
	let _lastTime = null
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gaptime || !_lastTime) {
			fn.apply(this, arguments)
			_lastTime = _nowTime
		}
	}
}
// 图片转Base64,pad 平台
export const imgToBase64 = function (path,callback){
	 // plus.nativeUI.previewImage([path]);
	 // return
	 plus.io.resolveLocalFileSystemURL(path, function (entry) {
	 	// 可通过entry对象操作文件
	 	entry.file(function (file){
	 		var fileReader = new plus.io.FileReader()
	 		fileReader.readAsDataURL(file, 'utf-8')
	 		fileReader.onloadend = function (evt) {
	 			let result = evt.target.result
	 			callback(1,result.split(',')[1])
				// remove this file
				entry.remove( function ( entry ) {
					console.log( "Remove succeeded" );
				}, function ( e ) {
					console.log( e.message );
				});
	 		}
	 		fileReader.onerror = function (e){
	 			callback(0,'文件读取失败')
	 		}
	 	})
	 }, function (e) {
		console.log(JSON.stringify(e))
	 	uni.showToast({icon: 'none',title: 'Resolve file URL failed: ' + e.message})
	 })
}
 
/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 遍历赋值
*/
export const objExtend = (obj1, obj2) => {
  for (let a in obj1){
    obj2[a] = obj1[a]
  }
  return obj2
}

// 正则验证车牌,验证通过返回true,不通过返回false
export const isLicensePlate = function (str) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
}

/**
 * 校验身份证号合法性
 */
export const checkIdNumberValid = (tex) => {
    // var tip = '输入的身份证号有误,请检查后重新输入!'
    let num = tex
    num = num.toUpperCase()

    let len = num.length
    let re
    if (len == 0) return true

    // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))){
        return false
    }

    // 验证前两位地区是否有效
    let aCity = {11: '北京',12: '天津',13: '河北',14: '山西',15: '内蒙古',21: '辽宁',22: '吉林',23: '黑龙江',31: '上海',32: '江苏',33: '浙江',
34: '安徽',35: '福建',36: '江西',37: '山东',41: '河南',42: '湖北',43: '湖南',44: '广东',45: '广西',46: '海南',50: '重庆',51: '四川',
52: '贵州',53: '云南',54: '西藏',61: '陕西',62: '甘肃',63: '青海',64: '宁夏',65: '新疆',71: '台湾',81: '香港',82: '澳门',91: '国外'}

    if (aCity[parseInt(num.substr(0, 2))] == null){
        return false
    }

    // 当身份证为15位时的验证出生日期。
    if (len == 15){
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/)
        let arrSplit = num.match(re)

        // 检查生日日期是否正确
        let dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        let bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
        if (!bGoodDay){
            return false
        }
    }

    // 当身份证号为18位时,校验出生日期和校验位。
    if (len == 18){
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
        let arrSplit = num.match(re)
        // 检查生日日期是否正确
        let dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
        let bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
        if (!bGoodDay){
            return false
        } else {
            // 检验18位身份证的校验码是否正确。
            // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
            let valnum
            let arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
            let arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
            let nTemp = 0
            let i
            for (i = 0; i < 17; i++){
                nTemp += num.substr(i, 1) * arrInt[i]
            }
            valnum = arrCh[nTemp % 11]
            if (valnum != num.substr(17, 1)){
                return false
            }
        }
    }
    return true
}

//  正则有效手机号码
export const isvalidPhone = function (str) {
  const reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
  return reg.test(str)
}

// 日期格式化
export const formatSubmitDate = (val, type) => {
  if (val == null || val == '' || val == undefined) {
    return ''
  } else {
    let _date = new Date(val)
    let _year = _date.getFullYear()
    let _montn = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1)
    let _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate()
    let _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours()
    let _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes()
    let _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds()

    if (type == 'minutes') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes
    else if (type == 'seconds') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes + ':' + _seconds
    else return _year + '-' + _montn + '-' + _day
  }
}

/**
 * //设置应用版本号对应的缓存信息
 * @param {Object} currTimeStamp 当前获取的时间戳
 */
export const  setStorageForAppVersion = function(currTimeStamp){
	uni.setStorage({
		key: 'tip_version_update_time',
		data: currTimeStamp,
		success: function () {
			console.log('setStorage-success');
		}
	});
}
/**
 * 进行版本型号的比对 以及下载更新请求
 * @param {Object} server_version 服务器最新 应用版本号
 * @param {Object} curr_version 当前应用版本号
 * isQzgx 是否强制更新
 * market 打开应用市场
 */
export const checkVersionToLoadUpdate = function(newVersion,type,market){
	const curVer = getApp().globalData.version
	const server_version = newVersion.version
	const curr_version = curVer.versionCode
	const isQzgx = newVersion.forceUpgrade != 1
	let isWifi = plus.networkinfo.getCurrentType()!=3 ? '有新的版本发布,检测到您目前非Wifi连接,' : '有新的版本发布,'
	let msg = isWifi + (!isQzgx ? '请立即更新?' : '是否立即更新版本?')
	// 下载app并安装
	let downloadApp = function(downloadApkUrl){
		var dtask = plus.downloader.createDownload( downloadApkUrl, {}, function ( d, status ) {
			// 下载完成  
			if ( status == 200 ) {   
				plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename),{},{},function(error){  
					uni.showToast({
						icon: 'none',
						title: '安装失败', 
						duration: 1500  
					});  
				})
			} else {  
				 uni.showToast({  
					icon: 'none',
					title: '更新失败',
					duration: 1500  
				 });  
			}
			uni.hideLoading()
		});  
		dtask.start();
	}
	// 打开应用市场
	const marketOpen = function(){
		market.open({
			ios:'',
			android:'com.zyucgj.car'
		});
	}
	if(Number(server_version) > Number(curr_version)){
		// #ifndef APP-PLUS
			uni.showModal({
				title: msg,
				content: '更新内容:'+newVersion.upgradeContent,
				showCancel: isQzgx,
				confirmText:'立即更新',
				cancelText:'稍后进行',
				success: function (res) {
					if (res.confirm) {
						uni.showLoading({
							title: '正在更新中...',
							mask: true,
						});
						//设置 最新版本apk的下载链接
						downloadApp(newVersion.attachment);
						// marketOpen()
					} else if (res.cancel) {
						console.log('稍后更新');
					}
				}
			});
		// #endif
		// #ifdef APP-PLUS
			plus.nativeUI.confirm('更新内容:'+newVersion.upgradeContent, function(e){
				if(e.index == 0){  //  确认
					uni.showLoading({
						title: '正在更新中...',
						mask: true,
					});
					//设置 最新版本apk的下载链接
					downloadApp(newVersion.attachment)
					// marketOpen()
				}
			},{"title":msg,"buttons": !isQzgx ? ["立即更新"] : ["立即更新","稍后进行"]})
		// #endif
	}else{
		if(type){
			uni.showToast({
				icon: 'none',
				title: '已是最新版本',
				duration: 1500  
			}); 
		}
	}
}

// 确认弹框
export const clzConfirm = function(opts){
	// #ifndef APP-PLUS
		uni.showModal({
			title: opts.title,
			content: opts.content,
			showCancel: opts.showCancel == false ? false : true,
			confirmText: opts.confirmText || '确定',
			cancelText: opts.cancelText || '取消',
			success: opts.success,
		})
	// #endif
	// #ifdef APP-PLUS
		plus.nativeUI.confirm(
		opts.content,
		opts.success,
		{"title":opts.title,"buttons": opts.buttons || ["确定","取消"]},
		)
	// #endif
}

// 保存base64 图片数据到阿里云
export const saveBase64ToAliOss = function(base64,callback){
	let bitmap = new plus.nativeObj.Bitmap();
	uni.showLoading({
		mask:true,
		title: '正在保存图片...'
	})
	// 保存图片到相册
	bitmap.loadBase64Data(base64, function() {
		var itemId = new Date().getTime()
		//保存到系统相册
		let filePath = "_doc/poster_"+itemId+".jpg"
		bitmap.save(filePath, {
			overwrite: true, //是否覆盖已有图片, true 是
			quality: 100 //图片质量,1-100 默认50, 100质量最高
		}, function(e) {
			uni.uploadFile({
				url: getApp().globalData.baseUrl + '/upload', //自行修改各自的对应的接口 
				filePath: e.target,
				name: 'file',
				success: (uploadFileRes) => {
					if (uploadFileRes) {
						let res = JSON.parse(uploadFileRes.data);
						callback(res)
					}
					uni.showToast({
						icon: 'none',
						title: uploadFileRes ? '保存图片成功' : '保存图片失败'
					})
					uni.hideLoading()
				}
			});
			bitmap.clear()
		}, function(e) {
			bitmap.clear()
			uni.showToast({
				icon: 'none',
				title: '图片保存失败'
			})
			uni.hideLoading()
		});
	}, function(e) {
	    bitmap.clear()
		uni.showToast({
			icon: 'none',
			title: '图片保存失败'
		})
		uni.hideLoading()
	});
}