var tools = {
	httpOne: 'https://yrjy.yurongjiuye.cn/api/', //域名 线上
	upload: 'https://yrjy.yurongjiuye.cn/api/common/upload', //上传图片域名
	URL: 'https://yrjy.yurongjiuye.cn',
	showtt: function(title, icon) {
		if (title && title.length > 0) {
			uni.showToast({
				title: title,
				duration: 2000,
				icon: icon ? icon : 'none'
			})
		}
	},
	showload: function(title, mask = false) {
		if (title && title.length > 0) {
			uni.showLoading({
				title,
				mask
			})
		}
	},
	isPromotionUnlockedValue: function(value) {
		return value === true || value === 'true' || value === 1 || value === '1'
	},
	getPromotionUnlocked: function() {
		return this.isPromotionUnlockedValue(uni.getStorageSync('promotionUnlocked'))
	},
	setPromotionUnlocked: function(value = true) {
		if (this.isPromotionUnlockedValue(value)) {
			uni.setStorageSync('promotionUnlocked', true)
			return true
		}
		uni.setStorageSync('promotionUnlocked', false)
		return false
	},
	setPromotionBridgeSkip: function(path) {
		if (!path) {
			return
		}
		uni.setStorageSync('promotionBridgeSkipPath', path)
	},
	setTabbarSelectedPath: function(path) {
		if (!path) {
			return
		}
		uni.setStorageSync('tabbarSelectedPath', path)
	},
	getTabbarSelectedPath: function() {
		return uni.getStorageSync('tabbarSelectedPath') || ''
	},
	consumePromotionBridgeSkip: function(path) {
		const skipPath = uni.getStorageSync('promotionBridgeSkipPath')
		if (skipPath && skipPath === path) {
			uni.removeStorageSync('promotionBridgeSkipPath')
			return true
		}
		return false
	},
	clearLoginStorage: function() {
		uni.clearStorageSync()
	},
	//图片地址拼接
	oss: function(url) {
		if (!url || url.indexOf("http://") != -1 || url.indexOf("https://") != -1) {
			return url
		} else {
			return this.URL + url
		}
	},
	// 跳转下一页
	goNext(url) {
		uni.navigateTo({
			url: url
		})
	},
	// 返回上一页
	goBack(num) {
		uni.navigateBack({
			delta: num
		})
	},
	// 跳转tabar页面
	goSwitchTab(url) {
		uni.switchTab({
			url: url
		})
	},
	// 关闭所有页面，跳转到指定页面
	goReLaunch(url) {
		uni.reLaunch({
			url: url
		})
	},
	// 关闭当前页，跳转下一页
	goRedirectTo(url) {
		uni.redirectTo({
			url: url
		})
	},
	//正常请求 
	//请求格式 method POST GET
	//请求地址 url
	//请求参数 data
	//加载中的框  showLoads
	axios: function(method, url, data, showLoads) {
		if (showLoads) {
			uni.showLoading({
				'title': showLoads
			})
		}; //加载中的框  showLoads
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.httpOne + url, //请求地址 url
				data: data, //请求参数 data
				method: method, //请求格式 method POST GET
				header: {
					'Content-Type': 'application/json;charset=utf-8'
				},
				success: (res) => {
					if (showLoads) {
						uni.hideLoading()
					}
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				},
				complete() {

				}
			})
		})
	},
	throttle: function(fn, wait) {
		clearTimeout(this.timeout)
		let id = this.tabs[this.current].id
		this.timeout = setTimeout(() => {
			this.getList(id, this.current)
		}, 450)
	},
	//FROM的请求
	//请求格式 method POST GET
	//请求地址 url
	//请求参数 data
	//加载中的框  showLoads
	axiosFrom: function(method, url, data, showLoads) {
		let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''; //用户的token
		if (showLoads) {
			uni.showLoading({
				'title': showLoads
			})
		}; //加载中的框
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.httpOne + url, //请求地址 url
				method: method, //请求格式 method POST GET
				data: data, //请求参数 data
				header: {
					'content-Type': 'application/x-www-form-urlencoded',
					'token': token
				},
				success: (res) => {
					if (showLoads) {
						uni.hideLoading()
					}
					resolve(res.data)
				},
				fail: (err) => {
					console.log('err', err)
					reject(err)
				},
				complete() {

				}
			})
		})
	},
	//FROM的请求 token
	//请求格式 method POST GET
	//请求地址 url
	//请求参数 data
	//加载中的框  showLoads
	axiosFromToken: function(method, url, data, showLoads) {
		let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''; //用户的token
		if (showLoads) {
			uni.showLoading({
				'title': showLoads
			})
		}; //加载中的框
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.httpOne + url, //请求地址 url
				method: method, //请求格式 method POST GET
				data: data, //请求参数 data
				header: {
					'content-Type': 'application/x-www-form-urlencoded',
					'token': token
				},
				success: (res) => {
					if (showLoads) {
						uni.hideLoading()
					}
					if (res.statusCode == 401) {
						uni.showModal({
							title: '温馨提示',
							content: '尚未登录或登录已过期，是否前往登录？',
							success: (res) => {
								this.clearLoginStorage()
								if(res.confirm){
									uni.navigateTo({
										url: "/pages/login/login"
									})
								}
							}
						});
						return false
					}
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				},
				complete() {

				}
			})
		})
	},
	getScrollHeight(titleH) {//获取元素铺满全屏的高度 uni.createSelectorQuery().select(".scroll")
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let system = uni.getSystemInfoSync()
				console.log(system, titleH)
				titleH.boundingClientRect(data => {
					console.log(data)
					resolve(system.windowHeight - data.top)//计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
				}).exec()
			}, 10)
		})
	},
	downloadFile(file,ifOpenFile) { //下载课件
		uni.showLoading({
			title: '请稍等',
			content: '正在下载文件',
			mask: true
		})
		uni.downloadFile({
			url: file, //下载地址接口返回
			success: (data) => {
				if (data.statusCode === 200) {
					//文件保存到本地
					uni.saveFile({
						tempFilePath: data.tempFilePath, //临时路径
						success: function(res) {
							uni.showToast({
								icon: 'none',
								mask: true,
								title: '文件已保存：' + res.savedFilePath, //保存路径
								duration: 3000,
							});
							if (ifOpenFile) {
								setTimeout(() => {
									//打开文档查看
									uni.openDocument({
										filePath: res.savedFilePath,
										success: function(res) {
											// console.log('打开文档成功');
										}
									});
								}, 1000)
							}
						},
						complete() {
							uni.hideLoading()
						}
					});
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '失败请重新下载',
				});
			},
		});
	},
	saveImage(url) { //保存二维码
		const that = this
		uni.showLoading({
			title: '加载中'
		})
		uni.downloadFile({
			url, //网络图片的地址
			success(res) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath, //临时文件地址
					success(res) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
						uni.hideLoading()
					},
					fail(res) {
						uni.showToast({
							title: '保存失败',
							icon: 'error'
						})
						uni.hideLoading()
						console.log('保存错误', res);
					}
				})
			},
			fail(res) {
				console.log('保存错误', res);
			},
		})
	},
	lookPhoto(url,current=0) {//查看图片
		uni.previewImage({
			current,
			urls: url,
			fail(err) {
				// console.log(err,'报错')
			}
		})
	},
	//函数拷贝
	copyObj(obj = {}) {
		//变量先置空
		let newobj = null;

		//判断是否需要继续进行递归
		if (typeof(obj) == 'object' && obj !== null) {
			newobj = obj instanceof Array ? [] : {};
			//进行下一层递归克隆
			for (var i in obj) {
				newobj[i] = this.copyObj(obj[i])
			}
			//如果不是对象直接赋值
		} else newobj = obj;

		return newobj;
	},
	imageLook(httpImgUrl) {
		uni.previewImage({
			urls: httpImgUrl
		})
	},
	// from表单的输入
	formInfo(data, keys) {
		let obj = {
			...data
		}
		// data 验证对象 Object
		// keys 验证对象中非必填字段 Array
		if (keys && keys[0]) {
			keys.forEach(val => {
				delete obj[val]
			})
		}
		let show = true
		for (let key in obj) {
			const value = obj[key]
			if (!value) {
				uni.showToast({
					title: '请检查信息是否填写',
					icon: 'none'
				})
				console.log(`未填写完整value => ${value}, key => ${key}`)
				show = false;
				break;
			}
		}
		return show;
	},
	call(tel) {
		// #ifdef APP
			plus.android.requestPermissions(
				["android.permission.CALL_PHONE"], 
				function(resultObj) {
					var result = 0;
					for (var i = 0; i < resultObj.granted.length; i++) {
						var grantedPermission = resultObj.granted[i];
						console.log('已获取的权限：' + grantedPermission);
						result = 1
					}
					for (var i = 0; i < resultObj.deniedPresent.length; i++) {
						var deniedPresentPermission = resultObj.deniedPresent[i];
						console.log('拒绝本次申请的权限：' + deniedPresentPermission);
						result = 0
					}
					for (var i = 0; i < resultObj.deniedAlways.length; i++) {
						var deniedAlwaysPermission = resultObj.deniedAlways[i];
						console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
						result = -1
					}
					console.log(result);
					if(result == 1){
						uni.makePhoneCall({
							 phoneNumber: tel,//电话号码
							success(ress) {
								console.log("拨打电话成功",ress)
							},
							fail(err) {
								console.log("拨打电话失败",'err')
							}
						});
					}else{
						uni.showToast({
							title:"请开启拨号权限",
							icon:"error",
						})
					}
				},
				function(error) {
					console.log('申请权限错误：' + error.code + " = " + error.message);
				}
			);
		// #endif
		// #ifdef MP-WEIXIN
				uni.makePhoneCall({
					 phoneNumber: tel,//电话号码
					success(ress) {
						console.log("拨打电话成功",ress)
					},
					fail(err) {
						console.log("拨打电话失败",'err')
					}
				});
		// #endif
	},
	// 判断身份证号    
	isSfz(idcard) {
		var id =
			/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/
		if (idcard === '') {
			return false
		} 
		 if (!id.test(idcard)) {
			return false
		} else {
			return true
		}
	},
	// 判断是否是手机号   
	isPhone(val) {
		var patrn = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/
		if (!patrn.test(val) || val === '') {
			uni.showToast({
				title: '手机号格式不正确',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},
	// 判断邮箱
	isEmail(email) {
		if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
			return true;
		else
			return false;
	},
	//当前日期
	data() {
		var now = new Date(),
			y = now.getFullYear(),
			m = now.getMonth() + 1,
			d = now.getDate();
		let Time = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d)
		return Time
	},
	//当前时间
	time() {
		var now = new Date(),
			y = now.getFullYear(),
			m = now.getMonth() + 1,
			d = now.getDate();
		let Time = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + "-" + now.toTimeString()
			.substr(0, 8)
		let str = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + "T" + now.toTimeString().substr(
			0, 8)
		console.log(str, 'str')
		return Time
	},
	//时间转时间戳
	timeTotimeStamp(time) {
		let timestamp = Date.parse(new Date(time).toString());
		//timestamp = timestamp / 1000; //时间戳为13位需除1000，时间戳为13位的话不需除1000
		return timestamp;
		//2021-11-18 22:14:24的时间戳为：1637244864707
	},
	//时间差
	// let startime = new Date()
	// let endTime = new Date(res.data.yushou_end_time_text)
	timeDifference(startime, endTime) {
		const stime = new Date(startime).getTime();
		const etime = new Date(endTime).getTime();
		const diffTime = etime - stime;
		const day = Math.floor(diffTime / (1000 * 60 * 60 * 24));
		const hour = Math.floor(diffTime / (1000 * 60 * 60) % 24);
		const minute = Math.floor(diffTime / (1000 * 60) % 60);
		const second = Math.floor(diffTime / 1000 % 60);
		let obj = {
			day,
			hour,
			minute,
			second,
			timeText: `${day}天${hour}时${minute}分${second}秒`
		}
		return obj
	},
	//时间戳计算时间差
	timestampDifference(startime, endTime) {
		const diffTime = endTime - startime;
		const day = Math.floor(diffTime / (60 * 60 * 24));
		const hour = Math.floor(diffTime / 60 / 60 % 24);
		const minute = Math.floor(diffTime / 60 % 60);
		const second = Math.floor(diffTime % 60);
		let obj = {
			day,
			hour,
			minute,
			second,
			timeText: `${day}天${hour}时${minute}分${second}秒`
		}
		return obj
	},
	// 时间戳转时间
	timestampToTime(timestamp) {
		timestamp *= 1000
		var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
		var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		return Y + M + D;
	},
	getDays() {//获取未来n天的日期信息
		var leng = 7;
		var now = new Date();
		var nowTime = now.getTime();
		var oneDayTime = 24 * 60 * 60 * 1000;
		var date = []
		for (var i = 0; i < leng; i++) {
			var dateItem = {date: '', text: ''}
			//显示星期
			var ShowTime = nowTime + i * oneDayTime;
			//初始化日期时间
			var myDate = new Date(ShowTime);
			var year = myDate.getFullYear();
			var month = myDate.getMonth() + 1;
			var date = myDate.getDate();
			dateItem.text = "星期" + "日一二三四五六".charAt(myDate.getDay());
			dateItem.date = year + "-" + month + "-" + date ; dateItem.select = 0;
			dateItem.year = year;dateItem.month = month;dateItem.day = date;
			if (i == 0) dateItem.text = '今天'
			if (i == 1) dateItem.text = '明天'
			if (i == 2) dateItem.text = '后天'
			date.push(dateItem);
		}
		return date
		console.log(date)
	},
	/**
	 * 判断是否是中文
	 * @param str
	 * @returns {Boolean}
	 */
	isChine: function(str) {
		var reg = /^([u4E00-u9FA5]|[uFE30-uFFA0])*$/;
		if (reg.test(str)) {
			return false;
		}
		return true;
	},
	/**
	 * 判断是否是中文
	 * @param num
	 * @returns {String | Number}
	 */
	isForNumber(num) {
		num = Number(num);
		if (num == 0) {
			return num + '';
		} else
		if (num > 1 && num < 10000) {
			return num + '';
		} else {
			return (num / 10000).toFixed(2) + '万';
		}
	},
	/*验证是否为图片*/
	tmCheckImage: function(fileName) {
		return /(gif|jpg|jpeg|png|GIF|JPG|PNG)$/ig.test(fileName);
	},
	/*验证是否为视频*/
	tmCheckVideo: function(fileName) {
		return /(mp4|mp3|flv|wav)$/ig.test(fileName);
	},
	// 判断密码是否符合 至少6位,包括大小写字母、数字、特殊字符
	isPassword(val) {
		var reg = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{8,16}$/;
		if (val === '') {
			uni.showToast({
				title: '请输入密码',
				icon: 'none'
			})
		} else if (!reg.test(val)) {
			uni.showToast({
				title: '至少6位,包括大小写字母、数字、特殊字符',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},
	copyTextH5App(info) {
		if (!info) return false;
		info = info + '';
		// #ifndef H5
		uni.setClipboardData({ //准备复制的数据
			data: info + '',
			success: function(res) {
				uni.showToast({
					title: '复制成功'
				});
			}
		})
		// #endif
		// #ifdef H5
		let result
		let textarea = document.createElement("textarea")
		textarea.value = info
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, info.length) // 设置选定区的开始和结束点

		result = document.execCommand("copy") //将当前选中区复制到剪贴板
		// console.log('[result]', result);
		if (result) {
			uni.showToast({ //提示
				title: '复制成功'
			})
		} else {
			uni.showToast({ //提示
				title: '复制失败，请重新尝试',
				icon: 'none'
			})
		}
		textarea.remove()
		// #endif
	},
}


export default tools;
