<template>
	<view>
		<tui-bottom-popup :show="show" @close="close">
			<tui-list-cell :hover="false">
				<view class="tui-pay-item__title">
					<view>请选择支付方式</view>
					<view>支付金额：<text class="tui-pay-amuont">￥{{ money }}</text></view>
				</view>
			</tui-list-cell>

			<radio-group>
				<tui-list-cell unlined :hover="false" v-if="schoolCardIsShow">
					<label class="tui-pay-item" @click="changeType(typeArr[0].value)">
						<image src="/static/images/mall/pay/icon_pay_balance.png" class="tui-pay-logo"></image>
						<text>{{ typeArr[0].name }}</text>
						<view class="tui-radio">
							<radio color="#008681" name="pay" :checked="typeArr[0].checked" disabled=""></radio>
						</view>
					</label>
				</tui-list-cell>
				<tui-list-cell unlined v-if="wxIsShow">
					<label class="tui-pay-item" @click="changeType(typeArr[1].value)">
						<image src="/static/images/mall/pay/icon_pay_weixin.png" class="tui-pay-logo"></image>
						<text>{{ typeArr[1].name }}</text>
						<view class="tui-radio">
							<radio color="#008681" name="pay" :checked="typeArr[1].checked"></radio>
						</view>
					</label>
				</tui-list-cell>
				<tui-list-cell unlined v-if="zfbIsShow">
					<label class="tui-pay-item" @click="changeType(typeArr[2].value)">
						<image src="/static/images/mall/pay/icon_pay_zhifubao.png" class="tui-pay-logo"></image>
						<text>{{ typeArr[2].name }}</text>
						<view class="tui-radio">
							<radio color="#008681" name="pay" :checked="typeArr[2].checked"></radio>
						</view>
					</label>
				</tui-list-cell>
				<tui-list-cell>
					<view class="payBtn" @click="btnPay">
						去支付
					</view>
				</tui-list-cell>
			</radio-group>
		</tui-bottom-popup>

		<tui-loading v-if="loading" text="正在前往支付..."></tui-loading>
	</view>
</template>

