import {
	host
} from '../Gdata'
import {
	router_list
} from '../config'

const gdata = getApp().globalData
export const getRouter = function() {
	var pages = getCurrentPages() //获取加载的页面
	var currentPage = pages[pages.length - 1] //获取当前页面的对象
	let id = ''
	router_list.forEach(item => {
		if (item.router_name == currentPage.route) {
			id = item.id
		}
	})
	return id
}
export const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

export const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : `0${n}`
}

export const httpUtil = (url, method, data, isLoading = true) => {
	if (isLoading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	return new Promise(function(resolve, reject) {
		wx.request({
			url: host + url,
			data: data,
			method: method,
			// header: { "Content-Type": "application/x-www-form-urlencoded" },
			success: res => {
				if (isLoading) {
					wx.hideLoading();
				}
				if (200 == res.data.status) {
					resolve(res.data.data);
				} else {
					wx.showToast({
						title: '请求错误！',
						icon: 'none',
						duration: 1000
					})
				}
			},
			fail: res => {
				wx.hideLoading();
			}
		})
	})
}
export const http = (url, method, data, isLoading = true) => {
	if (isLoading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	return new Promise(function(resolve, reject) {
		let token = getApp().globalData.token
		let uid = getApp().globalData.uid

		let cps = wx.getStorageSync("cps") || null
		let header = []
		if (cps !== null && cps.vTime >= new Date().getTime()) {
			header = {
				'token': token,
				'uid': String(uid),
				'cps': cps.value
			}
		} else {
			header = {
				'token': token,
				'uid': String(uid)
			}
		}
		// if (token && uid) {
		wx.request({
			url: host + url,
			data: data,
			method: method,
			header,
			success: res => {
				if (isLoading) {
					wx.hideLoading();
				}
				if (200 == res.data.status) {
					resolve(res.data.data);
				} else if (401 == res.data.status || 402 == res.data.status || 403 == res.data
					.status) {
					reject("登录失效！")
					wx.showModal({
						title: '温馨提示',
						content: '未登录或信息过期，是否前往登录？',
						confirmText: '前往',
						success(res) {
							if (res.confirm) {
								getApp().globalData.gologin = true
								uni.removeStorageSync('userInfo');
								getApp().globalData.token = null;
								getApp().globalData.uid = null;
								getApp().globalData.userInfo = null;
								wx.switchTab({
									url: '/pages/user/user_index/user'
								})
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					})
				}
			},
			fail: res => {
				wx.hideLoading();
			}
		})
		// } else {
		//   wx.showToast({
		//     title: '未登录\r\n点击个人中心头像登录',
		//     icon: 'none',
		//     duration: 2000
		//   })
		// }

	})
}

export const getUserInfoUtil = async (e) => {
	uni.showLoading({
		title: '加载...',
		mask: true
	})
	// #ifdef MP-ALIPAY
	if (!uni.canIUse('getOpenUserInfo')) {
		uni.hideLoading();
		uni.showToast({
			title: '请手动授权用户信息权限'
		})
		return false
	}
	// #endif
	// #ifndef MP-BAIDU
	let userInfoRes = await uni.getUserProfile({
		desc: '展示用户信息'
	})
	if (userInfoRes && userInfoRes[1].errMsg === 'getUserProfile:ok') {
		let loginRes = await uni.login()
		uni.hideLoading();
		if (loginRes && loginRes[1].errMsg === 'login:ok') {
			return {
				code: loginRes[1].code,
				userInfo: userInfoRes[1].userInfo
			}
		} else {
			uni.showToast({
				title: '调用login失败'
			})
		}
	} else {
		uni.showToast({
			title: '调用用户信息失败'
		});
	}
	// #endif
	// #ifdef MP-BAIDU
	let loginRes = await uni.login()
	uni.hideLoading();
	if (loginRes && loginRes[1].code) {
		return {
			code: loginRes[1].code,
			userInfo: e.detail.userInfo
		}
	}
	// #endif

	uni.hideLoading();
	return false
}

export const tokenAndLogin = async (userInfo, code, encryptedData, iv) => {
	let getTokenUrl = '/api/v1/xhs/get-token'
	let loginUrl = '/api/v1/xhs/login'
	let res = await httpUtil(getTokenUrl, 'get', {
		code
	})
	if (!res||!res.token) {
		console.log('token获取异常！');
		return false
	}
	gdata.code = null;
	let data = {
		token: res.token,
		encryptedData
	}
	// #ifndef MP-ALIPAY
	data.iv = iv
	// #endif
	let res1 = await httpUtil(loginUrl, 'post', data)
	if (!res1) {
		return false
	}
	// #ifndef MP-ALIPAY
	userInfo.avatarUrl = userInfo.avatarUrl.replace("/132", "/0")
	// #endif
	wx.setStorageSync('userInfo', Object.assign(res1, userInfo))
	gdata.token = res1.token
	gdata.uid = res1.uid
	gdata.userInfo = userInfo
	return userInfo
}

export const logout = n => {
	return new Promise(function(resolve, reject) {
		http('/api/v1/logout', 'get').then(res => {
			uni.removeStorageSync('userInfo');
			gdata.token = null;
			gdata.uid = null;
			gdata.userInfo = null;
			resolve()
		}).catch(rej => {
			if (rej === "登录失效！") {
				resolve()
			}
		})
	})
}

export const login_check = n => {
	if (!getApp().globalData.token || !getApp().globalData.uid || "undefined" == typeof(getApp()
			.globalData
			.token) || "undefined" == typeof(getApp().globalData.uid)) {
		if (n == 1) {
			uni.showToast({
				title: '未登录',
				icon: 'none',
				duration: 2000,
				complete() {
					function gologin() {
						uni.navigateTo({
							url: '/pages/user/login/login',
						})
					}
					setTimeout(gologin, 2000);
				}
			})
		} else {
			uni.showModal({
				title: '温馨提示',
				content: '您还没有登录，是否前往登录？',
				confirmText: '前往',
				success(res) {
					if (res.confirm) {
						// getApp().globalData.gologin = true
						// wx.switchTab({
						//     url: '/pages/user/user_index/user'
						// })
						uni.navigateTo({
							url: '/pages/user/login/login',
						})
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		}
	} else {
		return true
	}
}

export const location_city = function() {
	let default_city = arguments[0]
	return new Promise(function(resolve, reject) {
		if (default_city == "beijing") {
			let longitude = 116.404368
			let latitude = 39.924338
			let map_type = 1
			// #ifdef MP-ALIPAY
			map_type = 2
			// #endif
			httpUtil("/api/v1/get-city", "get", {
				latitude,
				longitude,
				type: map_type
			}).then(res1 => {
				resolve(res1)
			})
		} else {
			uni.getLocation({
				// #ifndef MP-ALIPAY
				type: 'wgs84',
				// #endif

				success(res) {
					console.log(res);
					if (!res.longitude) {
						reject('定位未开启')
						setting()
						return
					}
					let map_type = 1
					// #ifdef MP-ALIPAY || MP-TOUTIAO
					map_type = 2
					// #endif
					// #ifdef MP-BAIDU
					map_type = 3
					// #endif
					httpUtil("/api/v1/get-city", "get", {
						longitude: res.longitude,
						latitude: res.latitude,
						type: map_type
					}).then(res1 => {
						resolve(res1)
					})
				},
				fail(res) {
					// reject('定位失败，下拉重试或点击选择城市')
					reject('定位未开启')
					setting()
				}
			})
		}
	})
}
export const setting = function() {
	wx.getSetting({ //先查看授权情况
		success: function(res) {
			var statu = res.authSetting;
			if (!statu['scope.userLocation']) { //判断是否授权，没有授权就提示下面的信息
				wx.showModal({
					// title: '需要获取您的地理位置，请确认授权定位，否则小程序功能将无法使用',
					title: '需要获取您的地理位置，请确认授权定位，当前定位为北京',
					cancelColor: '#666666',
					success: function(tip) {
						if (tip.confirm) { //查看是否点击确定
							wx.openSetting({ //打开设置
								success: function(data) {
									if (data.authSetting[
											"scope.userLocation"
										] ==
										true
									) { //到这一步表示打开了位置授权 
										// wx.reLaunch({
										//     url: '/pages/index/index/index',
										// })
										wx.navigateBack({
											delta: 0,
										})
									} else {
										// #ifndef MP-ALIPAY
										wx.showToast({
											title: '授权定位失败',
											icon: 'error',
											duration: 1000
										})
										// #endif
										// #ifdef MP-ALIPAY
										if (my.canIUse(
												'showAuthGuide'
											)) {
											my.showAuthGuide({
												authType: 'LBS',
												success: (
													res
												) => {
													// wx.reLaunch({
													//     url: '/pages/index/index/index',
													// })
												},
												fail: (
													error
												) => {},
											})
										} else {
											uni.showModal({
												title: '提示',
												content: '请手动打开设置,允许应用使用位置权限',
												showCancel: false
											})
										}
										// #endif
									}
								}
							})
						} else {
							// wx.showToast({
							// 	title: '重新进入小程序唤起定位授权',
							// 	icon: 'error',
							// 	duration: 1000
							// })
						}
					}
				})
			} else {
				//用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
				wx.showModal({
					title: '',
					showCancel: false,
					content: '请在系统设置中打开定位服务',
					confirmText: '确定',
					success: function(res) {}
				})
			}
		}
	})
}

export const orderSubmit = order_data => {
	return new Promise(function(resolve, reject) {
		// 订单来源：8->微信小程序、9->抖音小程序、10->支付宝小程序、13->小红书
		let order_type = 13
		order_data.order_type = order_type
		http('/api/v1/order-submit', 'post', order_data).then((res) => {
			let orderPayData = {}
			orderPay(orderPayData)
		});
	})
}

export const orderPay = orderPayData => {
	console.log(orderPayData); // 需要修改

	// #ifdef MP-WEIXIN
	wx.requestPayment({
		...orderPayData,
		success(res) {
			wx.showToast({
				title: '支付成功！',
				icon: 'success',
				duration: 1000
			})
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/my_order/my_order'
				});
			}, 500);
		},
		fail(res) {
			wx.showToast({
				title: '支付未成功',
				icon: 'error',
				duration: 2000
			});

			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/my_order/my_order'
				});
			}, 500);
		}
	});
	// #endif

	// #ifdef MP-TOUTIAO
	let orderInfo = orderPayData
	uni.pay({
		orderInfo,
		service: 5,
		success(res) {
			let title = ''
			let icon = ''
			switch (res.code) {
				case 0:
					title = '支付成功！';
					icon = 'success';
					break
				case 1:
					title = '支付超时！';
					icon = 'fail';
					break
				case 2:
					title = '支付失败！';
					icon = 'fail';
					break
				case 3:
					title = '支付关闭！';
					icon = 'fail';
					break
				case 4:
					title = '支付取消！';
					icon = 'fail';
					break
				default:
					title = '支付结束！';
					icon = 'fail';
			}

			uni.showToast({
				title,
				icon,
				duration: 1000
			});
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/my_order/my_order'
				});
			}, 500);
		},
		fail(res) {
			uni.showToast({
				title: '支付未成功',
				icon: 'fail',
				duration: 2000
			});
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/my_order/my_order'
				});
			}, 500);
		}
	});
	// #endif

	// #ifdef MP-ALIPAY
	my.tradePay({
		...orderPayData,
		success: (res) => {
			if (res.resultCode == 9000) {
				my.showToast({
					content: '支付成功',
					type: 'success',
					duration: 2000
				})
				my.requestSubscribeMessage({
					//需要用户订阅的消息模板的id的集合
					entityIds: ['20ce215425374b34b06f9177dc3b4549'],
					success: (res) => {
						// res.behavior=='subscribe'
						console.log(res, 'success');
						let param = {
							order_no: orderPayData.order_no
						}
						http('/api/v1/send-subscribe', 'post', {
							type: 'pay_success',
							param: JSON.stringify(param)
						}).then((res) => {
							console.log(res, '消息调取');
						});
					},
					fail: (res) => {
						console.log(res, 'failfailfail');
					},
					complete: (res) => {
						setTimeout(function() {
							uni.reLaunch({
								url: '/pages/user/order_detail/order_detail?order_no=' +
									orderPayData.order_no + '&_type=1'
							});
						}, 500);
					}
				});
			} else {
				console.log(res, '未支付情况')
				my.showToast({
					content: res.memo,
					type: 'fail',
					duration: 2000
				})
				setTimeout(function() {
					uni.reLaunch({
						url: '/pages/user/my_order/my_order'
					});
				}, 500);
			}
		},
		fail(res) {
			my.showToast({
				content: "支付未成功",
				type: "fail",
				duration: 2000
			})
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/my_order/my_order'
				});
			}, 500);
		}
	});
	// #endif
	// #ifdef MP-BAIDU
	swan.requestPolymerPayment({
		orderInfo: orderPayData,
		success: res => {
			swan.showToast({
				title: '支付成功',
				icon: 'success'
			});
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/order_detail/order_detail?order_no=' +
						orderPayData.tpOrderId + '&_type=1'
				});
			}, 500);
		},
		fail: err => {
			swan.showToast({
				title: err.errMsg,
				icon: 'none'
			});
			setTimeout(function() {
				uni.reLaunch({
					url: '/pages/user/order_detail/order_detail?order_no=' +
						orderPayData.tpOrderId + '&_type=1'
				});
			}, 500);
		}
	})
	// #endif
}
export const orderNoPay = order_no => {
	http('/api/v1/pay', 'post', {
		order_no
	}).then((res) => {
		let orderPayData = {}
		console.log(res) // 需要修改
		// #ifdef MP-WEIXIN
		orderPayData = {
			timeStamp: res.timestamp,
			nonceStr: res.nonceStr,
			package: res.package,
			signType: res.signType,
			paySign: res.paySign
		}
		// #endif
		// #ifdef MP-TOUTIAO
		orderPayData = {
			order_id: res.order_id,
			order_token: res.order_token
		}
		// #endif
		// #ifdef MP-ALIPAY
		orderPayData = {
			tradeNO: res.trade_no,
			order_no: res.order_no
		}
		// #endif
		// #ifdef MP-BAIDU
		orderPayData = {
			dealId: res.dealId,
			appKey: res.appKey,
			totalAmount: res.totalAmount,
			tpOrderId: res.tpOrderId,
			dealTitle: res.dealTitle,
			signFieldsRange: res.signFieldsRange,
			rsaSign: res.rsaSign,
		}
		// #endif
		orderPay(orderPayData)
	});
}

// module.exports={
// 	formatTime,
// 	httpUtil,
// 	http,
// 	getUserInfoUtil,
// 	tokenAndLogin,
// 	logout,
// 	login_check,
// 	location_city,
// 	getRouter,
// 	orderSubmit,
// 	orderNoPay
// }
