<template>
	<view class="container">
		<view class="text-box">
			<text v-if="scanResult == ''" class="scanResult">待扫码</text>
			<text v-else class="scanResult">扫码结果：{{ scanResult }}</text>
		</view>
		<view class="btn-box">
			<button class="btn-scan" type="primary" @click="handleScan()">扫一扫</button>
		</view>
	</view>
</template>

<script>
	import {
		AssVerificationRequest
	} from "@/grpc/app_api_pb.js"
	import Base64 from 'base-64'

	export default {
		data() {
			return {
				userId: 0,
				uoId: 0,
				scanResult: ''
			}
		},
		onLoad() {},
		methods: {
			handleScan() {
				let that = this
				this.scanResult = ''

				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						// console.log('条码类型：' + res.scanType)
						// console.log('条码内容：' + res.result)
						let result = Base64.decode(res.result)
						console.log(result)
						result = JSON.parse(result)
						// console.log('条码内容 Base64.decode：' + JSON.stringify(result))
						that.userId = result.userId
						that.uoId = result.uoId
						// console.log('userId：' + that.userId)
						// console.log('uoId：' + that.uoId)
						that.verification()
					}
				})
			},
			// 核销
			verification() {
				// 创建请求参数并赋值
				var request = new AssVerificationRequest()
				request.setUserid(this.userId)
				request.setUoid(this.uoId)
				// 调用客户端相应的grpc方法，发送grpc请求，并接受后台发送回来的返回值
				this.$client.assVerification(request, {}, (err, response) => {
					if (err) {
						console.log(`[assVerification] err: code = ${err.code}` +
							`, message = "${err.message}"`)
						uni.showToast({
							title: `${err.message} (err:${err.code})`,
							icon: 'none',
							duration: 2000
						})
						this.scanResult = `${err.message} (err:${err.code})`
					} else {
						// console.log(response)
						uni.showToast({
							title: `核销成功`,
							icon: 'success',
							duration: 2000
						})
						this.scanResult = '核销成功'
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 15px;
		box-sizing: border-box;

		.text-box {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 200rpx;

			.scanResult {}
		}

		.btn-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20px;

			.btn-scan {
				width: 90%;
			}
		}
	}
</style>
