<template>
	<page-meta :page-style="themeColor"></page-meta>
	<view class="wrapper">
		<!-- 默认 -->
		<view v-if="(!isSuccess)&&(!isFail)" class="container">
			<view class="logo">
				<image :src="$util.img(siteInfo.logo)" mode=""></image>
			</view>
			<view class="pay_money">
				付款金额:{{pay_money}}
			</view>
			<view class="outTradeNo">
				<text style="color: #aaa;">订单编号：</text>{{outTradeNo}}
			</view>

			<!-- <br>
			token：{{token}}
			<br>
			goods_type：{{goods_type}} -->
			<view>
				<button type="primary" class="button" @click="payHandler">确认支付</button>
				<!-- <button type="primary" open-type="launchApp" app-parameter="wechat" @error="launchAppError">返回APP</button> -->
				<!-- <navigator class="duce_button" open-type="exit" target="miniProgram">退出小程序</navigator> -->
				<!-- <button type="primary" class="button" @click="exitApplet()">返回APP</button> -->
			</view>
		</view>
		<!-- 支付成功 -->
		<view class="" v-if="isSuccess" class="container">
			<view class="logo">
				<image :src="$util.img('/upload/weapp/user/successful.png')" mode=""></image>
			</view>
			<view class="pay_money">订单支付成功</view>
			<button type="primary" class="button" @click="exitApplet()">返回APP</button>
		</view>
		<!-- 支付失败 -->
		<view class="" v-if="isFail" class="container">
			<!-- <view class="logo">
				<image :src="$util.img('/upload/weapp/user/successful.png')" mode=""></image>
			</view> -->
			<view class="pay_money">未成功支付</view>
			<button type="default" class="button" @click="exitApplet()">返回APP</button>
			<button type="primary" class="button1" @click="goOn()">继续支付</button>
		</view>
	</view>

</template>