<script>
	import tuiLoading from "@/components/thorui/tui-loading/tui-loading"
	// #ifdef H5
	var wx = require('jweixin-module');
	// #endif
	export default {
		components: {
			tuiLoading
		},
		name: 'tPayWay',
		props: ['show', 'money', 'afterOrderCompleteGoToUrl', 'paytype', 'payid', 'description', 'orderTitle',
			'payAccessToken'
		],
		data() {
			return {
				loading: false,
				typeArr: [{
						name: "校园卡支付",
						value: "xiaoyuanpay",
						checked: false
					},
					{
						name: "微信支付",
						value: "wxpay",
						checked: true
					},
					{
						name: "支付宝支付",
						value: "alipay",
						checked: false
					},
				],
				zfbIsShow: true,
				wxIsShow: true,
				schoolCardIsShow: true,
				currentType: "wxpay",
				isWX_H5: false,
				h5RootPath: this.$store.state.h5RootPath,
				code: "",
				officialOpenId: "",
				officialAppId: this.$store.state.officialAppId,
				miniOpenId: ''
			};
		},
		methods: {
			is_wx() { //H5支付  判断当前H5环境是在普通浏览器 还是微信内嵌的浏览器
				let en = window.navigator.userAgent.toLowerCase();
				// 匹配en中是否含有MicroMessenger字符串
				if (en.match(/MicroMessenger/i) == 'micromessenger') {
					//在微信中的内嵌浏览器
					this.isWX_H5 = true;
				}
				if (en.match(/MicroMessenger/i) != 'micromessenger') {
					//在普通的H5浏览器
					this.isWX_H5 = false;
				}
			},
			changeType(type) {
				this.currentType = type;
				this.$emit("change", this.currentType);
			},
			close() {
				this.$emit("close", {})
			},
			btnPay() {

				// #ifdef MP-WEIXIN || APP-PLUS
				this.Pay();
				// #endif
				// #ifdef H5
				this.h5Pay();
				// #endif
			},
			async h5Pay() {
				this.close();
				this.loading = true;
				if (this.isWX_H5) {
					//你自己的需要跳转到的页面
					// var local =
					// 	`${this.h5RootPath}h5/#/pages/template/onlinePay/payDetail/payDetail?id=${this.payid}&type=0`;
					var local = window.location.href;
					if (this.officialAppId) {
						window.location.href =
							`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.officialAppId}&redirect_uri=${window.encodeURIComponent(local)}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`;
					} else {
						uni.showToast({
							title: "微信公众号appid尚未设置"
						})
					}
				} else {
					let url = await this.getOrderInfo();
					console.log('url=', url);
					window.location.href = url;
				}
			},
			getCode() {
				var context = '';
				var name = 'code';
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
				var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
				if (r != null) context = r[2];
				return context;
			},
			async Pay() {
				this.close();
				this.loading = true;
				let orderInfo = await this.getOrderInfo();
				console.log('orderInfo=', orderInfo);
				uni.requestPayment({
					provider: this.currentType,
					// #ifdef APP-PLUS
					orderInfo: orderInfo,
					// #endif
					// #ifdef MP-WEIXIN
					...orderInfo,
					// #endif
					success: (e) => {
						uni.navigateTo({
							url: `/pages/common/payresult/payresult?url=${this.afterOrderCompleteGoToUrl}`
						});
						console.log("success", e);
						uni.showToast({
							title: "支付成功"
						})
					},
					fail: (e) => {
						console.log("fail", e);
						uni.showModal({
							content: "支付失败,原因为: " + e.errMsg,
							showCancel: false
						})
					},
					complete: () => {
						this.loading = false;
					}
				})
			},
			async getOrderInfo() {
				console.log('miniopenid=', this.miniOpenId);
				const options = {
					userid: this.$store.state.userinfo.id,
					access_token: this.payAccessToken,
					provider: this.currentType,
					miniopenid: this.miniOpenId,
					officialopenid: this.officialOpenId,
					paytype: this.paytype,
					payid: this.payid,
					description: this.description,
					title: this.orderTitle,
					money: Number(this.money), // 转为以分为单位
					// #ifdef APP-PLUS
					platform: 'app-plus',
					// #endif
					// #ifdef MP-WEIXIN
					platform: 'mp-weixin',
					// #endif
					// #ifdef H5
					platform: this.isWX_H5 ? 'wx-h5' : 'h5',
					return_url: `${this.h5RootPath}h5/#/pages/common/payresult/payresult?url=${this.afterOrderCompleteGoToUrl}`
					// #endif
				}
				console.log("payType=", this.paytype);
				let res = await getApp().globalData.request.specialPost('apiout/paybase/paydeal', options);
				console.log("订单信息=", res);
				let orderInfo;
				// #ifdef H5
				if (this.isWX_H5) {
					orderInfo = {
						appId: res.data.appId,
						timestamp: res.data.timeStamp,
						nonceStr: res.data.nonceStr,
						signature: res.data.paySign,
						package: res.data.package
					}
				} else {
					orderInfo = res.data;
				}

				// #endif
				// #ifdef APP-PLUS 
				if (this.currentType == 'alipay') {
					orderInfo = res;
				} else {
					orderInfo = {
						sign: res.data.sign,
						returnCode: res.return_code,
						returnMsg: res.return_msg,
						resultCode: res.result_code,
						mchId: res.mch_id,
						nonceStr: res.nonce_str,
						prepayId: res.prepay_id,
						tradeType: res.trade_type,
						appId: res.appid,
						appid: res.data.appid,
						errMsg: res.msg,
						noncestr: res.data.noncestr,
						package: res.data.package,
						partnerid: res.data.partnerid,
						prepayid: res.data.prepayid,
						timestamp: res.data.timestamp,
					}
				}
				// #endif
				// #ifdef MP-WEIXIN
				orderInfo = {
					provider: this.currentType,
					timeStamp: res.data.timeStamp,
					nonceStr: res.data.nonceStr,
					package: res.data.package,
					signType: res.data.signType,
					paySign: res.data.paySign
				}
				// #endif
				return orderInfo;
			},
			async wxH5_Pay() {
				const _this = this;
				let params = await this.getOrderInfo();
				wx.config({
					debug: false,
					appId: params.appId, // 必填，公众号的唯一标识
					timestamp: params.timestamp, // 必填，生成签名的时间戳
					nonceStr: params.nonceStr, // 必填，生成签名的随机串
					signature: params.signature, // 必填，签名
					jsApiList: ['chooseWXPay'], // 必填，需要使用的JS接口列表
					openId: this.officialOpenId
				});
				wx.ready(() => {
					wx.chooseWXPay({
						appId: params.appId,
						timestamp: params.timestamp,
						nonceStr: params.nonceStr,
						package: params.package,
						signType: 'MD5',
						paySign: params.signature,
						success() {
							uni.showToast({
								icon: 'none',
								title: '支付成功'
							})
							window.location.href =
								`${_this.h5RootPath}h5/#/pages/common/payresult/payresult?url=${_this.afterOrderCompleteGoToUrl}`;
						},
						cancel() {
							uni.showToast({
								icon: 'none',
								title: '取消支付'
							})
						},
						fail() {
							uni.showToast({
								icon: 'none',
								title: '支付失败'
							})
						}
					})
				})
			},
			async getofficialopenid(code) {
				let res = await getApp().globalData.request.post('user/getofficialopenid', {
					code,
				})

				this.officialOpenId = res.data;
				if (this.officialOpenId) {
					this.wxH5_Pay();
				}
			},
			async UseThosePayMehtod() {
				let res = await await getApp().globalData.request.specialPost('apiout/paybase/paytype');
				console.log('pay method', res);
				this.zfbIsShow = Boolean(res.is_alipay);
				this.schoolCardIsShow = Boolean(res.is_card);
				this.wxIsShow = Boolean(res.is_wxpay);
				// #ifdef MP-WEIXIN
				this.zfbIsShow = false;
				// #endif
				// #ifdef H5
				if (this.isWX_H5) {
					this.zfbIsShow = false;
				}
				// #endif

			}
		},
		mounted() {
			const _this = this;
			// #ifdef MP-WEIXIN
			uni.login({
				success(res) {
					let res1 = getApp().globalData.request.post('user/getminiopenid', {
						code: res.code
					})
					console.log('res1=', res1);
					res1.then(res => {
						_this.miniOpenId = res.data;
					})
				}
			})
			// #endif
			this.UseThosePayMehtod();
			this.$emit("change", this.currentType);
			//#ifdef H5
			this.is_wx();
			if (this.isWX_H5) {
				let code = this.getCode();
				// console.log('code==',code);
				if (code) {
					this.getofficialopenid(code);
				}
			}
			// #endif
		}
	}
</script>

<style scoped>
	.tui-pay-item__title {
		width: 100%;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.tui-pay-amuont {
		color: #008681;
		font-weight: 500;
		font-size: 34rpx;
	}

	.tui-pay-item {
		width: 100%;
		height: 80rpx;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.tui-pay-logo {
		width: 48rpx;
		height: 48rpx;
		margin-right: 15rpx;
	}

	.tui-radio {
		margin-left: auto;
		transform: scale(0.8);
		transform-origin: 100% center;
	}

	.payBtn {
		width: 92%;
		height: 88rpx;
		line-height: 88rpx;
		background: #008681;
		border-radius: 10rpx;
		margin: 0 auto;
		color: #fff;
		font-size: 30rpx;
		text-align: center;
	}

	.tui-recharge {
		color: #fc872d;
		margin-left: auto;
		padding: 12rpx 0;
	}
</style>
