<template>
	<view>
		<view class="code-container " style="margin: 60rpx 35rpx;">
			<view class="title center">{{isPayment? "向商家付款":"扫一扫，向我付款"}}</view>
			<view class="main-content">
				<view v-if="isPayment">
					<!-- 占位 -->
					<view style="height: 50rpx;"></view>
					<!-- 条形码 -->
					<view class="bar-code center" style="overflow-x: hidden;margin: 0 30rpx;">
						<tki-barcode ref="barcode" :val="content" onval=true :opations="barOption" />
					</view>
					<!-- 付款码 -->
					<view class="qr-code center">
						<tki-qrcode  cid="2" ref="qrcode" :icon="avatar" :val="content" size="350" :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="500" :onval="true"
						:loadMake="true" :usingComponents="true" />
				</view>
			</view>
			<view class="footer center flex-direction"  :style="$isNotEmpty(vuex_channel)?'padding: 30rpx 0rpx;':''">
				<text class="text-xl text-bold">{{nickName}}</text>
				<!-- #ifdef  MP-WEIXIN-->
				<view style="width: 100%;padding: 0;">
					<channel-list></channel-list>
				</view>
				<!-- #endif -->
			</view>
			
		</view>
	</view>
</template>

<script>
	import channelList from '@/components/channel-list.vue'
	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"
	import crypto from "@/utils/crypto.js"
	export default {
		components: {
			channelList,
			tkiBarcode,
			tkiQrcode
		},
		computed: {
			content() {
				let transformStr = this.id
				let qrcodeText=transformStr + this.secret + ";" + (this.vuex_channel ? this.vuex_channel.id : 0)
				return crypto.encrypt(qrcodeText)
			}
		},
		data() {
			return {
				isFirst:true,
				id: '',
				avatar: "",
				nickName: '',
				secret: '000000',
				isPayment: true,
				timer: '',
				barOption: {
					width: 1,
					height: 120,
					displayValue: false
				},
				//webSocket
				webSocket: {},
				receiveId: '',
				payResult: {
					isSuccess: false,
					msg: "交易失败",
					//总价
					totalPrice: 0,
					//消耗积分值
					pointsNum: 0,
					//消耗现金值
					amountNum: 0,
				}
			}
		},	
		async onLoad(options) {
			uni.setKeepScreenOn({
			    keepScreenOn: true
			});
			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
			//生成动态密码
			if (this.isFirst) {
				this.secret = totp.getSecret(this.id);
				console.log(this.secret);
			}
			this.isFirst=false
			this.refreshCode();
		},
		onUnload() {
			this.handelOut()
		},
		onHide() {
			this.handelOut()
		},
		onBackPress() {
			this.handelOut()
		},
		methods: {
			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)
			},
			getSecret(){
				this.secret = totp.getSecret(this.id);
			},
			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: #0aa98b;
	}
</style>
<style lang="scss" scoped>
	$color:#0aa98b;
	.popup-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 30rpx 0;
		height: 100%;

		.channelbtn {
			background-color: $color;
			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: $color;
				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;

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

		.footer {
			width: 100%;
			padding:40rpx 0rpx;
			border-top: 1rpx dashed #dddddd;
		}

		.main-content {
			width: 100%;
			height: 700rpx;

			// overflow: hidden;
			.bar-code {
				height: 170rpx;
			}

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

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