const app = getApp();
const env = {
	NODE_ENV: 'dev',
	dev: {
		apiUrl: 'https://apitest.tongyu99.com'
	},
	prd: {
		apiUrl: 'https://apimall.zhiqiyun.com'
		// apiUrl: 'https://wlapi-pro-smartcity.123cx.com'
	},
	pota: {
		// apiUrl: 'http://192.168.110.248:7012' //y
		// apiUrl: 'http://192.168.110.97:7012' ,//w
		apiUrl:'http://192.168.110.109:7012',//w
	}
}

var header = {
	'content-type': 'application/x-www-form-urlencoded',
	'appId': 'ZQfMJBmiKkUKE0g',
}

/**小程序配置 */
const publicss = {
	WX_GZH_APPID: 'wxc01ea0423e91d9e0',
	// WX_GZH_URI: 'http://zhly.zhiqiyun.com/pages/authorize/authorize', //本地
	WX_GZH_URI: 'http://lcweb.tongyu99.com/pages/authorize/authorize', //线上
	// domain_head:' http://zhly.zhiqiyun.com',
	domain_head: 'http://lcweb.tongyu99.com',

	picUrls: 'https://zhiqiyun.oss-cn-hangzhou.aliyuncs.com/static/', //图片地址

	'mapLBSKEY': 'LVABZ-ZRC36-BWWS3-E6WJB-BVKZK-7DFP4',

	'homeTopBgCode': '1001', //公共服务平台首页顶部banner位
	'teseTopBgCode': '3001', //特色频道顶部banner位
	'foodBannerCode': '5001', //特色美食顶部banner位
	'hotelBannerCode': '4001', //酒店预订顶部banner位

	//产品的分类类型
	'mpOtc': '20', //门票    

	//信息发布code
	'zwtz': 'zwtz_2', //政务通知
	
	'ksggCode':'009',//考试公告
	'zysxCode':'010',//注意事项
	'wztxCode':'011',//网站提醒
	'xxzlCode':'012',//学习资料
	'cjwtCode':'013',//常见问题

}
/*
 * 获取token
 */
const getToken = (success) => {
	// let token = 'NYSQdiwsrMjGY2tGBqpSQjzeu34zXDUZw';
	let token = getStorage('AUTH_TOKENS');
	if (token) {
		success.call(this, token);
		return false;
	} else {
		loadToken(data => {
			success.call(this, data);
		});
	}
}
const loadToken = (success) => {
	let that = this
	uni.request({
		url: env[env.NODE_ENV].apiUrl + '/api/access_token',
		data: {},
		method: 'get',
		header: header,
		success(json) {
			if (json.statusCode !== 200) return msg(json.data.message);
			if (json.data.code !== 0) return msg(json.data.msg)
			setStorage('AUTH_TOKENS', json.data.data);
			success.call(that, json.data.data);
		},
		fail() {
			msg('access_token 获取失败');
		}
	})
}

const clearValueEmpty = (data) => {
	let keyValue = {};
	for (let key in data) {
		let value = typeof data[key];
		if (value == 'string' && value) {
			if (data[key] != 'undefined' && data[key] != " " && data[key] != undefined && data[key] != null) {
				keyValue[key] = data[key];
			}
			// keyValue[key] = data[key];
		} else if (value == 'number' && value != null) {
			keyValue[key] = data[key];
		} else if (value == 'boolean') {
			keyValue[key] = data[key];
		} else {
			if (data[key]) keyValue[key] = data[key];
		}
	}
	return keyValue;
}

/**
 * 公共请求
 * 
 * @param {*} url  请求url
 * @param {*} data 请求参数
 * @param {*} method 请求方法
 * @param {*} success 成功函数
 * @param {*} isLoad 是否显示加载提示
 */
