<template>
	<view class="content">
		<view class="paymentTop">
			 <!-- v-if="applyData.status" -->
			<view class="paymentTop-name">
				订单支付
				<text>与人方便,与己方便,珍惜时间,请先付款</text>
			</view>
			<img class="paymentTop-img" src="https://douhuo-storage.oss-cn-beijing.aliyuncs.com/images/2023/06/06/d9c965766807a6e1c57da11e069c8686.png">
		</view>
		<view class="paymentShow">
			<img class="paymentShow-img" src="https://douhuo-storage.oss-cn-beijing.aliyuncs.com/images/2023/06/06/5ccd7b6473095bf0e55c21240ca2eb90.png">
			<view class="paymentShow-text">
				<view class="paymentShow-top">
					<view class="paymentShow-top-name">订单名称：<text>{{style == 'chajia' ? '补差价' : '咨询服务费'}}</text></view>
					<view class="paymentShow-top-price">￥{{price}}</view>
				</view>
				<view class="paymentShow-tips">
					订单描述：{{remark ? remark : '暂无描述'}}
				</view>
				<view class="paymentShow-top-name" style="margin-bottom: 10px; color: #9a9a9a;">支付方式：</view>
				
				<view @click="payTypeVal = 'alipay'" class="paymentList-label">
					<image class="paymentList-img" :src="payTypeVal == 'alipay' ? '/static/imgs/payCheck_active.png' : '/static/imgs/payCheck.png'" mode="widthFix"></image>支付宝（银联商务）
				</view>
				<view @click="onUmsPay('mp')" class="paymentList-label">
					<image class="paymentList-img" :src="payTypeVal == 'umsWx' ? '/static/imgs/payCheck_active.png' : '/static/imgs/payCheck.png'" mode="widthFix"></image>微信支付（银联商务）
				</view>
				
				
				<view @click="payTypeVal = 'dgwxalipay'" class="paymentList-label">
					<image class="paymentList-img" :src="payTypeVal == 'dgwxalipay' ? '/static/imgs/payCheck_active.png' : '/static/imgs/payCheck.png'" mode="widthFix"></image>支付宝（汇付）
				</view>
				<view @click="dgwxPay('mp')" class="paymentList-label">
					<image class="paymentList-img" :src="payTypeVal == 'dgwx' ? '/static/imgs/payCheck_active.png' : '/static/imgs/payCheck.png'" mode="widthFix"></image>微信支付(汇付)
				</view>
				
			</view>
		</view>
		
		<view class="paymentBtn" v-if="payTypeVal == 'umsWx'">
			<!-- douhuotest dev=0是线上  dev=1是线下 -->
			<wx-open-launch-weapp
				username="gh_918c81628d6f"
				:path="'pages/pay/pay?type=h5&dev=0&trade_id=' + tradeId + '&token=' + token"
			>
				<script type="text/wxtag-template">
					<style>
						.gobtn {
							width: 280px;
							background-color: #da2b56;
							color: #ffffff;
							border-radius: 5px;
							height: 50px;
							line-height: 50px;
							font-size: 18px;
							border: none;
						}
					</style>
					<button type="default" class="gobtn">打开小程序收银台</button>
				</script>
			</wx-open-launch-weapp>
		</view>
		<view class="paymentBtn" v-else-if="payTypeVal == 'dgwx'">
			<button type="default" class="paymentBtn-go" :disabled="disabled" @click="payChickDg">
				打开小程序收银台
			</button>
		</view>
		<view class="paymentBtn" v-else>
			<button type="default" class="paymentBtn-go" :disabled="disabled" @click="payChick">
				立即支付
			</button>
		</view>
		
	</view>
</template>

