<template>
	<view class="">
		<!-- #ifdef  MP-WEIXIN-->
		<view class="">
			<u-navbar :isBack="isBack" :title="title"></u-navbar>
		</view>
		<!-- #endif -->

		<view class="" v-show="!payShow">
			<view class="shopInfo">
				<image :src="shopDetail.cover" mode=""></image>
				<text>{{shopDetail.name}}</text>
			</view>
			<view class="data">
				<text style="color: #000;">付款金额</text>
				<view class="price">
					<view class="input-bar center" @tap="show">
						<view class="icon center">￥</view>
						<view class="input" style="display: flex; align-items: center;">
							<view style="font-size: 80rpx;">{{filterMoney(orderAmount)}}</view>
							<view class="cusor"></view>
						</view>
					</view>
				</view>
				<view class="text-center text-base padding-top-20">
					<text>*使用联兑通付款有优惠打折</text>
				</view>
			</view>
			
			<view style="margin-top: -20rpx;">
				<channel-list ></channel-list>
			</view>
			<!-- #ifdef  MP-WEIXIN-->
			
			<!-- #endif -->
			
			<amountInput ref="amountInput" confirmText="付款" btnColor="#ff9900" placeholder="请输入交易金额" @change="change"
				@confirm="debouncePay"></amountInput>
			
			<u-modal v-model="modalShow" :mask-close-able="true" :showCancelButton="true" @cancel="payOfh5"
				@confirm="jumpLDT" cancel-text="直接付款" confirm-color="#FF9447" confirmText="去联兑通支付"
				content="去联兑通小程序付款有更多优惠哟~"></u-modal>
		</view>
		
		<pay-confirm v-show="payShow" :info="info" @confirm="doWxPay(bills.id)" @cancel="cancelPay"></pay-confirm>
	</view>
</template>