const baseRequest = (url, data, method, success, isLoad) => {
	getToken(token => {
		if (isLoad) {
			loadIng('加载中');
		};
		header.authorityToken = token;
		if (url.indexOf('/v3') != -1) {
			header['content-type'] = 'application/json;charset=UTF-8'
		}
		if (url.indexOf('manage/v3') != -1) {
			header.authorityToken = getStorage('admin_authToken');
		}
		uni.request({
			url: env[env.NODE_ENV].apiUrl + url,
			// url: url,
			data: clearValueEmpty(data),
			method: method,
			header: header,
			success(json) {
				if (isLoad) {
					uni.hideLoading();
				}
				if (json.statusCode !== 200) return msg(json.data.message);
				if (json.data.code === 10021 || json.data.code === 10020) {
					removeStorage('AUTH_TOKENS');
					return redirectIndex();
				}
				if(json.data.code!==0&&json.data.msg=='答题次数已用完'){
					console.log('答题次数已用完')
					return alertMsg(json.data.msg,()=>{
						removeStorage('AUTH_TOKENS');
						redirectIndex();
					})
				}
				if (json.data.code !== 0) {
					return msg(json.data.msg)
				}
				let data = json.data.data;
				if (typeof data === 'string' && data.indexOf("{") === 0) {
					data = JSON.parse(data);
				}
				if (data == null) {
					data = {};
				}
				success.call(this, data);
			},
			fail() {
				if (isLoad) {
					uni.hideLoading();
				}
			},
		})
	})
}

const loadIng = (msg) => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

/**POST请求 */
const postRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, isLoad);
}

const postRequestLoding = (url, data, success, isLoding) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, false, isLoding);
}

/**GET请求 */
const getRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'get', success, isLoad);
}
/**Put请求 */
const putRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'put', success, isLoad)
}
const putRequestJson = (url, data, success, isLoad) => {
	header['content-type'] = 'application/json;charset=UTF-8'
	baseRequest(url, data, 'put', success, isLoad)
}


/**
 * 上传文件
 * @param {*} url 请求url
 * @param {*} data 携带数据
 * @param {*} success 请求成功函数
 */
const uploadFile = (url, data, success, isLoad) => {
	// console.log(env[env.NODE_ENV].apiUrl + url, data)
	getToken(token => {
		if (isLoad) {
			loadIng('加载中');
		};
		uni.uploadFile({
			url: env[env.NODE_ENV].apiUrl + url,
			filePath: data,
			name: 'file',
			header: {
				'appId': header['appId'],
				'authorityToken': token
			},
			success(res) {
				uni.hideLoading();
				if (res.statusCode !== 200) {
					return msg('文件上传失败');
				}
				let data = JSON.parse(res.data);
				if (data.code !== 0) {
					return msg(data.msg);
				}
				success.call(this, data.data);
			},
		})
	})
}


/**弹窗 */
const msg = (title, success) => {
	if (title) {
		uni.showToast({
			title: title,
			icon: 'none',
			success() {
				if (success) success.call(this);
			}
		});
	}
	return false;
}

const msgConfirm = (msg, success, cancel) => {
	uni.showModal({
		title: '提示',
		content: msg,
		success(res) {
			if (res.confirm) {
				success.call(this);
			} else {
				if (cancel) cancel.call(this);
			}
		}
	})
}

const msgConfirmText = (msg, confirmText, success, cancel) => {
	uni.showModal({
		title: '提示',
		content: msg,
		confirmText: confirmText,
		success(res) {
			if (res.confirm) {
				success.call(this);
			} else {
				if (cancel) cancel.call(this);
			}
		}
	})
}

const alertMsg = (msg, success) => {
	uni.showModal({
		title: '提示',
		content: msg,
		showCancel: false,
		success(res) {
			if (success) success.call(this);
		}
	})
	return false;
}

const load = msg => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

const g = (url, success, isLoad) => {
	getRequest(url, {}, success, isLoad)
}

const p = (url, success, isLoad) => {
	postRequest(url, {}, success, isLoad)
}

const send = (url, mobile, success, error) => {
	if (!mobile) {
		return msg('手机号码不能为空', error);
	}
	postRequest(url, {
		phone: mobile
	}, json => {
		if (json.code !== 0) {
			return msg(json.msg, error);
		}
		let time = 60;
		const initTime = setInterval(() => {
			time--;
			if (time > 0) {
				success.call(this, time + '秒后获取');
			} else {
				clearInterval(initTime);
				success.call(this, '获取验证码');
			}
		}, 1000)
	})
}
// 登陆拦截
const redirectIndex = (params) => {
	uni.clearStorageSync();
	var pages = getCurrentPages();
	let currentUrl;
	if (pages) {
		var currentPage = pages[pages.length - 1];
		if (currentPage) {
			currentUrl = currentPage.route;
			let query = currentPage.query;
			if (query) {
				for (let key in query) {
					const fo = key + '=' + query[key];
					currentUrl += currentUrl.indexOf('?') > -1 ? '&' + fo : '?' + fo;
				}
			}
			if (currentUrl) {
				console.log('currentUrl》》》》》', currentUrl);
				setStorage("REDIRECT_URL", '/' + currentUrl)
				if (currentUrl == 'pages/login/login') {
					console.log('当前已经处于登录页面，不在向下执行跳转');
					return
				}
			}
		}
	}
	let redirectUrl = '/pages/login/login' + (params ? params : '');
	uni.reLaunch({
		url: redirectUrl
	})
	return false;
}

