<template>
	<view class="content" :class="{ blueBg: actionInd!=1,greenBg:actionInd==1}">
		<view class="coupon_transfer" >
			<view class="user">
				<view class="imgbox"><image class="img" :src="userinfo.avatar" mode=" scaleToFill"></image></view>
				<view class="niceName">{{ userinfo.nickname }}</view>
			</view>
			<view class="erwema">
				<view class="qrbox">
					<view class="payMoney" v-if="actionInd == 1">收款码</view>
					<view class="payMoney" v-if="actionInd == 0">付款码</view>
					<tki-qrcodes
						:cid="cid"
						ref="qrcode"
						:val="val"
						:size="size"
						:unit="unit"
						:background="background"
						:foreground="foreground"
						:pdground="pdground"
						:icon="icon"
						:iconSize="iconSize"
						:lv="lv"
						:onval="onval"
						:loadMake="loadMake"
						:usingComponents="usingComponents"
						@result="qrR"
					></tki-qrcodes>
					<!-- <view class="setMoney" @click="openApp">
						设置金额
					</view> -->
				</view>
			</view>
		</view>
		<view class="bottomTab flex">
			<view class="item1" @click="clickItem(0)" :class="{ action: actionInd == 0 }">
				<view><image class="img" src="../../static/icon/pay2.png" mode=" widthFix"></image></view>
				<view class="text">付款码</view>
			</view>
			<view class="item1" @click="clickItem(1)" :class="{ action: actionInd == 1 }">
				<view><image class="img" src="../../static/icon/pay1.png" mode=" widthFix"></image></view>
				<view class="text">收款码</view>
			</view>
			<view class="item1" @click="clickItem(2)" :class="{ action: actionInd == 2 }">
				<view><image class="img" src="../../static/icon/pay3.png" mode=" widthFix"></image></view>
				<view class="text">扫一扫</view>
			</view>
			<view class="item1" @click="openList" :class="{ action: actionInd == 3 }">
				<view><image class="img" src="../../static/icon/pay4.png" mode=" widthFix"></image></view>
				<view class="text">记录</view>
			</view>
		</view>
		<uniPopup ref="popup1" type="dialog">
			<uni-popup-dialog
				mode="input"
				type="input"
				title="支付"
				placeholder="请输入支付金额"
				:duration="2000"
				:before-close="true"
				@close="close"
				@confirm="confirm"
			></uni-popup-dialog>
		</uniPopup>
		<uniPopup ref="popup2" type="message"><uni-popup-message type="success" message="支付成功" :duration="2000"></uni-popup-message></uniPopup>
	</view>
</template>

