import store from '../store/index.js'
import qs from 'qs'
// const gatewayUrl = "http://192.168.1.105:8082/";
const gatewayUrl = "https://kptyun.cn/";
var requestTask = null

function checkStatus(response) {
	// console.log(response)
	if (response.data.code == "1000000009" || response.data.code == "1000000010") {
		store.commit('logout')
		//#ifndef H5
		uni.showModal({
			title: '提示',
			content: '登录失效，请重新登录',
			cancelText: "暂不登录",
			confirmText: "去登录",
			success(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/login/login',
					})
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})
		//#endif
		//#ifdef H5
		//alert("aaaa")
		// window.location.reload()
		if (util.isWeiXin()) {
			let baseUrl = "https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect";
			let redirectUri = util.appendParams(baseUrl, {
			    'appid': 'wx63ae87efa44fc305',
			    'redirect_uri': encodeURIComponent(window.location.href),
			    'response_type': 'code',
			    'scope': 'snsapi_userinfo',
			    'state': 'hello-world',
			});
			 window.location.replace(redirectUri);
			// const url =
			// 	'https://pailiying.com/livephoto/livephoto/getwxcode.html?appid=wx63ae87efa44fc305&scope=snsapi_userinfo&state=hello-world&redirect_uri=' +
			// 	encodeURI(window.location.href)
			// window.location.replace(url);
		}
		//#endif
	}
	// loading
	// 如果http状态码正常，则直接返回数据
	if (response && (response.statusCode === 200)) {
		return response.data;
	} else {
		// uni.showToast({
		// 	icon: "none",
		// 	mask: true,
		// 	title: "网络异常，请稍后再试"
		// })
	}
}


