import Md5 from "js-md5"
// import { get_xs } from '@/static/xhs.js'

const resolveRVHandler = (response) => {
	// if(response.header && response.header['r-v']){
	// 	uni.setStorageSync("r-v",response.header['r-v'])
	// }
}

const getRVHandler = (payload, token) => {
	// if(uni.getStorageSync("r-v")){
	// 	let a1 =uni.getStorageSync("r-v")
	// 	let xs = get_xs(payload, a1,token)
	// 	if(xs && xs !=''){
	// 		console.log(xs)
	// 		return xs
	// 	}
	// }
	return ''
}

export default {
	install(Vue, options) {
		Vue.prototype.host = "https://wx.weibaoge.cn/web/index.php?_mall_id=1285"
		// "http://192.168.5.204:8030"
		Vue.prototype.host2 = process.env.NODE_ENV=="development"?"https://erpmallapi.oytour.com":"https://erpmallapi.oytour.com"
		Vue.prototype.host3 = process.env.NODE_ENV=="development"?"http://192.168.5.204:8030":"https://reborn.oytour.com"
		Vue.prototype.hostErpUpload = process.env.NODE_ENV=="development"?"https://upload.oytour.com":"https://upload.oytour.com"
		Vue.prototype.hostErpFile = process.env.NODE_ENV=="development"?"https://imgfile.oytour.com":"https://imgfile.oytour.com"
		// Vue.prototype.host3 = "http://192.168.5.204:8030"
		// Vue.prototype.host3 = "https://reborn.oytour.com"
		// "http://192.168.5.204:8030":
		console.log()

		Vue.prototype.request = function(param, success, failed) {
			//网络请求
			uni.request({
				url: this.host + "&r=" + param.data.r,
				method: param.method || "GET",
				header: param.header || {
					'content-type': "application/json"
				},
				data: param.data,
				success: res => {
					if (res.data.code != 0 && res.data.msg != "商品未上架") {}
					typeof success == "function" && success(res.data);
				},
				fail: (e) => {
					console.log("网络请求fail:" + JSON.stringify(e));
					uni.showModal({
						content: "" + res.errMsg
					});
					typeof failed == "function" && failed(res.data);
				}
			});
		}
		Vue.prototype.request2 = function(param, success, failed) {
			let data = {
				MallBaseId: this.GetMiniAppId().MallBaseId,
				TenantId: this.GetMiniAppId().TenantId,
				OpenId: this.GetOpenId().OpenId,
				UserId: this.GetOpenId().UserId,
				SmallShopsId: this.GetOpenId().SmallShopsId,
				MiniAppId: this.GetMiniAppId().AppId,
				msg: param.data,
				token: this.GetOpenId().token
			}
			//['X-s']
			const sign = getRVHandler(data, this.GetOpenId().token)
			//网络请求
			uni.request({
				url: this.host2 + param.url,
				method: param.method || "Post",
				header: param.header || {
					'content-type': "application/json",
					'x-sign': sign["X-s"],
					'x-ts': sign["X-t"]
				},
				data,
				success: res => {
					resolveRVHandler(res)
					if (res.data.resultCode == 10000) {
						let u = uni.getStorageSync("mall_UserInfo");
						if (u) {
							this.getLogin_t(u)
							typeof failed == "function" && failed(res.data);
						}
					} else if (res.data.resultCode != 1) {
						if (res.data.message != '') {
							uni.showToast({
								title: res.data.message,
								icon: "none",
							});
						}
						typeof failed == "function" && failed(res.data);
					} else {
						typeof success == "function" && success(res.data);
					}
				},
				fail: (e) => {
					console.log("网络请求fail:" + JSON.stringify(e));
					uni.showModal({
						content: "" + res.errMsg
					});
					typeof failed == "function" && failed(res.data);
				}
			});
		}

		//请求app接口
		Vue.prototype.apipost = function(cmd, msg, success, failed) {
				var data = this.GetPostData(cmd, msg, "");
				//['X-s']
				const sign = getRVHandler(data, data.token)
				uni.request({
					url: this.host3 + '/api/common/post',
					method: "Post",
					header: {
						'Content-Type': 'application/json',
					},
					data,
					success: res => {
						resolveRVHandler(res)
						if (res.data.resultCode == 10000 || res.data.resultCode == 10001) {
							uni.removeStorageSync('b2b_user')
							uni.removeStorageSync('mall_UserInfo')
							const pages = getCurrentPages()
							const curPage = pages[pages.length-1]
							if(cmd=='b2b_post_CheckMiniAppToken'){
								// curPage.onLoad(curPage.options)
								curPage.onShow()
								// curPage.onReady()
							}else{
								console.log(uni.getStorageSync("LoginState"),'---log')
								if(uni.getStorageSync("LoginState")) {
									uni.removeStorageSync("LoginState")
									return
								}
								uni.setStorageSync("LoginState",true)
								setTimeout(()=>{
									uni.redirectTo({
										url: '/pages/index/index'
									})
								},1000)
							}
						} else if (res.data.resultCode != 1) {
							if (!failed) {
								if (res.data.message != '') {
									uni.showToast({
										title: res.data.message,
										icon: "none",
									});
								}
							}
							typeof failed == "function" && failed(res.data);
						} else {
							typeof success == "function" && success(res.data);
						}
					},
					fail: (e) => {
						console.log("网络请求fail:" + JSON.stringify(e));
						uni.showModal({
							content: "" + res.errMsg
						});
						typeof failed == "function" && failed(res.data);
					}
				})
			},
		Vue.prototype.apipostQrCode = function(cmd, msg, success, failed) {
			var data = this.GetPostData(cmd, msg, "");
			//['X-s']
			const sign = getRVHandler(data, data.token)
			uni.request({
				url: this.host3 + '/api/file/GetGuestSurvey',
				method: "Post",
				header: {
					'Content-Type': 'application/json',
				},
				data,
				success: res => {
					resolveRVHandler(res)
					if (res.data.resultCode == 10000 || res.data.resultCode == 10001) {
						uni.removeStorageSync('b2b_user')
						uni.removeStorageSync('mall_UserInfo')
						const pages = getCurrentPages()
						const curPage = pages[pages.length-1]
						if(cmd=='b2b_post_CheckMiniAppToken'){
							// curPage.onLoad(curPage.options)
							curPage.onShow()
							// curPage.onReady()
						}else{
							console.log(uni.getStorageSync("LoginState"),'---log')
							if(uni.getStorageSync("LoginState")) {
								uni.removeStorageSync("LoginState")
								return
							}
							uni.setStorageSync("LoginState",true)
							setTimeout(()=>{
								uni.redirectTo({
									url: '/pages/index/index'
								})
							},1000)
						}
					} else if (res.data.resultCode != 1) {
						if (!failed) {
							if (res.data.message != '') {
								uni.showToast({
									title: res.data.message,
									icon: "none",
								});
							}
						}
						typeof failed == "function" && failed(res.data);
					} else {
						typeof success == "function" && success(res.data);
					}
				},
				fail: (e) => {
					console.log("网络请求fail:" + JSON.stringify(e));
					uni.showModal({
						content: "" + res.errMsg
					});
					typeof failed == "function" && failed(res.data);
				}
			})
		},
			Vue.prototype.javaApipost = function(cmd, msg, success, failed) {
				let b2bUser = uni.getStorageSync('b2b_user')
				let token = "";
				let key = "";
				let groupId = 0
				let timestamp = (new Date()).valueOf();
				var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
				if (b2bUser && b2bUser.token) {
					token = b2bUser.token;
					key = b2bUser.secretKey;
					groupId = b2bUser.groupId;
				}
				var md5Str = Md5(`msg=${encodeMsg}&timestamp=${timestamp}&token=${token}&key=${key}`);
				var postData = {
					"groupId": groupId,
					"msg": msg,
					"timestamp": timestamp,
					"token": token,
					"sign": md5Str,
				}

				uni.request({
					url: 'https://efficient.oytour.com/api/' + cmd,
					method: "Post",
					header: {
						'Content-Type': 'application/json'
					},
					data: postData,
					success: res => {
						if (res.data.resultCode == 10000 || res.data.resultCode == 10001) {
							uni.removeStorageSync('b2b_user')
							uni.removeStorageSync('mall_UserInfo')
							// uni.redirectTo({
							// 	url: '/pages/jiuzhai/login'
							// })
							uni.redirectTo({
								url: '/pages/index/index'
							})
						} else if (res.data.resultCode != 1) {
							if (res.data.message != '') {
								uni.showToast({
									title: res.data.message,
									icon: "none",
								});
							}
							typeof failed == "function" && failed(res.data);
						} else {
							typeof success == "function" && success(res.data);
						}
					},
					fail: (e) => {
						console.log("网络请求fail:" + JSON.stringify(e));
						uni.showModal({
							content: "" + res.errMsg
						});
						typeof failed == "function" && failed(res.data);
					}
				})
			},
			Vue.prototype.apipostDownload = function(cmd, msg, success, failed) {
				var postData = this.GetPostData(cmd, msg, "");
				uni.request({
					url: this.host3 + '/api/file/' + cmd,
					method: "Post",
					header: {
						'Content-Type': 'application/json'
					},
					data: postData,
					success: res => {
						if (res.data.resultCode == 10000) {
							let u = uni.getStorageSync("mall_UserInfo");
							if (u) {
								this.getLogin_t(u)
								typeof failed == "function" && failed(res.data);
							}
						} else if (res.data.resultCode != 1) {
							if (res.data.message != '') {
								uni.showToast({
									title: res.data.message,
									icon: "none",
								});
							}
							typeof failed == "function" && failed(res.data);
						} else {
							typeof success == "function" && success(res.data);
						}
					},
					fail: (e) => {
						console.log("网络请求fail:" + JSON.stringify(e));
						uni.showModal({
							content: "" + res.errMsg
						});
						typeof failed == "function" && failed(res.data);
					}
				})
			},

			//获取请求参数
			Vue.prototype.GetPostData = function(cmd, msg) {
				if (msg == null || msg == "") {
					msg = {}
				}
				let b2bUser = uni.getStorageSync('b2b_user')
				let token = b2bUser.token;
				let key = ""
				let groupId = ''
				let timestamp = (new Date()).valueOf();
				if (b2bUser && b2bUser.token) {
					token = b2bUser.token
					key = b2bUser.secretKey
				}
				if (b2bUser) {
					groupId = b2bUser.groupId
				}
				var encodeMsg = encodeURIComponent(JSON.stringify(msg)).toLowerCase();
				var postData = {
					"groupId": groupId,
					"msg": msg,
					"cmd": cmd,
					"timestamp": timestamp,
					"token": token,
					"sign": '',
					"locale": 'zh_CN',
					"currencyCode": 'CNY',
					version: 'MiniProgram'
				}
				return postData
			},
			// token失效再次登录接口
			Vue.prototype.getLogin_t = function(obj) {
				console.log('apijs', obj)
				let pid = uni.getStorageSync("pid") ? uni.getStorageSync("pid").pid : 0;
				let Up = uni.getStorageSync("Up") ? uni.getStorageSync("Up").Up : 0;
				let SmallShopId = uni.getStorageSync("SmallShopId") ? uni.getStorageSync("SmallShopId").SmallShopId : 0;
				let CounponPassword = uni.getStorageSync("CounponPassword") ? uni.getStorageSync("CounponPassword").CounponPassword :
					0;
				let KeyWord = uni.getStorageSync("KeyWord") ? uni.getStorageSync("KeyWord").KeyWord : '';
				this.request2({
						url: '/api/AppletLogin/Login',
						data: {
							Source: obj.Source,
							OpenId: obj.OpenId,
							Name: obj.Name,
							Photo: obj.Photo,
							Moblie: '',
							SuperiorId: pid,
							SmallShopId: SmallShopId,
							UserPageType: Up,
							CounponPassword: CounponPassword,
							KeyWord: KeyWord,
						}
					},
					res => {
						if (res.resultCode == 1) {
							uni.setStorageSync('mall_UserInfo', res.data);
							uni.removeStorageSync('pid');
							uni.removeStorageSync('SmallShopId');
							uni.removeStorageSync("Up");
							uni.removeStorageSync("CounponPassword");
							uni.removeStorageSync("KeyWord");
						}
					}
				);
			}
		// 获取小程序APPID
		Vue.prototype.GetMiniAppId = function() {
			let appObj = {};
			let appType = 2;
			// #ifdef MP-DI
			appObj = {
				AppId: 'wx5564525562e92ddb',
				TenantId: 29,
				MallBaseId: 19,
			};
			// #endif
			
			// #ifdef MP-AG
			appObj = {
				AppId: 'wxcf0727a7c78b501e',
				TenantId: 12,
				MallBaseId: 2,
			};
			// #endif
			
			return appObj;
		}
		//获取OpenId
		Vue.prototype.GetOpenId = function() {
			let mall_userinfo = wx.getStorageSync('mall_UserInfo')
			var obj = {
				OpenId: '',
				UserId: 0,
				token: '',
				SmallShopsId: 0,
			}
			if (mall_userinfo) {
				if (mall_userinfo.OpenId) {
					obj.OpenId = mall_userinfo.OpenId;
					obj.UserId = mall_userinfo.UserId;
					obj.token = mall_userinfo.Token;
					obj.SmallShopsId = mall_userinfo.UserSmallShopId;
				}
			}
			return obj
		}
		//公用判断图片地址 判断是否包含http
		Vue.prototype.getIconLink = function(url) {
			let str = ''
			if (url && url != '') {
				if (url.indexOf('http') != -1) {
					str = url
				} else {
					str = 'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com' + url;
				}
				return str;
			}
		}
		//价格返回.00
		Vue.prototype.getPrice = function(val) {
			val = Number(val).toFixed(2);
			return val
		}

		Vue.prototype.apiheader = function() {
			return {
				'X-Access-Token': '_4Y_WpUZ4a6SI5uJgsZ4Lb7t9mvqJTyr',
				'X-App-Platform': 'wxapp',
				'X-App-Version': '4.2.47',
				'X-Form-Id-List': '[]',
				'X-Requested-With': 'XMLHttpRequest',
				'X-User-Id': '19992',
				'content-type': "application/json"
			}
		}
	}
}