<script>
	// 包裹 uniapi 接口
	const MiniWarp = (fn, data) => {
		return new Promise((resolve, reject) => {
			fn({
				success: (res) => resolve(res),
				fail: (res) => reject(res),
				...data,
			})
		})
	}
	const uniLogin = data => MiniWarp(uni.login, data);
	const requestPayment = data => MiniWarp(uni.requestPayment, data);

	export default {
		data() {
			return {
				// SiteInfo: uni.getStorageSync('siteInfo'),
				token: "",
				outTradeNo: '',
				payInfo: {},
				wxCode: "",
				aliCode: "",
				goods_type: '',
				isSuccess: false, //支付成功
				isFail: false, //支付失败
				pay_money: "",
				trade_no:"",
			};
		},
		onLoad(option) {
			// #ifndef MP-ALIPAY
			this.outTradeNo = option.out_trade_no;
			this.token = option.token;
			this.goods_type = option.goods_type;
			this.pay_money = option.pay_money
			// #endif
			// #ifdef MP-ALIPAY
			console.log(uni.getStorageSync('schemeData'), `optionOnLoad`);
			// this.schemeData = uni.getStorageSync('schemeData');
			this.outTradeNo = uni.getStorageSync('schemeData').out_trade_no;
			this.token = uni.getStorageSync('schemeData').token;
			this.goods_type = uni.getStorageSync('schemeData').goods_type;
			this.pay_money = uni.getStorageSync('schemeData').pay_money
			// #endif
		},
		onShow() {},
		methods: {
			async launchAppError(e) {
				console.log(e.detail)
				uni.showToast({ icon: 'none', title: e.detail.errMsg })
			},
			async payHandler() {
				try {
					// #ifdef MP-WEIXIN
					await this.weixinPay()
					// #endif
					// #ifdef MP-ALIPAY
					await this.aliPay()
					// #endif
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			async weixinPay() {
				try {
					let provider = 'weixin'
					// 微信登录
					const loginRes = await uniLogin({ provider })
					console.log(loginRes, 'loginRes');
					this.wxCode = loginRes.code;
					// 请求后端
					let url = '/api/boofopay/unifiedOrder';
					// debug 模式调用 测试支付接口
					const appBaseInfo = wx.getAppBaseInfo()
					if (appBaseInfo.enableDebug)
						url = '/api/boofopay/test'
					if (this.goods_type == '2')
						url = '/api/boofopay/rechargeUnifiedOrder'
					const res = await this.$api.sendRequest({
						url,
						data: {
							token: this.token,
							code: this.wxCode,
							payCode: "WECHAT_JSAPI", //payCode  支付宝：ALIPAY_JSAPI 微信：WECHAT_JSAPI
							out_trade_no: this.outTradeNo,
							goods_type: this.goods_type
						},
						async: false
					})
					// 拼接支付参数
					const { timeStamp, nonceStr, package: payPackage, signType, paySign } = res.data.chlRetParam
						.wc_pay_data
					await requestPayment({
						provider,
						timeStamp,
						nonceStr,
						package: payPackage,
						signType,
						paySign,
					});
					this.isSuccess = true;
					this.isFail = false;
					// 退出小程序
					// wx.exitMiniProgram()
				} catch (e) {
					this.isSuccess = false;
					this.isFail = true;
					//TODO handle the exception
					console.log(e);
				}
			},
			async aliPay() {
				try {
					let provider = 'alipay'
					// 支付宝登录
					const loginRes = await uniLogin({ provider })
					console.log(loginRes, 'loginRes');
					this.aliCode = loginRes.code;
					// 请求后端
					let url = '/api/boofopay/unifiedOrder';
					// debug 模式调用 测试支付接口
					// appBaseInfo = wx.getAppBaseInfo()
					// if (appBaseInfo.enableDebug)
					// 	url = '/api/boofopay/test'
					// goods_type 默认1 充值余额2
					if (this.goods_type == '2')
						url = '/api/boofopay/rechargeUnifiedOrder'
					const res = await this.$api.sendRequest({
						url,
						data: {
							token: this.token,
							code: this.aliCode,
							payCode: "ALIPAY_JSAPI", //payCode  支付宝：ALIPAY_JSAPI 微信：WECHAT_JSAPI
							out_trade_no: this.outTradeNo,
							goods_type: this.goods_type
						},
						async: false
					})
					// 拼接支付参数
					console.log(res);
					this.trade_no = res.data.chlRetParam.trade_no
					// await requestPayment({
					// 	provider,
					// 	orderInfo: trade_no
					// })
					console.log(this.trade_no);
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: this.trade_no,
						success: (r) => {
							console.log(r, 'res');
							if (r.resultCode == '9000') {
								this.isSuccess = true;
								this.isFail = false;
							}else{
								var Str="";
								if(r.resultCode == '4000'){
									Str='订单支付失败'
									this.isSuccess = false;
									this.isFail = true;
								}else if(r.resultCode == '5000'){
									Str='重复请求'
									this.isSuccess = false;
									this.isFail = true;
								}else if(r.resultCode == '6001'){
									Str='用户中途取消'
									this.isSuccess = false;
									this.isFail = true;
								}else if(r.resultCode == '6002'){
									Str='网络连接出错'
									this.isSuccess = false;
									this.isFail = true;
								}
								uni.showModal({
									content:Str,
									showCancel: false
								})
							}
						},
						fail: (e) => {
							var Str="";
							if(e.resultCode == '4000'){
								Str='订单支付失败'
								this.isSuccess = false;
								this.isFail = true;
							}else if(e.resultCode == '5000'){
								Str='重复请求'
								this.isSuccess = false;
								this.isFail = true;
							}else if(e.resultCode == '6001'){
								Str='用户中途取消'
								this.isSuccess = false;
								this.isFail = true;
							}else if(e.resultCode == '6002'){
								Str='网络连接出错'
								this.isSuccess = false;
								this.isFail = true;
							}
							console.log(e, 'err');
							uni.showModal({
								content:Str||e,
								showCancel: false
							})
						}
					});

					// 退出小程序
					// wx.exitMiniProgram()
				} catch (e) {
					this.isSuccess = false;
					this.isFail = true;
					console.log(e);
				}
			},
			exitApplet() {
				wx.exitMiniProgram()
			},
			goOn() {
				this.isSuccess = false;
				this.isFail = false;
			}
		}
	};
</script>

<style lang="scss">
	.wrapper {
		width: calc(100vw - 60rpx);
		margin: 0 30rpx;
		height: 100vh;
		position: relative;

		.container {

			width: calc(100% - 60rpx);
			height: 400rpx;
			padding: 30rpx;
			// border: 1rpx solid red;
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			margin: 100rpx auto;

			.outTradeNo {
				text-align: center;
			}

			.pay_money {
				text-align: center;
				font-weight: 600;
				font-size: 60rpx;
				margin-bottom: 30rpx;
			}

			.logo {
				width: 100%;
				display: flex;
				justify-content: center;
				margin-bottom: 30rpx;

				image {
					width: 200rpx;
					height: 200rpx;
					background-size: 100% 100%;
				}
			}
		}

		.button {
			width: 50%;
			margin: 0 auto;
			margin-top: 200rpx;

		}

		.button1 {
			width: 50%;
			margin: 0 auto;
			margin-top: 60rpx;
		}
	}
</style>