<script>
	import VConsole from 'vconsole';
	const jweixin = require('jweixin-module');
	import { applyPay, diffPay, authFollow } from '@/apis/interfaces/index'
	import { umsDiff, umsOrder, umsState, dgPay, diffDgPay } from '@/apis/interfaces/pay.js'
	export default {
		data() {
			return {
				payTypeVal  : 'alipay',	 // 支付方式
				tradeId		: '',	 // 查询id
				jumpUrlDg   : '',    // 抖巩支付
				getState	: false, // 查询支付结果
				token		: '',	 // 用户token
				style	    : '',    // 支付类型
				price	    : '',    // 价格
				disabled    : false  // 按钮状态
			}
		},
		onLoad() {
			// new VConsole();
		},
		onShow() {
			if(this.getState && this.tradeId != ''){
				this.getUmsState(this.tradeId)
			}
			this.token = this.$store.getters.getToken
			this.style  = this.$Route.query.style
			this.price  = this.$Route.query.price
			this.remark  = this.$Route.query.remark
		},
		methods: {
			// 查询支付结果
			getUmsState(tradeId){
				uni.showLoading({
					title: '查询支付结果...',
					mask : true
				})
				let outTime;
				let resNumb = 0;
				outTime = setInterval(() => {
					if(resNumb >= 3){
						clearInterval(outTime)
						uni.showToast({
							title: "查询支付结果失败",
							icon : "none",
							mask : true
						})
						return
					}
					umsState(tradeId).then(res => {
						resNumb++
						if(res.state === 'success'){
							clearInterval(outTime)
							uni.hideLoading()
							this.$Router.replace({name: 'sheetPoint'})
						}
					}).catch(err => {
						uni.showToast({
							title: err.message,
							icon : 'none'
						})
					})
				}, 2000)
			},
			// 支付
			payChick(){
				switch(this.payTypeVal){
					case '':
						uni.showToast({
							title: '请选择支付方式',
							icon : 'none'
						})
						break;
					case 'wxpay':
						this.payClick()
						break;
					case 'alipay':
						this.onUmsPay('mp_alipay')
						break;
					case 'dgwxalipay':
						this.dgwxPay('mp_alipay')
						break;
				}
				this.showPayMenu = false
			},
			
			// 抖供支付
			payChickDg() {
				window.location.href = this.jumpUrlDg.scheme_code
			},
			
			// 第三方差价支付
			onUmsPay(type){
				let umsFun = this.style == 'chajia' ? umsDiff : umsOrder
				umsFun(this.$Route.query.id, {type}).then(res => {
					this.getState = true
					switch (type){
						case 'mp':
							this.tradeId = res.trade_id
							this.payTypeVal = 'umsWx'
							break;
						case 'mp_alipay':
							this.tradeId = res.trade_id
							window.location.href = res.alipay
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			
			// 斗拱支付
			dgwxPay(type){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				let umsFun = this.style == 'chajia' ? dgPay : diffDgPay
				dgPay(this.$Route.query.id, {type, app_schema: 'weixin://'}).then(res => {
					let { params, trade_id } = res;
					this.getState = true
					uni.hideLoading()
					switch (type){
						case 'mp':
							this.tradeId = trade_id
							this.jumpUrlDg = JSON.parse(params.miniapp_data)
							this.payTypeVal = 'dgwx'
							break;
						case 'mp_alipay':
							this.tradeId = trade_id
							// window.location.href = 'https://ds.alipay.com/?scheme=' + encodeURIComponent(params.jump_url)
							window.location.href = `https://ds.alipay.com/?scheme=` + encodeURIComponent(params.jump_url)
							this.payTypeVal = 'dgwxalipay'
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			
			//咨询服务费 - 微信支付
			payClick() {
				let newOpenId = uni.getStorageSync('openId')
				if(newOpenId) {
					let NewUrl = ''
					if(this.$Route.query.style == 'daijiao') {
						NewUrl = applyPay
					} else {
						NewUrl = diffPay
					}
					NewUrl(this.$Route.query.id, {
					    openid : newOpenId
					}).then(res => {
					    let wxConfig = JSON.parse(res.wechat)
					    jweixin.config({
					        appId: wxConfig.appId,
					        debug: false,
					        jsApiList: ['chooseWXPay'],
					        signature: wxConfig.signature,
					        nonceStr: wxConfig.nonceStr,
					        timestamp: wxConfig.timestamp,
					    })
					    jweixin.ready(() => {
					        jweixin.chooseWXPay({
					            timestamp: wxConfig.timeStamp,
					            nonceStr: wxConfig.nonceStr, 
					            package: wxConfig.package,
					            signType: wxConfig.signType,
					            paySign: wxConfig.paySign,
					            success: payRes => {
									// 先跳支付成功
									uni.showToast({
										title: '支付成功',
										icon: "none"
									})
									this.disabled = true
									setTimeout(()=>{
										this.$Router.replace({name: 'sheetPoint'})
									},3000)
					            },
								cancel: payCancel => {
									// 跳到咨询单
									this.$Router.replace({name: 'sheetIndex'})
								},
					            fail: payfail => {
									// 取消支付
									uni.showToast({
									    title: '取消支付',
									    icon: 'none'
									})
									this.disabled = true
									setTimeout(()=>{
										this.$Router.replace({name: 'User'})
									},1000)
					            }
					        });
					    });
					}).catch(err => {
						uni.showToast({
							title: err.message,
							icon: "none"
						})
					})
					return
				}
				
				// 获取微信授权信息-获取oppid
				authFollow({
					// url: 'https://web.douhuotest.douhuofalv.com/webWechat/index?id=' + this.$Route.query.id + '&style=' + this.$Route.query.style + '&price=' + this.$Route.query.price
					// url: 'http://web.douhuo.demos.uzchain.tech/webWechat/index?id=' + this.$Route.query.id + '&style=' + this.$Route.query.style + '&price=' + this.$Route.query.price 最新
				    url: 'https://web.douhuofalv.com/webWechat/index?id=' + this.$Route.query.id + '&style=' + this.$Route.query.style + '&price=' + this.$Route.query.price
				}).then(res => {
				    window.location.href = res
				}).catch(err => {
				    uni.showToast({
				        title: err.message,
				        icon: "none"
				    })
				})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.paymentTop {
		background-color: #dc7f8b;
		padding: $padding * 2 $padding * 2 $padding * 4;
		box-sizing: border-box;
		display: flex;
		color: #ffffff;
		.paymentTop-name {
			flex: 1;
			font-size: $title-size + 10;
			text {
				margin-top: 20rpx;
				display: block;
				font-size: $title-size-sm;
			}
		}
		.paymentTop-img {
			width: 100rpx;
			height: 100rpx;
		}
	}
	.paymentShow {
		position: relative;
		top: -80rpx;
		left: 0;
		width: 100%;
		.paymentShow-img,
		.paymentShow-text{
			position: absolute;
			left: 30rpx;
			top: 0;
			width: calc(100% - 60rpx);
		}
		.paymentShow-text {
			padding: $padding $padding * 2 0;
			box-sizing: border-box;
		}
		.paymentShow-top {
			display: flex;
			font-size: $title-size + 2;
			line-height: 130rpx;
			.paymentShow-top-name {
				flex: 1;
				display: flex;
				color: #9a9a9a;
				text {
					color: #000000;
				}
			}
			.paymentShow-top-price {
				color: $mian-color;
			}
		}
		.paymentShow-tips {
			margin-bottom: $margin + 10;
			color: #9a9a9a;
			font-size: $title-size-lg;
		}
		.paymentShow-coupon {
			display: flex;
			.paymentTop-icon {
				width: 42rpx;
				height: 42rpx;
			}
			.paymentTop-usable {
				flex: 1;
				margin-left: 20rpx;
				text {
					display: block;
					color: #9a9a9a;
					font-size: $title-size-sm;
					line-height: 48rpx;
				}
			}
		}
	}
	
	.paymentList-label {
		line-height: 80rpx;
		display: flex;
	}
	
	.paymentList-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: $margin - 10;
	}
	.paymentList-img {
		width: 34rpx;
		height: 34rpx;
		margin-top: 22rpx;
		margin-right: $margin - 10;
	}
	
	.paymentBtn {
		position: fixed;
		bottom: $margin * 2;
		left: 0;
		text-align: center;
		padding: 0 $padding 100rpx;
		box-sizing: border-box;
		width: 100%;
		.paymentBtn-go {
			width: 70% !important;
			background-color: $mian-color;
			color: #ffffff;
			border-radius: 10rpx;
			line-height: 94rpx;
			font-size: $title-size + 2;
			&[disabled] {
				background-color: #eba5a5;
			}
		}
	}
</style>