<template>
	<view class="">
		<!-- #ifdef  MP-WEIXIN-->
		<view class="">
			<u-navbar title="收银台"></u-navbar>
		</view>
		<!-- #endif -->

		<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>
		<!-- #ifdef  MP-WEIXIN-->
		<view v-if="$isNotEmpty(channel)" @click="channelShow=true" class="channel " style="width: 100%;">
			<view class="left">
				<view class="center">
					<image :src="channel[0].channelLogo" mode=""></image>
				</view>
				<view class="content">
					<text>{{channel[0].channelName}}</text>
					<text>优先使用该渠道积分支付</text>
				</view>
			</view>
			<view class="right">
				<text class="cuIcon-right"></text>
			</view>
		</view>
		<u-popup :closeable="true" v-model="channelShow" mode="bottom" height="65%">
			<view class="popup-content">
				<view class="">
					<view style="border-bottom: 1rpx solid #eee;" class="fixed center text-bold text-lg padding-bottom-40">
						请选择优先使用的渠道积分
					</view>
					<view @click="channelId=item.channelId" v-for="(item,index) in channel" :key="index" class="channel-item">
						<image :src="item.channelLogo" mode=""></image>
						<text class="margin-left-10">{{item.channelName}}（剩余 ￥ {{item.available}}）</text>
						<text v-if="channelId==item.channelId" class="cuIcon-check checked"></text>
					</view>
				</view>
				<view class="center">
					<view @click="channelShow=false" class="cu-btn radius channelbtn">
						确认
					</view>
				</view>
			</view>
		</u-popup>
		<!-- #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>
</template>

<script>
	import amountInput from '../../comps/amountInput/amountInput.vue';
	export default {
		components: {
			amountInput
		},
		data() {
			return {
				//渠道积分
				channel:[],
				channelShow:false,
				channelId:0,
				
				//第一次点击支付不需要防抖操作
				isFirstPay: true,
				orderAmount: '',
				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
			}
			this.getUserPonint()
			// #endif

			if (this.$isEmpty(this.shopId)) {
				this.$dialog.showModal('商户id不能为空', false).then(() => {
					uni.navigateBack()
				})
				return
			}
			this.fetchShopDetail()
		},
		methods: {
			//获取用户渠道积分
			getUserPonint(){
				let params={
					userId:this.vuex_userId
				}
				this.$api.userChannelPoint.list(params).then(res=>{
					if (this.$isNotEmpty(res.data.records)) {
						this.channel=res.data.records
						this.channelId=this.channel[0].channelId
					}
				})
			},
			//防抖支付
			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)
				if (!this.$isEmpty(res.data.qrCodeUrl)) {
					location.href = res.data.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,
					channelId:this.channelId
				}
				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.doWxPay(resp.data.bills.id)
				}else{
					this.handelResult(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;
		}
	}
	
	.channel{
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
		padding:0 30rpx;
		
		.left{
			display: flex;
			image{
				width: 60rpx;
				height: 60rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			view{
				display: flex;
				flex-direction: column;
			}
			
			.content{
				margin-left: 16rpx;
				
				text:first-child{
					font-size: 34rpx;
					margin-bottom: 10rpx;
				}
				
				text:last-child{
					font-size: 28rpx;
					color: #989898;
				}
			}
		}
		
		.right{
			display: flex;
			justify-content: center;
			align-items: center;
		}
		
	}
	
	.popup-content{
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 40rpx 0;
		height: 100%;
		
		.channelbtn{
			background-color: #18b566;
			color: #FFFFFF;
			padding: 36rpx 150rpx;
		}
		
		.channel-item{
			position: relative;
			display: flex;
			padding: 30rpx;
			border-bottom: 1rpx solid #eee;
			image{
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}
			
			.checked{
				color: #18b566;
				font-size: 34rpx;
				position: absolute;
				font-weight: 800;
				right: 40rpx;
				bottom: 30rpx;
			}
			
		}
	}
</style>