const saveImage = (url) => {
	uni.saveImageToPhotosAlbum({
		filePath: url,
		success() {
			msg('图片保存成功');
		}
	})
}

const saveImageToPhotosAlbum = (url) => {
	if (!url) return msg('小程序码不存在');
	uni.getImageInfo({
		src: url,
		success(json) {
			// uni.getSetting({
			//   success(res) {
			//     if (!res.authSetting['scope.writePhotosAlbum']) {
			//       uni.authorize({
			//         scope: 'scope.writePhotosAlbum',
			//         success() {
			//           saveImage(json.path);
			//         }
			//       })
			//     } else {
			//       saveImage(json.path);
			//     }
			//   }
			// })
		}
	})
}

const getConfig = (config, id) => {
	let con = {};
	config.info.forEach(inf => {
		// console.log(inf.version, inf.version ? inf.version.indexOf(id) : '-')
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	config.card.forEach(inf => {
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	config.realTime.forEach(inf => {
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	return con;
}

const isLogin = async (error) => {
	let userInfo = getStorage('userInfo');
	if (!userInfo || !userInfo.id) {
		if (error) return false;
		// console.log("第一次执行")
		return redirectIndex();
	}
	return true;
}

//检测是否登录
const isLogins = (isGoLogin) => {
	let userInfo = getStorage('userInfo');
	if (!userInfo) {
		if (isGoLogin) {
			redirectIndex();
		}
		return false;
	}
	return true;
}

/**
 * 退出登录
 */
const outLogin = () => {
	uni.clearStorageSync();
	isLogins(true);
}


const setStorage = (key, value) => {
	uni.setStorageSync(env.NODE_ENV + "_" + key, value)
}

const getStorage = (key) => {
	return uni.getStorageSync(env.NODE_ENV + "_" + key)
}

const removeStorage = (key) => {
	return uni.removeStorageSync(env.NODE_ENV + "_" + key);
}

function isWeixin() {
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}

const payOrder = (id, type, success) => {
	let isShowLoading = false;
	if (!isShowLoading) {
		loadIng('加载中');
		isShowLoading = true;
	}
	var loctionAddressMap = getStorage('loctionAddressMap');
	var datas = {
		id: id
	};
	if (loctionAddressMap) {
		datas.province = loctionAddressMap.province;
		datas.city = loctionAddressMap.city;
	};
	datas.payChannel = 'wx_pub';
	postRequest('/api/order/weixin/pay', datas, json => {
		//下单完成后，调用验证
		if (isWeixin()) {
			checkWXJs(id, json, type, success);
		}
	})
}

//微信支付订单公共方法 
// const payOrder = (id, success) => {
// 	let isShowLoading = false;
// 	if (!isShowLoading) {
// 		loadIng('加载中');
// 		isShowLoading = true;
// 	}
// 	var loctionAddressMap = getStorage('loctionAddressMap');
// 	var datas = {
// 		id: id
// 	};
// 	if (loctionAddressMap) {
// 		datas.province = loctionAddressMap.province;
// 		datas.city = loctionAddressMap.city;
// 	};
// 	postRequest('/api/order/weixin/pay', datas, json => {
// 		// console.log(json)
// 		if (json.type === 2 || json.type === 3) {
// 			//调用后台判断订单是否支付成功
// 			let i = 0;
// 			let timer = setInterval(() => {
// 				postRequest('/api/order/check', {
// 					id: id
// 				}, res => {
// 					if (res.isSuccess || i === 4) {
// 						clearInterval(timer);
// 						success.call(this, res.isSuccess);
// 					} else {
// 						i++;
// 					}
// 				}, true)
// 			}, 200);
// 			// success.call(this);
// 			return false;
// 		}
// 		uni.requestPayment({
// 			timeStamp: json.timeStamp,
// 			nonceStr: json.nonceStr,
// 			package: json.packages,
// 			signType: json.signType,
// 			paySign: json.sign,
// 			success: function() {
// 				console.log('支付成功')
// 				let i = 0;
// 				let timer = setInterval(() => {
// 					postRequest('/api/order/check', {
// 						id: id
// 					}, res => {
// 						console.log(i)
// 						if (res.isSuccess || i === 5) {
// 							clearInterval(timer);
// 							success.call(this, res.isSuccess);
// 						} else {
// 							i++;
// 						}
// 					}, true)
// 				}, 500);
// 			},
// 			fail: function(res) {
// 				console.log('支付失败')
// 				postRequest('/api/order/cancelPay', {
// 					id: id
// 				}, data => {
// 					uni.redirectTo({
// 						url: '/mine/orderDet/orderDet?id=' + id,
// 					})
// 				})
// 				console.log(res);
// 			}
// 		})
// 		if (isShowLoading) {
// 			uni.hideLoading();
// 			isShowLoading = false;
// 		}
// 	})
// }

const authSetting = (authority, success, error) => {
	// console.log(authority,success)
	// #ifndef H5
	uni.getSetting({
		success(res) {
			if (res.authSetting[authority]) {
				success.call(this);
				return false;
			}
			uni.authorize({
				scope: authority,
				success() {
					success.call(this);
				},
				fail: function(res) {
					error.call(this);
				}
			})
		}
	})
	// #endif
}

const getLocation = (suss) => {
	// #ifndef H5
	authSetting('scope.userLocation', () => {
		// load('定位中…');
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy: true,
			success: function(res) {
				// uni.hideLoading();
				setStorage('cLocation', res);
				console.log(res, "789")
				suss.call(this, res);
			},
			fail: function(res) {
				console.log("调用失败", res)
				suss.call(this, 2)
				// uni.hideLoading();
			}
		})
	}, () => {
		// uni.hideLoading();
		console.log("取消")
		suss.call(this, 1)
	});
	// #endif

	// #ifdef H5
	uni.getLocation({
		type: 'gcj02',
		isHighAccuracy: true,
		success: function(res) {
			console.log("缓存当前位置的经纬度>>>>>>>", res)
			//缓存当前位置的经纬度
			setStorage('cLocation', res);
			suss.call(this, res, "789");
		},
		fail: function(res) {
			console.log("调用失败", res)
			suss.call(this, 2)
		}
	})
	// #endif
}

const scopeAddress = (success) => {
	authSetting('scope.address', () => {
		uni.chooseAddress({
			success: function(res) {
				success.call(this, res);
			},
		})
	}, () => {
		msg('未设置开放权限')
	});
}

const isAuth = () => {
	const user = getStorage('userInfo');
	return user && user.id;
}

// 去掉字符串中的特殊字符和转义字符
const excludeSpecial = (s) => {
	// 去掉转义字符
	//  s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');

	const pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""' + - - _ % 。，、？\s]/g;
	if (s != undefined || s != null) {
		s = s.replace(pattern, "")
	}
	return s;
}

const checkWXJs = (id, payJson, payType, success) => {
	var url = window.location.href;
	console.log('当前URL地址数据====', url);
	getRequest('/api/getWeiXinJsApiInfo', {
			url: url
		}, res => {
			jWeixin.config({
				debug: false, // 开启调试模式
				appId: res.appId, // 必填，公众号的唯一标识
				timestamp: res.timestamp, // 必填，生成签名的时间戳
				nonceStr: res.nonceStr, // 必填，生成签名的随机串
				signature: res.signature, // 必填，签名
				jsApiList: [
					'chooseWXPay', //
				]
			});
			jWeixin.ready(function() {
				jWeixin.chooseWXPay({
					timestamp: payJson
						.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					nonceStr: payJson.nonceStr, // 支付签名随机串，不长于 32 位
					package: payJson.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
					signType: payJson.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
					paySign: payJson.sign, // 支付签名
					success: function(res) {
						console.log('支付成功')
						// 支付成功后的回调函数
						try {
							let i = 0;
							let timer = setInterval(() => {
								postRequest('/api/order/check', {
									id: id
								}, res => {
									console.log(i)
									if (res.isSuccess || i === 5) {
										clearInterval(timer);
										uni.hideLoading();
										success.call(this, res.isSuccess);
									} else {
										i++;
									}
								}, true)
							}, 500);
						} catch (e) {
							uni.hideLoading();
						}
					},
					fail: function(res) {
						uni.hideLoading();
						console.log('支付失败', res)
						postRequest('/api/order/cancelPay', {
							id: id
						}, data => {
							if (payType == 'activity') {

							} else {
								uni.redirectTo({
									url: '/mine/orderDet/orderDet?id=' + id,
								})
							}
						})
					}
				});
			});
		},
		true
	);
}
// 获取用户行为操作
const getBehavior = (id, behavior, type, success) => {
	let params = {
		bindId: id,
		behavior: behavior,
		type: type
	}
	getRequest('/api/v3/behavior/have', params, res => {
		success.call(this, res)
	})
}
// 获取用户行为操作数量
const getBehaviorCount = (id, behavior, type, success) => {
	let params = {
		bindId: id,
		behavior: behavior,
		type: type
	}
	getRequest('/api/v3/behavior/count', params, res => {
		success.call(this, res)
	})
}

//格式化时间
const dateFormat = (dat)=>{
	var dat = new Date(dat)
    //获取年月日，时间
    var year = dat.getFullYear();
    var mon = (dat.getMonth()+1) < 10 ? "0"+(dat.getMonth()+1) : dat.getMonth()+1;
    var data = dat.getDate()  < 10 ? "0"+(dat.getDate()) : dat.getDate();
    var hour = dat.getHours()  < 10 ? "0"+(dat.getHours()) : dat.getHours();
    var min =  dat.getMinutes()  < 10 ? "0"+(dat.getMinutes()) : dat.getMinutes();
    var seon = dat.getSeconds() < 10 ? "0"+(dat.getSeconds()) : dat.getSeconds();
	
	var a = new Array("日", "一", "二", "三", "四", "五", "六");  
	var week = dat.getDay();  
	var str = "星期"+ a[week]; 
	
	// 获取当前小时
    var hours = dat.getHours();
    // 设置默认文字
    var text = ``;
	console.log(hours)
    // 判断当前时间段
    if (hours >= 0 && hours <= 9) {
        text = `早上`;
    } else if (hours > 9 && hours <= 13) {
        text = `中午`;
    } else if (hours > 13 && hours <= 17) {
        text = `下午`;
    } else if (hours > 17 && hours <= 24) {
        text = `晚上`;
    }
		
    var newDate = {
		v1:year +"-"+ mon +"-"+ data +" "+ hour +":"+ min +":"+ seon,
		v2:year +"/"+ mon +"/"+ data +" "+ hour +":"+ min +":"+ seon,
		v3:year +"/"+ mon +"/"+ data,
		v4:year +"年"+ mon +"月"+ data +"日",
		v5:year +"-"+ mon +"-"+ data,
		week:str,
		text:text
	};
    return newDate;
}

module.exports = {
	setStorage: setStorage,
	getStorage: getStorage,
	postRequest: postRequest,
	postRequestLoding: postRequestLoding,
	getRequest: getRequest,
	putRequest: putRequest,
	putRequestJson: putRequestJson,
	msg: msg,
	g: g,
	p: p,
	env: env,
	send: send,
	redirectIndex: redirectIndex,
	saveImage: saveImage,
	saveImageToPhotosAlbum: saveImageToPhotosAlbum,
	uploadFile: uploadFile,
	msgConfirm: msgConfirm,
	getConfig: getConfig,
	load: load,
	isLogin: isLogin,
	isLogins: isLogins,
	payOrder: payOrder,
	getLocation: getLocation,
	scopeAddress: scopeAddress,
	isAuth: isAuth,
	alertMsg: alertMsg,
	getToken: getToken,
	loadIng: loadIng,
	removeStorage: removeStorage,
	public: publicss,
	header: header,
	excludeSpecial: excludeSpecial,
	msgConfirmText: msgConfirmText,
	isWeixin: isWeixin,
	checkWXJs: checkWXJs,
	getBehavior: getBehavior,
	getBehaviorCount: getBehaviorCount,
	outLogin: outLogin,
	dateFormat:dateFormat
}