function checkCode(res) {
	// 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
	// uni.showToast({
	// 	icon: "none",
	// 	mask: true,
	// 	title: "网络异常，请稍后再试"
	// })
}
let util = {
	gatewayUrl: gatewayUrl,
	postForm(url, data, header) {
		let _url = '';
		if (url.indexOf('http://') != -1) {
			_url = url
		} else {
			_url = gatewayUrl + url
		}
		const headers = header || {};
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'post',
				url: _url,
				data: qs.stringify(data),
				header: {
					...headers,
					'X-Requested-With': 'XMLHttpRequest',
					'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
					"token": uni.getStorageSync("userInfo") ? uni.getStorageSync("userInfo").token :
						""
				},
				success: (res => {
					resolve(checkStatus(res))

				}),
				fail: (res => {
					reject(checkCode(res))
				})
			})
		})
	},
	postJson(url, data, header) {
		let _url = '';
		if(requestTask && url=='/pailiying-user/v1/user/getPhotoLiveImgList'){
			requestTask.abort()
			requestTask = null
		}
		if (url.indexOf('http://') != -1) {
			_url = url
		} else {
			_url = gatewayUrl + url
		}
		const headers = header || {};
		// console.log(uni.getStorageSync("userInfo"))
		return new Promise((resolve, reject) => {
		requestTask = uni.request({
				method: 'post',
				url: _url,
				data, // post 请求时带的参数
				header: Object.assign({
					'X-Requested-With': 'XMLHttpRequest',
					'content-type': 'application/json; charset=UTF-8',
					"token": uni.getStorageSync("userInfo") ? uni.getStorageSync("userInfo")
						.token : ""
				}, headers),
				success: (res => {
					requestTask = null
					resolve(checkStatus(res))
				}),
				fail: (res => {
					requestTask = null
					reject(checkCode(res))
				})
			})
		})
	},
	get(url, data, header) {
		let _url = '';
		if (url.indexOf('/api/') != -1) {
			_url = url
		} else {
			_url = gatewayUrl + url
		}
		const headers = header || {};
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'get',
				url: _url,
				data, // get 请求时带的参数
				header: Object.assign({
					'X-Requested-With': 'XMLHttpRequest',
					'Accept': 'application/json, text/plain, */*',
					'content-type': ' ',
					"token": uni.getStorageSync("userInfo") ? uni.getStorageSync(
						"userInfo").token : ""
				}, headers),
				success: (res => {
					resolve(checkStatus(res))
				}),
				fail: (res => {
					reject(checkCode(res))
				})
			})
		})
	},

	combineFromParamForNull: (param, needFormStyle) => { //组合参数
		const params = {};
		for (var i in param) {
			if (param[i] != null && param[i] != 'null') {
				params[i] = param[i]
			}
		}
		return params
	},


	getLocalTime(time) { //将时间错转化成2010-10-20 10:00:00
		const now = new Date(time)
		const year = now.getFullYear();
		var month = now.getMonth() + 1;
		if (month < 10) month = "0" + month;
		var date = now.getDate();
		if (date < 10) date = "0" + date;
		var hour = now.getHours();
		if (hour < 10) hour = "0" + hour;
		var minute = now.getMinutes();
		if (minute < 10) minute = "0" + minute;
		var second = now.getSeconds();
		if (second < 10) second = "0" + second;
		return year + "-" + month + "-" + date + "   " + hour + ":" + minute + ":" + second;
	},
	getLocalTime2(time) { //将时间错转化成2010-10-20
		const now = new Date(time)
		const year = now.getFullYear();
		var month = now.getMonth() + 1;
		if (month < 10) month = "0" + month;
		var date = now.getDate();
		if (date < 10) date = "0" + date;
		return year + "-" + month + "-" + date
	},
	getLocalTime3(time) { //将时间错转化成 10:00:00
		const now = new Date(time)
		const year = now.getFullYear();
		var month = now.getMonth() + 1;
		if (month < 10) month = "0" + month;
		var date = now.getDate();
		if (date < 10) date = "0" + date;
		var hour = now.getHours();
		if (hour < 10) hour = "0" + hour;
		var minute = now.getMinutes();
		if (minute < 10) minute = "0" + minute;
		var second = now.getSeconds();
		if (second < 10) second = "0" + second;
		return hour + ":" + minute + ":" + second;
	},
	getLocalTime4(time) { //将时间错转化成 10:00
		const now = new Date(time)
		const year = now.getFullYear();
		var month = now.getMonth() + 1;
		if (month < 10) month = "0" + month;
		var date = now.getDate();
		if (date < 10) date = "0" + date;
		var hour = now.getHours();
		if (hour < 10) hour = "0" + hour;
		var minute = now.getMinutes();
		if (minute < 10) minute = "0" + minute;
		var second = now.getSeconds();
		if (second < 10) second = "0" + second;
		return minute + ":" + second;
	},
	isWeiXin() {
		let ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
	},
	isAlipay() {
		let userAgent = navigator.userAgent.toLowerCase();
		if (userAgent.match(/Alipay/i) == "alipay") {
			return true;
		} else {
			return false;
		}
	},

	gethtml(value) {
		if (value) {
			let a = value.replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig,
					'<img$1 style="max-width:100%;height:auto;float:none;display:block;')
				.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
				.replace(/<p>/ig, '<p style="font-size: 15Px; line-height: 25Px;">')
				.replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1 ')
				.replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1 ')
				.replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
				.replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1 "');
			return a
		} else {
			return ""
		}

	},
	//登录校验
	checkLogin(callback) {
		let userInfo = uni.getStorageSync('userInfo') || '';
		if (userInfo.token) {
			callback()
		} else {
			// #ifdef H5
			if (this.isWeiXin()) {
				// h5_address
				console.log('h5_address==>',uni.getStorageSync("h5_address"))
				// const url = 'https://pailiying.com/livephoto/getwxcode.html?appid=wx63ae87efa44fc305&scope=snsapi_userinfo&state=hello-world&redirect_uri=' + encodeURI(window.location.href)
				const url = uni.getStorageSync("h5_address") + '/getwxcode.html?appid=wx63ae87efa44fc305&scope=snsapi_userinfo&state=hello-world&redirect_uri=' + encodeURI(window.location.href)
				window.location.replace(url);
			}
			// #endif
		}
	},


	payorder(aa, callback) {
		let that = this
		let msg = aa
		// #ifdef H5
		if (that.isWeiXin()) {
			that.postJson(msg.url, that.combineFromParamForNull(msg.parms)).then(function(res) {
					uni.hideLoading()
					if (res.status == 1) {



						uni.showLoading({
							title: '正在支付',
							mask: true
						})
						if (typeof WeixinJSBridge == "undefined") {
							if (document.addEventListener) {
								document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady(res.data,
									callback), false);
							} else if (document.attachEvent) {
								document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady(res.data,
									callback));
								document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady(res.data,
									callback));
							}
						} else {

							that.onBridgeReady(res.data, callback);
						}

					} else {

						uni.showModal({
							title: '',
							content: "付款失败",
							showCancel: false,
						})
					}
				},
				function(fail) {
					uni.hideLoading()
					uni.showToast({
						title: "付款失败",
						icon: "none"
					})
				}
			)



		} else if (utils.isAlipay()) {
			parms.payType = 2
			utils.postJson(url, utils.combineFromParamForNull(parms), {}).then(function(res) {
					uni.hideLoading()
					if (res.status == '0') {

						if (typeof(res.data) === 'string') {
							that.tradeNO = JSON.parse(res.data).tradeNO;
						} else {
							that.tradeNO = res.data.tradeNo;
						}


						if (res.data.code_url) {
							// uni.navigateTo({
							// 	url: "../webview/webview?urls=" + res.data.code_url
							// })
						} else {
							uni.showLoading({
								title: '正在跳转支付宝支付',
								mask: true
							})
							if (window.AlipayJSBridge) {
								that.onAliBridgeReady && that.onAliBridgeReady();
							} else {
								// 如果没有注入则监听注入的事件
								document.addEventListener('AlipayJSBridgeReady', that.onAliBridgeReady, false);
							}
						}
					} else {
						that.$api.msg(res.msg);
						uni.showModal({
							title: '',
							content: "付款失败",
							showCancel: false,
						})
					}
				},
				function(fail) {
					uni.hideLoading()
					that.$api.msg(fail);
				}
			)
		} else {
			alert("请在支付宝或者微信中扫码")
		}
		// #endif


		//#ifdef MP-WEIXIN

		that.postJson(msg.url, that.combineFromParamForNull(msg.parms),
			msg.heard
		).then(function(res) {
				uni.hideLoading()
				if (res.code == '0000') {
					uni.showLoading({
						title: '正在跳转微信支付',
						mask: true
					})
					const payParam = {
						appId: res.data.appId,
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						timeStamp: res.data.timeStamp + "",
						signType: res.data.signType,
						paySign: res.data.paySign,
					}
					uni.requestPayment({
						provider: 'wxpay',
						//#ifdef MP-WEIXIN
						...payParam,
						//#endif
						//#ifdef APP-PLUS
						orderInfo: payParam,
						//#endif
						success: function(resq) {
							callback()
						},
						fail: function(fails) {
							uni.hideLoading()
							uni.showToast({
								title: "付款失败",
								icon: "none"
							})
							console.log("支付过程失败", fails);
							// that.$api.msg(JSON.stringify(fails))

						},
						complete: function(res) {
							uni.hideLoading()
							console.log("支付过程结束")
						}
					});


				} else {

					uni.showModal({
						title: '',
						content: "付款失败",
						showCancel: false,
					})
				}
			},
			function(fail) {
				uni.hideLoading()
				that.$api.msg(fail);
			}
		)

		//#endif

	},


	onAliBridgeReady() { //唤起支付宝支付
		const me = this;

		AlipayJSBridge.call("tradePay", {
			tradeNO: me.tradeNO
		}, function(res) {
			if (res.resultCode == 9000) {
				uni.redirectTo({
					url: "/pages/shopSuccess/shopSuccess"
				})
			} else {
				uni.showModal({
					title: '',
					content: "付款失败",
					showCancel: false,
				})
			}
		});
	},
	appendParams(url, params) {
		if (params) {
			var baseWithSearch = url.split('#')[0];
			var hash = url.split('#')[1];
			for (var key in params) {
				var attrValue = params[key];
				if (attrValue !== undefined) {
					var newParam = key + "=" + attrValue;
					if (baseWithSearch.indexOf('?') > 0) {
						var oldParamReg = new RegExp('^' + key + '=[-%.!~*\'\(\)\\w]*', 'g');
						if (oldParamReg.test(baseWithSearch)) {
							baseWithSearch = baseWithSearch.replace(oldParamReg, newParam);
						} else {
							baseWithSearch += "&" + newParam;
						}
					} else {
						baseWithSearch += "?" + newParam;
					}
				}
			}

			if (hash) {
				url = baseWithSearch + '#' + hash;
			} else {
				url = baseWithSearch;
			}
		}
		return url;
	},

	onBridgeReady(datas, callback) { //唤起微信支付
		const me = this;
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				"appId": datas.appId,
				"nonceStr": datas.nonceStr,
				"package": datas.package,
				"paySign": datas.paySign,
				"signType": datas.signType,
				"timeStamp": datas.timeStamp
			},
			function(res) {
				alert(JSON.stringify(res))
				uni.hideLoading();
				if (res.err_msg ==
					"get_brand_wcpay_request:ok") { // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
					callback()
				} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
					uni.showModal({
						title: '',
						content: "付款失败",
						showCancel: false,
					})
				} else if (res.err_msg == "get_brand_wcpay_request:fail") {
					uni.showModal({
						title: '',
						content: "付款失败",
						showCancel: false,
					})
				} else {
					uni.showModal({
						title: '',
						content: "付款失败",
						showCancel: false,
					})
				}
			}
		)
	},
	//校验手机号
	checkphone(n) {
		var myreg =
			/^(((14[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(13[0-9]{1})|(19[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
		if (n && myreg.test(n)) {
			return true
		} else {
			return false
		}
	},
	//正整数校验
	checkNumber(n) {
		var myreg = /(^[1-9]\d*$)/;
		if (n && myreg.test(n)) {
			return true
		} else {
			return false
		}
	},
	// 校验金额
	checkMoney(n) {
		var myreg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{1,2}$)/;
		if (n && myreg.test(n)) {
			return true
		} else {
			return false
		}
	},
	// 不为空校验
	checkstr(n) {
		var myreg = /\S/;
		if (n && myreg.test(n)) {
			return true
		} else {
			return false
		}
	},
	checkPwd(n) { //校验密码6-16位至少有一个数字字母
		var myreg =
			/^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![,\!@$.#%\'\+\*\-:;^_`]+$)[,\!@$.#%\'\+\*\-:;^_`0-9A-Za-z]{6,16}$/;
		if (n && myreg.test(n)) {
			return true
		} else {
			return false
		}
	},

	Base64() {
	        // 私钥
	        let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	        // 加密
	        this.encode = function (input) {
	                var output = "";
	                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	                var i = 0;
	                input = _utf8_encode(input);
	                while (i < input.length) {
	                        chr1 = input.charCodeAt(i++);
	                        chr2 = input.charCodeAt(i++);
	                        chr3 = input.charCodeAt(i++);
	                        enc1 = chr1 >> 2;
	                        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	                        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	                        enc4 = chr3 & 63;
	                        if (isNaN(chr2)) {
	                                enc3 = enc4 = 64;
	                        } else if (isNaN(chr3)) {
	                                enc4 = 64;
	                        }
	                        output = output +
	                            _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
	                            _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
	                }
	                return output;
	        }
	        // 解密
	        this.decode =  (input)=> {
	                var output = "";
	                var chr1, chr2, chr3;
	                var enc1, enc2, enc3, enc4;
	                var i = 0;
	                if (input==undefined||input==null){
	
	                }else {
	                        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	                        while (i < input.length) {
	                                enc1 = _keyStr.indexOf(input.charAt(i++));
	                                enc2 = _keyStr.indexOf(input.charAt(i++));
	                                enc3 = _keyStr.indexOf(input.charAt(i++));
	                                enc4 = _keyStr.indexOf(input.charAt(i++));
	                                chr1 = (enc1 << 2) | (enc2 >> 4);
	                                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	                                chr3 = ((enc3 & 3) << 6) | enc4;
	                                output = output + String.fromCharCode(chr1);
	                                if (enc3 != 64) {
	                                        output = output + String.fromCharCode(chr2);
	                                }
	                                if (enc4 != 64) {
	                                        output = output + String.fromCharCode(chr3);
	                                }
	                        }
	                        output = _utf8_decode(output);
	                        return output;
	                }
	
	        }
	        // private method for UTF-8 encoding
	        let _utf8_encode =  (string)=> {
	                string = string.replace(/\r\n/g,"\n");
	                var utftext = "";
	                for (var n = 0; n < string.length; n++) {
	                        var c = string.charCodeAt(n);
	                        if (c < 128) {
	                                utftext += String.fromCharCode(c);
	                        } else if((c > 127) && (c < 2048)) {
	                                utftext += String.fromCharCode((c >> 6) | 192);
	                                utftext += String.fromCharCode((c & 63) | 128);
	                        } else {
	                                utftext += String.fromCharCode((c >> 12) | 224);
	                                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	                                utftext += String.fromCharCode((c & 63) | 128);
	                        }
	                }
	                return utftext;
	        }
	        // private method for UTF-8 decoding
	        let _utf8_decode = (utftext)=> {
	                var string = "";
	                var i = 0;
	                var c = c1 = c2 = 0;
	                var c1 = 0;
	                var c2 = 0;
	                var c3 = 0;
	                while ( i < utftext.length ) {
	                        c = utftext.charCodeAt(i);
	                        if (c < 128) {
	                                string += String.fromCharCode(c);
	                                i++;
	                        } else if((c > 191) && (c < 224)) {
	                                c2 = utftext.charCodeAt(i+1);
	                                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	                                i += 2;
	                        } else {
	                                c2 = utftext.charCodeAt(i+1);
	                                c3 = utftext.charCodeAt(i+2);
	                                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	                                i += 3;
	                        }
	                }
	                return string;
	        }
	},




	promisify: api => {
		return (options, ...params) => {
			return new Promise((resolve, reject) => {
				const extras = {
					success: resolve,
					fail: reject
				}
				api({
					...options,
					...extras
				}, ...params)
			})
		}
	}
};

export default util;
