<template>
	<view class="code-container">
		<view class="title center">{{isPayment? "向商家付款":"扫一扫，向我付款"}}</view>
		<view class="main-content">
			<view v-if="isPayment">
				<!-- 占位 -->
				<view style="height: 50rpx;"></view>
				<!-- 条形码 -->
				<view class="bar-code center">
					<tki-barcode ref="barcode" :val="content" onval=true :opations="barOption" />
				</view>
				<!-- 付款码 -->
				<view class="qr-code center">
					<tki-qrcode cid="2" ref="qrcode" :val="content" size="320" :onval="true" :loadMake="true"
						:usingComponents="true" />
				</view>
			</view>
			<!-- 收款码 -->
			<view v-else class="charge-code center">
				<tki-qrcode cid="1" ref="qrcode-charge" :val="id" :icon="avatar" size="440" :onval="true"
					:loadMake="true" :usingComponents="true" />
			</view>
		</view>
		<view class="footer center flex-direction">
			<text class="text-xl text-bold">{{nickName}}</text>
			<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>
		</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 class="cu-btn radius channelbtn">
						确认
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import tkiQrcode from "../../comps/tki-qrcode/tki-qrcode.vue"
	import tkiBarcode from "../../comps/tki-barcode/tki-barcode.vue"
	import totp from "../../utils/totp.js"
	import socket from "../../utils/socket.js"
	export default {
		components: {
			tkiBarcode,
			tkiQrcode
		},
		computed: {
			content() {
				let transformStr = this.id
				return transformStr + this.secret+";"+this.channelId
			}
		},
		data() {
			return {
				//渠道积分
				channel:[],
				channelShow:false,
				channelId:0,
				
				id: '',
				avatar: "",
				nickName: '',
				secret: '000000',
				isPayment: true,
				timer: '',
				barOption: {
					width: 3,
					height: 130,
					displayValue: false
				},
				//webSocket
				webSocket: {},
				receiveId: '',
				payResult: {
					isSuccess: false,
					msg: "交易失败",
					//总价
					totalPrice: 0,
					//消耗积分值
					pointsNum:0,
					//消耗现金值
					amountNum:0,
				}
			}
		},
		async onLoad(options) {
			//获取用户的渠道积分
			this.getUserPonint()
			
			let res = await this.$api.loginUser.detail({
				id: this.vuex_userId
			})
			this.nickName = res.data.nickName
			// this.avatar =(await  this.initAvatat(res.data.avatar)).tempFilePath;
			//连接websocket
			this.onSocketOpen()
		},
		async mounted() {
			//获取用户ID
			this.id = this.vuex_userId
			//生成动态密码
			this.refreshCode();
		},
		onUnload() {
			this.handelOut()
		},
		onHide() {
			this.handelOut()
		},
		onBackPress() {
			this.handelOut()
		},
		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
					}
				})
			},
			handelOut() {
				uni.hideLoading()
				this.webSocket.closeSocket()
				clearInterval(this.timer);
			},
			// 启动webSocket
			onSocketOpen() {
				this.webSocket = new socket({
					sid: this.$global.socket_prefix + this.vuex_userId
				})
				this.webSocket.init(() => {
					console.log("启动成功");
				});
				this.webSocket.error = () => {
					this.webSocket.closeSocket();
					this.$dialog.showModalAndBack('网络异常')
				}
				this.webSocket.acceptMessage = (res) => {
					uni.hideLoading()
					if (!this.$isEmpty(res.price)) {
						this.receiveId = res.receiveId
						this.payResult.totalPrice = res.cost
						this.payResult.amountNum = res.price
						this.payResult.pointsNum =this.$digital.floatSub(res.cost,res.price)
						//调起微信支付
						this.toPay(res.id)
					}
					if (res.isSuccess) {
						console.log(res);
						this.payResult=res
						this.payResult.pointsNum=res.totalPrice
						this.payResult.amountNum = 0
						uni.navigateTo({
							url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(res),
						})
					}
				}

			},
			refreshCode() {
				this.timer = setInterval(() => {
					this.secret = totp.getSecret(this.id);
					console.log(this.secret);
				}, 1000)
			},
			async initAvatat(url) {
				return new Promise((reslove, reject) => {
					uni.downloadFile({
						url,
						success: (res) => {
							reslove(res);
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			async toPay(orderId) {
				//去支付
				let params = {
					orderType: this.$global.orderType.USER_PAY,
					orderId,
					payStatus: this.$global.payStatus.IS_WAIT
				}
				let res = await this.$api.pay.payOrder(params)
				if (!this.$isEmpty(res.data.prePayTn)) {
					let prePayTn = JSON.parse(res.data.prePayTn)
					this.$mpi.requestPayment(prePayTn).then(() => {
						this.handelResult(true)
					}).catch(err => {
						this.handelResult(false)
					})
					return
				}
				this.handelResult(false)
			},
			handelResult(flag) {
				if (flag) {
					this.payResult.msg = '交易成功'
					this.payResult.isSuccess = true
				} else {
					this.payResult.msg = '交易失败'
					this.payResult.isSuccess = false
				}
				this.sendInfo()
				uni.navigateTo({
					url: "/pagesC/pages/checkstand/pay-result?payResult=" + JSON.stringify(this.payResult)
				})
			},
			sendInfo() {
				let msg = {
					sid: this.$global.socket_prefix_SHOP + this.receiveId,
					content: JSON.stringify(this.payResult),
				}
				this.$api.webSocket.sendInfo(msg)
			},
		},
	}
</script>

<style>
	page {
		background-color: #18b566;
	}
</style>
<style lang="scss" scoped>
	.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;
			}
			
		}
	}
	
	
	
	.channel{
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
		
		.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;
		}
		
	}
	
	.code-container {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		min-height: 800rpx;
		margin: 60rpx 20rpx;

		.title {
			border-radius: 25rpx 25rpx 0 0;
			height: 100rpx;
			width: 100%;
			font-size: 35rpx;
			color: #18b566;
			background-color: #F7F7F7;
			font-weight: 600;
			letter-spacing: 3rpx;
		}

		.footer {
			width: 96%;
			padding: 30rpx;
			margin-left: 2%;
			border-top: 1rpx dashed #dddddd;
		}

		.main-content {
			width: 100%;
			height: 600rpx;
			scroll-margin-top: 600rpx;

			// overflow: hidden;
			.bar-code {
				margin-left: 5%;
				width: 90%;
				height: 150rpx;
			}

			.qr-code {
				width: 100%;
				height: 450rpx;
			}

			.charge-code {
				width: 100%;
				height: 600rpx;
				transition: transform 1s ease-in-out;
			}
		}
	}
</style>
