<template>
	<view>
		<uni-popup ref="pdaScanPopup" type='center'>
			<view>扫码提示</view>
			请对准二维码或条形码扫描查看结果
		
			<button>取消</button>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: "klp-scaner",
		data() {
			return {
				pdaScaning: false,
				main: null,
				indent: null
			};
		},
		onHide: function() {
			if (uni.getSystemInfoSync().platform === 'android') {
				this.stopScan();
			}
		},
		destroyed: function() {
			// 页面退出时一定要卸载监听,否则下次进来时会重复，造成扫一次出2个以上的结果
			if (uni.getSystemInfoSync().platform === 'android') {
				this.stopScan();
			}
		},
		created() {
			if (uni.getSystemInfoSync().platform === 'android') {
				this.init();
			}
		},
		methods: {
			init() {
				this.main = plus.android.runtimeMainActivity(); //获取activity
				let context = plus.android.importClass('android.content.Context'); //上下文
				let receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: this.doReceive
				});
				this.receiver = receiver;
				let IntentFilter = plus.android.importClass('android.content.IntentFilter');
				let Intent = plus.android.importClass('android.content.Intent');
				let filter = new IntentFilter();

				filter.addAction("nlscan.action.SCANNER_RESULT"); //监听扫描,根据设备的广播动作进行更换
				// filter.addAction("android.intent.action.SCANRESULT"); //监听扫描,根据设备的广播动作进行更换

				this.doS(receiver, filter);
			},
			doS(receiver, filter) {
				this.main.registerReceiver(receiver, filter);
			},
			doReceive(context, intent) {
				//通过intent实例引入intent类，方便以后的‘.’操作
				console.log(indent);
				plus.android.importClass(intent);
				let barcodeData = intent.getStringExtra("SCAN_BARCODE1"); //获取扫描结果
				// let barcodeData = intent.getStringExtra("value"); //获取扫描结果
				let barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE", -1); //获取扫码类型
				if (this.pdaScaning) {
					uni.$emit('scan', {
						code: barcodeData
					})
				}
			},
			stopScan() {
				this.main.unregisterReceiver(this.receiver);
			},
			startScan(mode = 'camera') {
				if (mode == 'camera') {
					uni.scanCode({
						success(res) {
							resolve(res.result);
							this.$emit('scan', res.result)
						},
						fail() {
							reject()
						}
					})
				} else if (mode == 'pda') {
					this.pdaScaning = true;
					this.$refs.pdaScanPopup.open()
					// 等待对应的广播消息，收到广播消息后返回扫码结果，
				}
			}
		},
		closePdaScanPopup() {
			this.pdaScaning = false;
			this.$refs.pdaScanPopup.close()
		}
	}
</script>

<style>

</style>