<script>
import tkiQrcodes from '@/components/tki-qrcode/tki-qrcode.vue';
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import uniPopupDialog from '@/components/uni-popup/uni-popup-dialog.vue';
import uniPopupMessage from '@/components/uni-popup/uni-popup-message.vue';
import { getUserInfo } from '@/api/login.js';
import { receivedCollectionCode, receivedPaymentCode, receivedCodeState, receivedPaymentCreate, receivedLst, collectionLst, collectionSetTip } from '@/api/received.js';
// #ifdef H5
import { mapState } from 'vuex';
import { weixindata } from '@/utils/wxAuthorized';
// #endif
import Voice from '@/utils/QS-baiduyy.js';
export default {
	components: { tkiQrcodes, uniPopup, uniPopupDialog, uniPopupMessage },
	// #ifdef H5
	computed: {
		...mapState(['weichatObj'])
	},
	// #endif
	data() {
		return {
			url: '',
			uid: '',
			qrsize: 80, // 二维码大小
			cid: 'tki-qrcode-canvas', //canvasId，页面存在多个二维码组件时需设置不同的ID
			size: 500, //生成的二维码大小
			unit: 'upx', //大小单位尺寸
			// show: true,//默认使用组件中的image标签显示二维码
			val: '', //要生成的内容
			background: '#ffffff', //二维码背景色
			foreground: '#333333', //二维码前景色
			pdground: '#333333', //二维码角标色
			icon: '', //二维码图标URL（必须是本地图片，网络图需要先下载至本地）
			iconSize: 40, //二维码图标大小
			lv: 3, //容错级别
			onval: true, //监听val值变化自动重新生成二维码
			loadMake: false, //组件初始化完成后自动生成二维码，val需要有值
			usingComponents: false, //是否使用了自定义组件模式（主要是为了修复非自定义组件模式时 v-if 无法生成二维码的问题）
			showLoading: false, //是否显示loading
			loadingText: '二维码生成中', //loading文字
			src: '', // 二维码生成后的图片地址或base64
			ratio: 1, //页面比例用于计算
			ctxSrc: '', //要显示的图片
			loading: true, //是否载入图片中
			canHeight: '',
			canWeidth: '',
			userinfo: {}, //用户信息
			actionInd: 1, //默认展示收款码
			setTimeOutPay: null, //付款倒计时
			getMoneyList: null, //收款记录倒计时倒计时
			showSqr: true,
			code: '', //保存扫码code
			indexNum: 0 //默认没有商品
		};
	},

	onLoad(option) {
		this.loadlist;
		this.userinfo = uni.getStorageSync('userInfo');
		// 加载用户数据
		this.getUserInfo();
		// #ifdef H5
		// 获取是否为微信内核浏览器
		this.showSqr = uni.getStorageSync('weichatBrowser') || false;
		weixindata();
		// #endif
	},
	onReady() {
		// Voice('成功收款100000000元')
	},
	onShow() {
		// 开启倒计时
		this.setTimePay();
	},
	onHide() {
		clearInterval(this.setTimeOutPay);
		clearInterval(this.getMoneyList);
	},
	// 监听页面卸载
	onUnload() {
		// 关闭倒计时
		clearInterval(this.setTimeOutPay);
		clearInterval(this.getMoneyList);
	},
	// 监听页面后退
	onBackPress() {
		// 关闭倒计时
		clearInterval(this.setTimeOutPay);
		clearInterval(this.getMoneyList);
	},
	methods: {
		// 获取收款记录
		collectionLst() {
			collectionLst()
				.then(e => {
					console.log(e);
					// 循环处理播报语音
					e.data.data.forEach((d, ind) => {
						Voice({
							voiceSet: {
								tex: '满园春收款' + (+d.amount - d.service_charge) + '元'
							},
							audioSet: {
								volume: 1
							},
							lineUp: true // 加入语音队列
						});
						//清除记录
						collectionSetTip({ id: d.id });
					});
				})
				.catch(e => {});
		},
		// 获取用户信息
		getUserInfo() {
			let obj = this;
			getUserInfo({})
				.then(({ data }) => {
					obj.userinfo = data;
					// 加载收款码
					obj.receivedCollectionCode();
					// 调用循环
					// obj.setTimePay();
					// #ifdef H5
					uni.showModal({
						title: '提示',
						content: '打开支付提示成功！',
						showCancel: false,
					});
					// #endif
				})
				.catch(e => {
					console.log(e);
				});
		},
		/**
		 * 点击取消按钮触发
		 * @param {Object} done
		 */
		close(done) {
			// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 done 才会关闭对话框
			// ...
			done();
		},
		/**
		 * 点击确认按钮触发
		 * @param {Object} done
		 * @param {Object} value
		 */
		confirm(done, value) {
			// 输入框的值
			receivedPaymentCreate({
				code: this.code,
				amount: value
			})
				.then(({ data }) => {
					uni.showModal({
						title: '提示',
						content: '成功',
						showCancel: false
					});
				})
				.catch(e => {
					uni.showModal({
						title: '提示',
						content: e.message,
						showCancel: false
					});
					console.log(e);
				});
			// TODO 做一些其他的事情，手动执行 done 才会关闭对话框
			// ...
			done();
		},
		// payVdeo(){

		// 	    var mess = document.getElementById('ttsText').value;
		// 	    var msg = new SpeechSynthesisUtterance(mess);
		// 	    msg.volume = 100;
		// 	    msg.rate = 1;
		// 	    msg.pitch = 1.5;
		// 	    console.log(msg);
		// 	    window.speechSynthesis.speak(msg);
		// },
		// 开启循环倒计时
		setTimePay() {
			// 判断当前是否为付款码
			if (this.actionInd == 0) {
				this.setTimeOutPay = setInterval(() => {
					this.receivedCodeState();
				}, 5000);
			}
			// 获取首付款信息
			this.getMoneyList = setInterval(e => {
				this.collectionLst();
			}, 5000);
		},
		// 判断付款码是否可以使用
		receivedCodeState() {
			let obj = this;
			// 查询是否过期
			receivedCodeState({
				code: obj.val
			})
				.then(e => {
					// 无效
					if (e.msg == 'overdue') {
						obj.receivedPaymentCode();
					}
					// 已使用
					else if (e.msg == 'use') {
						uni.showModal({
							title: '提示',
							content: '已支付成功',
							showCancel: false
						});
						obj.receivedPaymentCode();
					}
				})
				.catch(e => {
					console.log(e);
				});
		},
		// 开启验证是否已经过期或使用付款成功
		// receivedCodeState(){

		// },
		// 跳转到记录页面
		openList() {
			clearInterval(this.setTimeOutPay);
			clearInterval(this.getMoneyList);
			// this.$refs.popup1.open();
			// uni.navigateTo({
			// 	url: '/pages/wallet/wallet'
			// });
			uni.navigateTo({
				url: './list'
			});
		},
		//点击首付款事件
		clickItem(item) {
			// 更新付款码
			if (item === 0) {
				this.receivedPaymentCode();
				this.setTimePay();
				uni.setNavigationBarColor({
					backgroundColor:'#4b8fdb',
					frontColor:'#ffffff',
					success:(e) => {
						console.log(e);
					},
					fail:function (e) {
						console.log(e);
					}
				})
			}
			// 更新收款码
			if (item === 1) {
				clearInterval(this.setTimeOutPay);
				uni.setNavigationBarColor({
					backgroundColor:'#5DBC7C',
					frontColor:'#ffffff',
					success:(e) => {
						console.log(e);
					},
					fail:function (e) {
						console.log(e);
					}
				})
				this.receivedCollectionCode();
			}
			// 扫码收付款
			if (item === 2) {
				clearInterval(this.setTimeOutPay);
				this.ToChangeInto();
				return;
			}
			// 赋值
			this.actionInd = item;
		},
		// 扫码
		ToChangeInto() {
			let obj = this;
			// #ifdef H5
			this.weichatObj.scanQRCode({
				needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
				success: function(res) {
					obj.code = res.resultStr;
					obj.$refs.popup1.open();
				}
			});
			// #endif
			// #ifndef H5
			uni.scanCode({
				onlyFromCamera: true,
				success: function(e) {
					let result = JSON.parse(e.result);
					uni.showModal({
						title: '扫描二维码',
						content: e.result
					});
				}
			});
			// #endif
		},
		// 扫码成功数据处理
		scanQR(e) {},
		// 获取付款码
		receivedPaymentCode() {
			receivedPaymentCode()
				.then(e => {
					this.val = e.data.code;
					console.log(e);
				})
				.catch(e => {
					console.log(e);
				});
		},
		// 获取收款码
		receivedCollectionCode() {
			receivedCollectionCode()
				.then(e => {
					this.val = e.msg;
					console.log(e);
				})
				.catch(e => {
					console.log(e);
				});
		},
		// 創建二维码
		creatQrcode() {
			console.log(this.$refs.qrcode._makeCode);
			this.$refs.qrcode._makeCode();
		},
		// 保存二维码到图库
		saveQrcode() {
			this.$refs.qrcode._saveCode();
		},
		// 生成二维码后返回base64
		qrR(res) {
			this.src = res;
		},
		//清空二维码（清空二维码会触发result回调 返回值为空）
		clearQrcode(e) {
			this.$refs.qrcode._clearCode();
			this.val = '';
		},
		// 保存二维码
		upload() {
			this.$refs.qrcode._saveCode();
		},
		openApp() {
			let weixinObj = require('jweixin-module');
		}
	}
};
</script>

