<template>
	<view class=""  :style="{'height':height}">
		<!-- #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>
			
			<!-- #ifdef  MP-WEIXIN-->
			<view style="margin-top: -20rpx;">
				<channel-list ></channel-list>
			</view>
			<!-- #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>
		
		<toast ref="toast" ></toast>
		<pay-confirm confirmText="确认" :params="params" cancelText="继续支付" :type="payConfirmType" v-show="payShow" :info="info" @confirm="confirmClick" @cancel="cancelClick"></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';
	import crypto from "@/utils/crypto.js"
	export default {
		components: {
			payConfirm,
			channelList,
			amountInput
		},
		data() {
			return {
				height:'',
				
				isH5:false,
				//navbar
				title:"收银台",
				isBack:true,
				
				//第一次点击支付不需要防抖操作
				isFirstPay: true,
				orderAmount: '',
				//支付bills信息
				payShow:false,
				payConfirmType:'',
				info:{},
				bills:{},
				
				modalShow: false,
				shopId: '',
				shopDetail: {},
				//支付参数 
				payParams: {},
				//支付结果
				payResult: {
					isSuccess: false,
					msg: "交易失败",
					//总价
					totalPrice: 0,
					//消耗积分值
					pointsNum: 0,
					//消耗现金值
					amountNum: 0,
				}
			}
		},
		async onLoad(options) {
			this.height=this.$u.sys().windowHeight + 'px';
			if (!this.$isEmpty(options.query)) {
				//h5跳转回小程序后重新赋值
				let params = options.query.split(";")
				this.shopId = params[0]
				this.orderAmount = params[1]
				this.$refs.amountInput.initialMoney(this.orderAmount)
				this.isH5=true
			} else {
				this.isH5=false
				this.shopId = crypto.decrypt(options.data)
			}

			// #ifdef  MP-WEIXIN
			//如果是新用户通过h5微信支付扫码进入此页面，跳回首页
			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.showModalAndBack('商户id不能为空')
				return
			}
			this.fetchShopDetail()
		},
		onShow() {
			console.log(this.orderAmount);
		},
		methods: {
			handelScanResult(res){
				let result=res.result
				/**
				 * urlParams
				 * url和加密的参数 ["/pagesC/pages/checkstand/index","cA8f31EnoYduLe52YELaV109iQpDEOxcDQYxiizK6BA="]
				 */
				let urlParams=result.split("#")[1].split("?")
				//解密参数
				let decryptParams=crypto.decrypt(urlParams[1])
				if (this.$isEmpty(decryptParams)) {
					this.$refs.toast.error('参数异常')
					return
				}
				//重新拼接url
				let url=urlParams[0]+"?"+decryptParams
				this.jump(url)
			},
			isWxBrowser(){
				let na = navigator.userAgent.toLowerCase()
				return na.indexOf('micromessenger') !== -1
			},
			//防抖支付
			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.showModalAndBack('获取不到商户信息')
						return
					}
					this.shopDetail = res.data
					if (this.$isNotEmpty(this.orderAmount)&&this.isH5) {
						//从h5跳转回来后，直接付款
						this.pay()
					}
				}).catch(err => {
					this.$dialog.showModalAndBack('获取不到商户信息')
				})
			},
			//获取用户信息
			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.$refs.toast.error('支付失败')
				}
			},
			async pay() {
				if (!this.orderAmount.length || this.orderAmount == 0) {
					this.$refs.toast.warn('请输入交易金额')
					return
				}
				// #ifdef  H5
				if (this.$isWxBrowser()) {
					//如果是微信浏览器打开
					this.modalShow = true
				}else{
					//直接支付
					this.payOfh5()
				}
				// #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
				this.bills=resp.data.bills
				if (this.bills.discount==-1) {
					this.bills.discount=0
				}
				if (resp.data.status == '付款成功') {
					this.handelResult(true)
				} else if (resp.data.status == '待付款') {
					if (this.bills.cost==this.bills.price) {
						this.doWxPay(this.bills.id)
					}else{
						this.info={
							shop:this.shopDetail,
							bills:this.bills,
						}
						this.payConfirmType=''
						this.title="支付确认"
						this.isBack=false
						this.payShow=true
					}
					
				} 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),
					// }
					// uni.navigateTo({
					// 	url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(this.payResult)
					// })
					// return
					
					//本页显示支付结果+抵扣详情
					this.info={
						shop:this.shopDetail,
						bills:this.bills,
					}
					this.payConfirmType='paySuccess'
					this.title="支付结果"
					this.isBack=false
					this.payShow=true
					return
				}
				this.payResult.msg = '交易失败'
				this.payResult.isSuccess = false
				uni.navigateTo({
					url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(this.payResult)
				})
				
			},
			confirmClick(){
				if (this.payConfirmType=='paySuccess') {
					uni.reLaunch({
						url:"/pages/mine/mine"
					})
					return
				}
				this.doWxPay(this.bills.id)
			},
			cancelClick(){
				this.title="收银台"
				this.isBack=true
				this.payShow=false
			}
			
		}
	}
</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>