<script>
	import payConfirm from '@/components/pay-confirm.vue'
	import channelList from '@/components/channel-list.vue'
	import amountInput from '../../comps/amountInput/amountInput.vue';
	export default {
		components: {
			payConfirm,
			channelList,
			amountInput
		},
		data() {
			return {
				//navbar
				title:"收银台",
				isBack:true,
				
				//第一次点击支付不需要防抖操作
				isFirstPay: true,
				orderAmount: '',
				//支付bills信息
				payShow:false,
				info:{},
				bills:{},
				
				modalShow: false,
				shopId: '',
				shopDetail: {},
				//支付参数 
				payParams: {},
				//支付结果
				payResult: {
					isSuccess: false,
					msg: "交易失败",
					//总价
					totalPrice: 0,
					//消耗积分值
					pointsNum: 0,
					//消耗现金值
					amountNum: 0,
				}
			}
		},
		async onLoad(options) {
			if (!this.$isEmpty(options.query)) {
				//h5跳转回小程序后重新赋值
				let params = options.query.split(";")
				this.shopId = params[0]
				this.orderAmount = params[1]
			} else {
				this.shopId = options.id
			}

			// #ifdef  MP-WEIXIN
			//如果是新用户通过微信支付扫码进入此页面，跳回首页
			if (this.$isEmpty(this.vuex_userId)) {
				uni.reLaunch({
					url: "/pages/mine/mine?query=" + this.shopId + ";" + this.orderAmount
				})
				return
			}
			//如果用户信息为空，阻断
			let flag = await this.fetchUserDetail()
			if (!flag) {
				this.$dialog.showModal('用户信息获取失败', false).then(() => {
					uni.reLaunch({
						url: "/pages/mine/mine"
					})
				})
				return
			}
			// #endif

			if (this.$isEmpty(this.shopId)) {
				this.$dialog.showModal('商户id不能为空', false).then(() => {
					uni.navigateBack()
				})
				return
			}
			this.fetchShopDetail()
		},
		onShow() {
			console.log(this.orderAmount);
		},
		methods: {
			//防抖支付
			debouncePay() {
				if (this.isFirstPay) {
					this.pay()
					this.isFirstPay = false
				} else {
					this.$u.debounce(this.pay, 500)
				}
			},
			//获取商户信息
			fetchShopDetail() {
				this.$api.shop.detail({
					id: this.shopId
				}).then(res => {
					if (this.$isEmpty(res.data)) {
						this.$dialog.showModal('获取不到商户信息', false).then(() => {
							uni.navigateBack({
								delta: 1
							})
						})
					} else {
						this.shopDetail = res.data
					}
				}).catch(err => {
					this.$dialog.showModal('获取不到商户信息', false).then(() => {
						uni.navigateBack({
							delta: 1
						})
					})
				})
			},
			//获取用户信息
			async fetchUserDetail() {
				let res = await this.$api.loginUser.detail({
					id: this.vuex_userId
				})
				if (this.$isEmpty(res.data)) {
					return false
				} else {
					return true
				}
			},
			show() {
				this.$refs.amountInput.show()
			},
			change(e) {
				if (!e) {
					this.orderAmount = 0
				} else {
					this.orderAmount = e
				}
			},
			filterMoney(value) {
				if (!value) {
					return ''
				} else {
					value = value.replace(/\$\s?|(,*)/g, '')
					return value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
				}
			},
			async jumpLDT() {
				this.$dialog.showLoading('打开中..')
				let params = {
					path: "/pagesC/pages/checkstand/index",
					query: "query=" + this.shopId + ";" + this.orderAmount
				}
				let res = await this.$api.wxApp.getGenerateScheme(params)
				if (!this.$isEmpty(res.data.openlink)) {
					location.href = res.data.openlink
				} else {
					location.href = "weixin://dl/business/?t=X2CyIQDbgtm"
				}
				uni.hideLoading()
			},
			async payOfh5() {
				let expireTime = this.$dateTime.getExpireTime(5)
				let params = {
					expireTime,
					money: this.orderAmount,
					shopId: this.shopId,
				}
				let resp = await this.$api.pay.getPayOrderPamamsForH5(params)
				let payObj = {
					orderType: this.$global.orderType.USER_PAY,
					orderId: resp.data.id
				}
				let res = await this.$api.pay.payOrderOfscanCode(payObj)
				let qrCodeUrl=JSON.parse(res.data.result).qrCodeUrl
				if (this.$isNotEmpty(qrCodeUrl)) {
					location.href = qrCodeUrl
				} else {
					this.$u.toast('支付失败')
				}
			},
			async pay() {
				if (!this.orderAmount.length || this.orderAmount == 0) {
					this.$u.toast('请输入交易金额')
					return
				}
				// #ifdef  H5
				this.modalShow = true
				// #endif

				// #ifdef MP-WEIXIN
				this.toWXPay()
				// #endif
			},
			async toWXPay() {
				let expireTime = this.$dateTime.getExpireTime(5)
				let params = {
					userId: this.vuex_userId,
					appId: this.$global.wxParams.APPID,
					billsTitle: '用户扫码支付',
					money: this.orderAmount,
					expireTime,
					shopId: this.shopId,
					openId: this.$cache.get('userInfo').openId,
				}
				if (this.$isNotEmpty(this.vuex_channel)) {
					params.channelId=this.vuex_channel.id
				}
				
				let resp = await this.$api.pay.getPayOrderPamams(params)
				this.payParams = resp.data
				
				
				if (resp.data.status == '付款成功') {
					this.handelResult(true)
				} else if (resp.data.status == '待付款') {
					this.bills=resp.data.bills
					if (this.bills.discount==-1) {
						this.bills.discount=0
					}
					if (this.bills.cost==this.bills.price) {
						this.doWxPay(this.bills.id)
					}else{
						this.info={
							shop:this.shopDetail,
							bills:this.bills,
						}
						this.title="支付确认"
						this.isBack=false
						this.payShow=true
					}
					
				} else {
					this.handelResult(false)
				}
			},
			cancelPay(){
				this.title="收银台"
				this.isBack=true
				this.payShow=false
			},
			async doWxPay(orderId) {
				let obj = {
					orderType: this.$global.orderType.USER_PAY,
					orderId,
					payStatus: this.$global.payStatus.IS_WAIT
				}
				let res = await this.$api.pay.payOrder(obj)
				let prePayTn = JSON.parse(res.data.prePayTn)
				this.$mpi.requestPayment(prePayTn).then((res) => {
					this.handelResult(true)
				}).catch(err => {
					this.handelResult(false)
				})
			},
			handelResult(flag) {
				if (flag) {
					this.payResult = {
						isSuccess: true,
						msg: "交易成功",
						totalPrice: this.payParams.totalPrice,
						amountNum: this.payParams.bills.price,
						pointsNum: this.$digital.floatSub(this.payParams.totalPrice, this.payParams.bills.price),
					}
				} else {
					this.payResult.msg = '交易失败'
					this.payResult.isSuccess = false
				}
				uni.navigateTo({
					url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(this.payResult)
				})
			},
		}
	}
</script>

<style>
	page {
		background-color: #ffff;
	}
</style>

<style lang="scss" scoped>
	.shopInfo {
		margin: 60rpx 0 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		image {
			border-radius: 50%;
			width: 140rpx;
			height: 140rpx;
		}

		text {
			margin-top: 30rpx;
			font-size: 32rpx;
		}
	}

	.data {
		padding: 50rpx;
		display: flex;
		justify-content: flex-start;
		flex-direction: column;

		.price {

			&-icon {
				font-size: 40rpx;
				font-weight: 800;
			}
		}
	}

	.center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.input-bar {
		height: 150rpx;
		border-bottom: 1rpx solid #DDDDDD;

		.icon {
			width: 15%;
			font-size: 70rpx;
			font-weight: 900;
			height: 100%;
		}

		.input {
			width: 85%;
			height: 100%;
			overflow: hidden;
			font-size: 70rpx;
		}

		.cusor {
			margin-left: 10rpx;
			width: 6rpx;
			border-radius: 20rpx;
			height: 60%;
			background-color: #ff9900;
			animation: blink 1200ms infinite ease-in-out;
		}
	}

	@keyframes blink {
		from {
			opacity: 0;
		}
	}
</style>