<style lang="scss">
.content,
page {
	// border-top: 2rpx solid #f2f3f5;
	background-color: $base-color;
	height: 100%;
}

// 共有底部高度
$btHeight: 100rpx;
.btHeight {
	height: $btHeight;
}
.greenBg{
	background-color: $base-color;
	}
	.blueBg{
		background-color: #4b8fdb;
	}
.coupon_transfer {
	// background-color: #ffffff;
	padding: 20rpx 25rpx;
	padding-top: 50rpx;
	// padding-bottom: 130rpx;
	width: 100%;
	// margin-top: 25rpx;
	
	.user {
		margin-bottom: -125rpx;
		height: 200rpx;
		line-height: 1;
		.imgbox {
			margin: 0 auto;
			text-align: center;
			.img {
				width: 150rpx;
				height: 150rpx;
				border-radius: 999rpx;
			}
		}
		.niceName {
			text-align: center;
			font-size: $font-lg;
			margin-top: 15rpx;
			font-weight: bold;
			color: $font-color-dark;
		}
	}
}
.erwema {
	width: 686rpx;
	height: 817rpx;
	background-color: #ffffff;
	padding-top: 100rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	margin: 0rpx auto;
	.qrbox {
		width: 500rpx;
		text-align: center;
		font-weight: bold;
		.payMoney {
			font-size: 50rpx;
			// margin-top: 80rpx;
			color: $font-color-dark;
			font-weight: bold;
		}
		.setMoney {
			font-size: $font-base;
			color: $base-color;
			margin-top: 20rpx;
		}
	}
}
/deep/ .qrbox .img {
	margin-top: -500rpx !important;
}
/deep/ .tki-qrcode {
	// height: 500rpx;
	line-height: 0;
	margin-top: 10rpx;
}
.bottomTab {
	padding: 50rpx;
	padding-top: 20rpx;
	// position: fixed;
	// padding-bottom: 50rpx;
	// left: 0;
	// bottom: 0;
	width: 100%;
	.item1 {
		text-align: center;
		color: #ffffff;
		opacity: 0.7;
		flex-grow: 1;
		line-height: 1;
		.img {
			width: 80rpx;
			height: 80rpx;
		}
		.text {
			font-size: $font-lg;
		}
		&.action {
			opacity: 1;
		}
	}
}
</style>
