<template>
	<view class="pay">
		<!-- 支付金额 -->
		<view class="header">
			<view class="header-title">实付金额</view>
			<view class="header-price"><text>￥</text>{{total}}</view>
			<block v-if="rate != 1">
				<view class="header-fire">火力值：{{totalFire}}</view>
				<view class="header-no">当前火力值比例1:{{rate}}</view>
			</block>
			<view class="header-no">订单号:{{orderNo}}</view>
		</view>
		<!-- 选择支付方式 -->
		<view class="choose">
			<radio-group @change="changeRadio" >
				<label class="choose-item" v-if="payType != 'free'">
					<view class="choose-text nowrap">
						<image src="@/static/icons/pay_alipay.png" mode="aspectFill"></image>
						火力值支付
					</view>
					<radio class="choose-radio" value="coin" :checked="payMethod == 'coin'"></radio>
				</label>
				<label class="choose-item nowrap">
					<view class="choose-text">
						<image src="@/static/icons/pay_wechat.png" mode="aspectFill"></image>
						微信支付(银联)
					</view>
					<radio class="choose-radio" value="wx" :checked="payMethod == 'wx'"></radio>
				</label>
				<label class="choose-item nowrap">
					<view class="choose-text">
						<image src="@/static/icons/pay_wechat.png" mode="aspectFill"></image>
						微信支付(汇付)
					</view>
					<radio class="choose-radio" value="dgwx" :checked="payMethod == 'dgwx'"></radio>
				</label>
				<label class="choose-item nowrap" v-if="Number(total) <= 10000">
					<view class="choose-text">
						<image src="@/static/icons/pay_ali.png" mode="aspectFill"></image>
						支付宝支付(银联)
					</view>
					<radio class="choose-radio" value="ali" :checked="payMethod == 'ali'"></radio>
				</label>
				<label class="choose-item nowrap">
					<view class="choose-text">
						<image src="@/static/icons/pay_ali.png" mode="aspectFill"></image>
						支付宝支付(汇付)
					</view>
					<radio class="choose-radio" value="dgali" :checked="payMethod == 'dgali'"></radio>
				</label>
				<label class="choose-item nowrap">
					<view class="choose-text">
						<image src="@/static/icons/pay_code.png" mode="aspectFill"></image>
						付款码支付
					</view>
					<radio class="choose-radio" value="code"></radio>
				</label>
			</radio-group>
		</view>
		<view class="deduction" v-if="(payMethod == 'wx' || payMethod == 'ali' || payMethod == 'dgwx' || payMethod == 'dgali') && payType != 'free'">
			<view class="deduction-item">
				<view class="deduction-label">
					<view class="title">使用火力值抵扣</view>
					<view class="balance">余额:{{balance}}</view>
				</view>
				<u-switch
					activeColor="#446EFE"
					size="20"
					v-model="isDeduction"
					@change="onDeductionSwitch"
				></u-switch>
			</view>
			<view class="deduction-item" v-if="isDeduction">
				<view class="deduction-label">
					<view class="title">使用数量</view>
				</view>
				<input class="deduction-input" type="number" placeholder="输入火力值" v-model="deductionVal" @blur="blurDeductionVal">
			</view>
		</view>
		<!-- 扫码付二维码 -->
		<u-popup
			:show="payCodeShow"
			mode="center"
			round="10px">
			<view class="qrpay">
				<view class="title">支付二维码</view>
				<view class="src">
					<l-painter class="qrcode-src">
						<l-painter-qrcode
							:text="payQrUrl"
							css="width: 280rpx; height: 280rpx;"
						/>
					</l-painter>
				</view>
				<view class="time">请使用{{payQrType == 'app' ? '微信': '支付宝'}}扫码</view>
				<view class="btns">
					<button class="btn cancel" @click="onCancel">取消支付</button>
					<button class="btn confirm" @click="onGetOrderPayState">我已支付</button>
				</view>
			</view>
		</u-popup>
		<!-- 确认支付 -->
		<view class="payBtn">
			<button size="default" @click="onPay">支付</button>
		</view>
	</view>
</template>

