<template>
	<view class="pay">
		<view class="pay-hd">
			<view class="a">订单号：<text>{{order_id}}</text></view>
			<view class="a">支付价格：<text>￥{{orderInfo.pay_price}}</text>元</view>
		</view>
		<view class="pay-bd">
			<view class="title">选择支付方式</view>
			<view class="item" v-for="(a,i) in list2" @click="tabItem(i)">
				<image v-if="tabIndex == i" src="@/static/invoice/select-on.png"></image>
				<image v-else src="@/static/invoice/select.png"></image>
				{{a.method == 'huifu' ? '银联支付' : (a.method == 'wechat'?'微信支付':'余额支付')}}<text v-if="a.method == 'balance'">（余额：{{userInfo.balance}}）</text>
			</view>
		</view>
		<view class="pay-btn" @click="clickPay()">确认支付</view>
	</view>
</template>

<script>
	import { Wechat } from '@/core/payment'
	import * as CashierApi from '@/api/cashier';
    import * as newFunApi from '@/api/newFun'
	export default {
		data() {
			return {
				tabIndex: 0,
				type: "",
				order_id: "",
				userInfo: {},
				list2: [],
				orderInfo: {},
				isClick: true,
			};
		},
		onLoad(o) {
			console.log(o)
			this.order_id = o.order_id;
			this.type = o.type;
			this.toServerOrder();
			uni.$on('appShow', this.solveShowMsg);
		},
		onUnload() {
			uni.$off('appShow', this.solveShowMsg);
		},

		methods: {
			solveShowMsg(info) {
				console.log(info);
				if (this.miniPayRequest && Object.keys(this.miniPayRequest).length > 0 && info.appId === this.miniPayRequest.miniuser) {
					this.onTradeQuery(this.miniPayRequest.out_trade_no, this.list2[this.tabIndex].method);
				}
			},
			clickPay(){
				if(this.isClick == false){
					return;
				}
				this.isClick = false;
				if(this.list2[this.tabIndex].method == "balance"){
					if(Number(this.orderInfo.pay_price) <= Number(this.userInfo.balance)){
						this.toPay()
					}else{
						this.isClick = true;
						uni.showToast({
							icon: "none",
							title: "余额不足，请选择其他支付方式"
						})
					}
				}else if(this.list2[this.tabIndex].method == "wechat"){
					this.toPay1()
				} else if(this.list2[this.tabIndex].method == "huifu") {
					this.isClick = true;
					if (!this.miniPayRequest || Object.keys(this.miniPayRequest).length === 0) {
							this.$toast(`暂无银联支付信息`);
							return
					}
					let appPayRequest = '';
					appPayRequest = encodeURIComponent(JSON.stringify({
						sign: this.miniPayRequest.sign,
						prepayid: this.miniPayRequest.prepayid,
					}));
					uni.openEmbeddedMiniProgram({
						appId: this.miniPayRequest.miniuser,
						path: `${this.miniPayRequest.minipath}?appPayRequest=${appPayRequest}`
					});
				}
			},
			//创建支付方式信息
			async toServerOrder(order_id) {
				let {status, data, message } = await newFunApi.serverOrderInfo({
					client: 'MP-WEIXIN',
					order_id: this.order_id
				})
				if(status == 200){
					this.userInfo = data.personal
					this.orderInfo = data.order
					this.list2 = data.paymentMethods;
					this.setDefaultPayType();
					console.log(data)
					console.log(this.orderInfo)
					console.log(this.list2)
					console.log(this.userInfo)
				}else{
					uni.showToast({
						icon: "none",
						title: message
					})
				}
			},
			async huifuPay() {
				const app = this;
				const {status, data } = await newFunApi.serverOrderPay({
					order_id: this.order_id,
					method: 'huifu',
					client: "MP-WEIXIN",
				})
				if(status == 200) {
					const { miniPayRequest, out_trade_no } = data.payment;
					app.miniPayRequest = miniPayRequest;
					app.miniPayRequest.out_trade_no = out_trade_no;
				}
				
			},
			async toPay1() {
				const that = this;
				const {status, data } = await newFunApi.serverOrderPay({
					order_id: this.order_id,
					method: 'wechat',
					client: "MP-WEIXIN",
				})
				if(status == 200) {
					Wechat.payment(data.payment)
					.then((result) => {
						console.log(22,result)
						uni.showToast({
							title: "支付成功"
						})
						this.isClick = true;
						setTimeout(()=>{
							if(that.type == 'fuwu'){
								uni.redirectTo({
									url: "/pages/news/recycling/orderList"
								})
							}else if(that.type == 'fuwuorder'){
								uni.navigateBack({
									delta:1
								})
							}
							
						},1000)
					})
					.catch(err => {
						uni.showToast({
							title: "支付失败"
						})
						this.isClick = true;
						setTimeout(()=>{
							if(that.type == 'fuwu'){
								uni.redirectTo({
									url: "/pages/news/recycling/orderList"
								})
							}else if(that.type == 'fuwuorder'){
								uni.navigateBack({
									delta:1
								})
							}
							
						},1000)
					})
				}
				
			},
			//去支付 余额支付
			async toPay() {
				const that = this;
				const {status, message} = await newFunApi.serverOrderPay({
					order_id: this.order_id,
					method: 'balance',
					client: "MP-WEIXIN",
				})
				if(status == 200) {
					uni.showToast({
						title: "支付成功"
					})
					this.isClick = true;
					setTimeout(()=>{
						if(that.type == 'fuwu'){
							uni.redirectTo({
								url: "/pages/news/recycling/orderList"
							})
						}else if(that.type == 'fuwuorder'){
							uni.navigateBack({
								delta:1
							})
						}
						
					},1000)
				}else{
					this.isClick = true;
					uni.showToast({
						icon: "none",
						title: message
					})
				}
			},
			// 设置默认的支付方式
			setDefaultPayType() {
				const app = this
				const defaultIndex = app.list2.findIndex(item => item.is_default == true)
				defaultIndex > -1 && app.tabItem(defaultIndex);
			},
			tabItem(i){
				this.tabIndex = i
				if (this.list2[this.tabIndex].method == "huifu") {
					this.huifuPay();
				}
			},
			
			// 已完成支付按钮事件: 请求后端查单
			onTradeQuery(outTradeNo, method) {
				const app = this
				// 交易查询
				// 查询第三方支付订单是否付款成功
				CashierApi.tradeQuery({
						outTradeNo,
						method,
						client: app.platform
					})
					.then(result => {
						if (result.data.isPay) {
							uni.showToast({
								title: result.message || "支付成功",
								icon: 'success'
							})
							
							setTimeout(() => {
								uni.redirectTo({
									url: "/pages/news/caigou/notice1"
								})
							}, 1000)
						}	else {
							uni.showToast({
								title: result.message || "支付失败",
								icon: 'none'
							})
						}
					})
					.finally(() => app.showConfirmModal = false)
			},
		}
	}
</script>

<style lang="scss" scoped>
.pay{
	overflow: hidden;
	&-hd{
		width: 710rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		margin: 0 auto;
		margin-top: 20rpx;
		.a{
			padding: 20rpx 0;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #666;
			text{
				margin-left: 20rpx;
				color: #212121;
			}
		}
	}
	&-bd{
		width: 710rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		margin: 0 auto;
		margin-top: 20rpx;
		.title{
			padding: 30rpx 0;
			font-size: 30rpx;
		}
		.item{
			padding: 20rpx 0;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #212121;
			image{
				width: 30rpx;
				height: 30rpx;
				margin-right: 20rpx;
			}
			text{
				margin-left: 20rpx;
				color: #666;
			}
		}
	}
	&-btn{
		width: 710rpx;
		padding: 0 20rpx;
		line-height: 80rpx;
		box-sizing: border-box;
		background-color: #ff3939;
		margin: 0 auto;
		margin-top: 160rpx;
		text-align: center;
		font-size: 36rpx;
		color: #fff;
		border-radius: 20rpx;
	}
}
</style>