<script>
	import { info } from '@/apis/interfaces/order.js'
	import { oderinfo } from '@/apis/interfaces/synthesisOrder.js'
	import {
		coinPay,
		diffCoinPay,
		umsPay,
		umsState,
		diffUmsPay,
		umsFree,
		umsFreeInfo,
		dgPay,
		diffDgPay,
		dgFree,
		umsSynthesize,
		dgSynthesize,
		coinSynthesize,
		} from '@/apis/interfaces/pay.js'
	import mixin from 'uview-ui/libs/mixin/mixin';
	export default {
		data() {
			return {
				getState  	: false,
				trade_id  	: '',
				orderId	  	: '',
				diffId	  	: '',
				payMethod 	: 'coin',
				payType   	: 'price',
				total  	  	: '0.00',
				orderNo	  	: '',
				balance		: 0,
				isDeduction	: false,
				deductionVal: '',
				// 综法支付订单类型
				orderType	: '',
				rate		: 1,
				totalFire	: '',
				// 二维码支付
				payCodeShow	: false,
				payQrUrl	: '',
				payQrType	: ''
			};
		},
		onShow() {
			if(this.getState && this.trade_id != ''){
				this.onGetOrderPayState()
			}
		},
		created() {
			uni.showLoading({
				title: '获取订单信息...',
				mask : true
			})
			// 自由服务包订单信息
			if(this.$Route.query.paytype === 'free'){
				this.payMethod = "wx"
				umsFreeInfo(this.$Route.query.serviceId).then(res => {
					let { order_id, price, order_no } = res;
					this.orderId 	= order_id
					this.total 		= price
					this.orderNo 	= order_no
					this.payType	= this.$Route.query.paytype
					uni.hideLoading()
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
				return
			}
			// 综法订单支付
			if(this.$Route.query.paytype === 'synthesize'){
				let order_type = this.$Route.query.orderType.replace(/\-/g, '\\')
				oderinfo( this.$Route.query.orderId, order_type).then(res => {
					let { order_no, price, score, order_id, rate, total_fire } = res
					this.rate		= rate
					this.totalFire	= total_fire
					this.orderType	= order_type
					this.payType	= this.$Route.query.paytype
					this.orderId	= order_id
					this.total 		= price
					this.orderNo 	= order_no
					this.balance	= score
					uni.hideLoading()
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
				return
			}
			// 其他支付方式订单信息
			info(this.$Route.query.orderId).then(res => {
				let { total, order_no, business_order_id, diff_prices, diff, score } = res
				this.orderId 	= business_order_id
				this.diffId		= diff.business_order_diff_price_id
				this.payType 	= this.$Route.query.paytype
				this.total 		= this.payType === 'diff' ? diff_prices: total
				this.orderNo 	= order_no
				this.balance	= score
				uni.hideLoading()
			}).catch(err => {
				uni.showToast({
					title: err.message,
					icon : 'none'
				})
			})
		},
		methods: {
			// 查询订单状态
			onGetOrderPayState(){
				// 查询支付状态
				uni.showLoading({
					title: '查询支付结果...',
					mask : true
				})
				let outTime;
				let resNumb = 0;
				outTime = setInterval(() => {
					if(resNumb >= 3){
						clearInterval(outTime)
						uni.showToast({
							title: '暂未查询到你的支付订单',
							icon : 'none'
						})
						return
					}
					umsState(this.trade_id).then(res => {
						resNumb++
						if(res.state === 'success'){
							clearInterval(outTime)
							wx.showModal({
								title		: '提示',
								content 	: this.$Route.query.paytype === 'synthesize' ? '支付成功，可在工作台综法订单管理查询您的订单' : '支付成功',
								showCancel	: false,
								confirmColor: '#446EFE',
								success		: () => {
									this.onRrmoveItem()
								}
							})
						}
					}).catch(err => {
						clearInterval(outTime)
						uni.showToast({
							title: err.message,
							icon : 'none'
						})
					})
				}, 2000)
			},
			// 取消支付
			onCancel(){
				this.payCodeShow = false,
				this.payQrUrl	 = '',
				this.payQrType	 = ''
			},
			// 选择支付方式
			changeRadio(e){
				let { value } = e.detail
				this.payMethod = value
				// 初始化金额
				if(value == 'coin' || value == 'code'){
					this.isDeduction  = false
					this.deductionVal = 0
				}
			},
			// 抵扣金额
			onDeductionSwitch(e){
				this.deductionVal = ''
			},
			// 抵扣金额
			blurDeductionVal(e){
				let { value } = e.target
				let maxVal = Math.min(this.balance, this.total)
				if(value > maxVal){
					this.deductionVal = maxVal
				}
			},
			// 支付方式
			onPay(){
				switch(this.payMethod){
					case 'coin':
						if(this.payType == 'price') this.onCoinPay()
						if(this.payType == 'diff') this.onDiffCoinPay()
						if(this.payType == 'synthesize') this.onCoinSynthesizePay()
						break;
					case 'code':
						uni.showActionSheet({
							itemList:["微信付款码", "支付宝付款码"],
							success : actionRes => {
								if(actionRes.tapIndex === 0){
									if(this.payType == 'price') this.onDgPay('app', true)
									if(this.payType == 'diff') this.onDgDiffPay('app', true)
									if(this.payType == 'free') this.onDgFreePay('app', true)
									if(this.payType == 'synthesize') this.onFreeToast('onDgSynthesizePay', 'app', true)
								}
								if(actionRes.tapIndex === 1){
									if(this.payType == 'price') this.onDgPay('app_alipay', true)
									if(this.payType == 'diff') this.onDgDiffPay('app_alipay', true)
									if(this.payType == 'free') this.onDgFreePay('app_alipay', true)
									if(this.payType == 'synthesize') this.onFreeToast('onDgSynthesizePay', 'app_alipay', false)
								}
							}
						})
						break;
					case 'wx':
						if(this.payType == 'price') this.onUmsPay('app')
						if(this.payType == 'diff') this.onDiffUmsPay('app')
						if(this.payType == 'free') this.onFreePay('app')
						if(this.payType == 'synthesize') this.onFreeToast('onUmsSynthesizePay', 'app')
						break;
					case 'ali':
						if(this.payType == 'price') this.onUmsPay('app_alipay')
						if(this.payType == 'diff') this.onDiffUmsPay('app_alipay')
						if(this.payType == 'free') this.onFreePay('app_alipay')
						if(this.payType == 'synthesize') this.onFreeToast('onUmsSynthesizePay', 'app_alipay')
						break;
					case 'dgwx':
						if(this.payType == 'price') this.onDgPay('app', false)
						if(this.payType == 'diff') this.onDgDiffPay('app', false)
						if(this.payType == 'free') this.onDgFreePay('app', false)
						if(this.payType == 'synthesize') this.onFreeToast('onDgSynthesizePay', 'app', false)
						break;
					case 'dgali':
						if(this.payType == 'price') this.onDgPay('app_alipay', false)
						if(this.payType == 'diff') this.onDgDiffPay('app_alipay', false)
						if(this.payType == 'free') this.onDgFreePay('app_alipay', false)
						if(this.payType == 'synthesize') this.onFreeToast('onDgSynthesizePay', 'app_alipay', false)
						break
				}
			},
			// 火力值 - 综法
			onCoinSynthesizePay(){
				coinSynthesize({
					order_type	: this.orderType,
					order_id	: this.orderId
				}).then(res => {
					wx.showModal({
						title		: '提示',
						content 	: '火力值支付成功',
						showCancel	: false,
						confirmColor: '#446EFE',
						success		: () => {
							this.onRrmoveItem()
						}
					})
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 火力值使用提示
			onFreeToast(funName, type, isCode){
				if(this.isDeduction){
					let discount = this.deductionVal * this.rate
					let surplus  = Number(this.total) - (this.deductionVal * this.rate)
					uni.showModal({
						title		: '支付提示',
						content		: '本次支付使用火力值抵扣现金：' + discount.toFixed(2) + '元，您还需支付现金：' + surplus.toFixed(2) + '元',
						cancelText	: '取消支付',
						confirmText	: '继续支付',
						success		: res => {
							if(res.confirm){
								this[funName](type, isCode)
							}
						}
					})
					return
				}
				this[funName](type, isCode)
			},
			// 银联三方 - 综法
			onUmsSynthesizePay(type){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				umsSynthesize({
					type,
					order_type	: this.orderType,
					order_id	: this.orderId,
					fire		: this.deductionVal || 0,
					use_fire	: this.isDeduction ? 1 : 0,
					app_schema	: 'doufire://',
				}).then(res => {
					this.getState = true
					this.trade_id = res.trade_id
					switch (type){
						case 'app':
							this.onMiniWx()
							break;
						case 'app_alipay':
							plus.runtime.openURL(res.alipay)
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 斗拱 - 综法
			onDgSynthesizePay(type, code){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				dgSynthesize({
					type,
					order_type	: this.orderType,
					order_id	: this.orderId,
					fire		: this.deductionVal || 0,
					use_fire	: this.isDeduction ? 1 : 0,
					app_schema	: 'doufire://',
				}).then(res => {
					let { params, trade_id } = res;
					// 二维码支付
					if(code){
						this.onDgPayCode(type, params, trade_id)
						return
					}
					// 转跳付款
					this.getState = true
					this.trade_id = trade_id
					if(type == 'app'){
						let jumpUrl = JSON.parse(params.miniapp_data)
						plus.runtime.openURL(jumpUrl.scheme_code)
					}
					if(type == 'app_alipay'){
						plus.runtime.openURL(params.jump_url)
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 斗拱支付
			onDgPay(type, code){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				dgPay(this.orderId, {
					type,
					use_fire	: this.isDeduction ? 1 : 0,
					fire		: this.deductionVal || 0,
					app_schema	: 'doufire://'
				}).then(res => {
					let { params, trade_id } = res;
					uni.hideLoading()
					// 二维码支付
					if(code){
						this.onDgPayCode(type, params, trade_id)
						return
					}
					// 转跳付款
					this.getState = true
					this.trade_id = trade_id
					if(type == 'app'){
						let jumpUrl = JSON.parse(params.miniapp_data)
						plus.runtime.openURL(jumpUrl.scheme_code)
					}
					if(type == 'app_alipay'){
						plus.runtime.openURL(params.jump_url)
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 斗拱补差价
			onDgDiffPay(type, code){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				diffDgPay(this.diffId, {
					type,
					use_fire	: this.isDeduction ? 1 : 0,
					fire		: this.deductionVal || 0,
					app_schema	: 'doufire://'
				}).then(res => {
					let { params, trade_id } = res;
					uni.hideLoading()
					// 二维码支付
					if(code){
						this.onDgPayCode(type, params, trade_id)
						return
					}
					// 转跳付款
					this.getState = true
					this.trade_id = trade_id
					if(type == 'app'){
						let jumpUrl = JSON.parse(params.miniapp_data)
						plus.runtime.openURL(jumpUrl.scheme_code)
					}
					if(type == 'app_alipay'){
						plus.runtime.openURL(params.jump_url)
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 斗拱自由服务包
			onDgFreePay(type, code){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				dgFree(this.orderId, {
					type,
					app_schema	: 'doufire://'
				}).then(res => {
					let { params, trade_id } = res;
					uni.hideLoading()
					// 二维码支付
					if(code){
						this.onDgPayCode(type, params, trade_id)
						return
					}
					// 转跳付款
					this.getState = true
					this.trade_id = trade_id
					if(type == 'app'){
						let jumpUrl = JSON.parse(params.miniapp_data)
						plus.runtime.openURL(jumpUrl.scheme_code)
					}
					if(type == 'app_alipay'){
						plus.runtime.openURL(params.jump_url)
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 抖拱二维码付款
			onDgPayCode(type, params, trade_id){
				this.trade_id  		= trade_id
				this.payQrUrl  		= type == 'app_alipay' ? params.jump_url : 'https://dg-pay.douhuofalv.com?miniurlcode=' + encodeURIComponent(JSON.parse(params.miniapp_data).scheme_code)
				this.payQrType 		= type
				this.payCodeShow	= true
			},
			// 银联三方支付
			onUmsPay(type){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				umsPay(this.orderId, {
					type,
					use_fire: this.isDeduction ? 1 : 0,
					fire	: this.deductionVal || 0,
				}).then(res => {
					uni.hideLoading()
					this.getState = true
					this.trade_id = res.trade_id
					switch (type){
						case 'app':
							this.onMiniWx()
							break;
						case 'app_alipay':
							plus.runtime.openURL(res.alipay)
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			// 银联三方补差价支付
			onDiffUmsPay(type){
				uni.showLoading({
					title: '加载中...',
					mask : true
				})
				diffUmsPay(this.diffId, {
					type,
					use_fire: this.isDeduction ? 1 : 0,
					fire	: this.deductionVal || 0
				}).then(res => {
					uni.hideLoading()
					this.getState = true
					this.trade_id = res.trade_id
					switch (type){
						case 'app':
							this.onMiniWx()
							break;
						case 'app_alipay':
							plus.runtime.openURL(res.alipay)
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			// 银联三方自由服务包支付
			onFreePay(type){
				wx.showLoading({
					title: '加载中...',
					mask : true
				})
				umsFree(this.orderId, type).then(res => {
					uni.hideLoading()
					this.getState = true
					this.trade_id = res.trade_id
					switch (type){
						case 'app':
							this.onMiniWx()
							break;
						case 'app_alipay':
							plus.runtime.openURL(res.alipay)
							break;
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			// 火力值支付
			onCoinPay(){
				wx.showLoading({
					title: '支付中...',
					mask : true
				})
				coinPay(this.orderId).then(res => {
					wx.showModal({
						title		: '提示',
						content 	: '代缴费成功，请提醒用户尽快签约并完善资料',
						showCancel	: false,
						confirmColor: '#446EFE',
						success		: () => {
							this.onRrmoveItem()
						}
					})
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			// 火力值补差价支付
			onDiffCoinPay(){
				diffCoinPay(this.diffId).then(res => {
					wx.showModal({
						title		: '提示',
						content 	: '补缴差价成功',
						showCancel	: false,
						confirmColor: '#446EFE',
						success		: () => {
							this.onRrmoveItem()
						}
					})
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon : 'none'
					})
				})
			},
			// 打开微信小程序收银台
			onMiniWx(){
				let token   = this.$store.getters.getToken
				let tradeId = this.trade_id
				plus.share.getServices(e => {
					let wxIndex = e.findIndex(val => val.id == 'weixin')
					let sweixin = null
					if(wxIndex >= 0){
						sweixin = e[wxIndex]
						sweixin ? sweixin.launchMiniProgram({
							id	: 'gh_918c81628d6f',
							path: 'pages/pay/pay?type=app&trade_id=' + tradeId + '&token=' + token,
						}): uni.showToast({
							title: '当前环境暂不支持微信支付',
							icon : 'none'
						})
					}
				})
			},
			// 更新订单列表
			onRrmoveItem(){
				this.$store.commit('setOrderId', this.orderId)
				this.$Router.back()
			}
		}
	}
</script>

<style lang="scss">
	// 二维码收款
	.qrpay{
		padding: 50rpx;
		background: white;
		width: 80vw;
		box-sizing: border-box;
		border-radius: 20rpx;
		.title{ text-align: center; font-weight: bold; font-size: 40rpx; color: #333; padding-bottom: 50rpx; }
		.src{ background: #f8f8f8; width: 300rpx; height: 300rpx; margin: 0 auto; }
		.qrcode-src{ width: 300rpx; height: 300rpx; display: flex; align-items: center; justify-content: center; }
		.time{ text-align: center; padding-top: 20rpx; font-size: 28rpx; color: gray; }
		.btns{
			display: flex;
			justify-content: center;
			padding-top: 50rpx;
			.btn{
				margin: 0;
				height: 90rpx;
				line-height: 90rpx;
				font-size: 32rpx;
				font-weight: bold;
				border-radius: 10rpx;
				padding: 0 40rpx;
				&::after{ display: none; }
				&.confirm{ margin-left: 30rpx; background: $main-color; color: white; }
				&.cancel{ color: $main-color; border:solid 1rpx $main-color; background: white; box-sizing: border-box; line-height: 87rpx; }
			}
		}
	}
	// 支付收银台
	.pay{
		background: #f8f8f8;
		height: 100vh;
		width: 100vw;
		padding: 30rpx 30rpx 60rpx;
		box-sizing: border-box;
		.header{
			padding: 80rpx 0 100rpx;
			text-align: center;
			.header-title{
				font-size: 32rpx;
				padding-bottom: 10rpx;
			}
			.header-price{
				font-size: 68rpx;
				font-family: Arial, Helvetica, sans-serif;
				font-weight: bold;
				text{
					font-size: 60%;
				}
			}
			.header-no{
				padding-top: 20rpx;
				font-size: 28rpx;
				color: gray;
			}
			.header-fire{
				@extend .header-no;
				font-size: 30rpx;
				color: $text-price;
			}
		}
		// 支付抵扣
		.deduction{
			background: white;
			border-radius: 20rpx;
			padding: 10rpx 30rpx;
			margin-top: 30rpx;
			.deduction-item{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 0;
				.deduction-label{
					display: flex;
					flex-direction: column;
					justify-content: center;
					width: 300rpx;
					.title{ font-size: 32rpx; line-height: 40rpx; }
					.balance{ font-size: 26rpx; color: gray; line-height: 30rpx; margin-top: 5rpx; }
				}
				.deduction-input{
					height: 85rpx;
					width: calc(100% - 300rpx);
					text-align: right;
					font-size: 32rpx;
				}
			}
		}
		// 选择支付方式
		.choose{
			background-color: white;
			border-radius: 20rpx;
			padding: 10rpx 30rpx;
			.choose-item{
				display: block;
				padding: 20rpx 0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				&:last-child{
					border-bottom: none;
				}
				.choose-text{
					line-height: 80rpx;
					font-size: 32rpx;
					padding-left: 80rpx;
					position: relative;
					image{
						position: absolute;
						left: 0;
						top: 15rpx;
						width: 50rpx;
						height: 50rpx;
						border-radius: 10rpx;
					}
				}
				.choose-radio{
					transform:scale(0.8)
				}
			}
		}
		// 按钮
		.payBtn{
			padding: 50rpx 0;
			button[size="default"]{
				height: 100rpx;
				line-height: 100rpx;
				padding: 0;
				border-radius: 20rpx;
				background-color: $main-color;
				color: white;
				font-size: 32rpx;
				font-weight: bold;
				&::after{
					display: none;
				}
			}
		}
	}
</style>
