<template>
	<view class="containers">
		<topWindow></topWindow>
		<QrScan ref="qrcode" @ok="getResult" @err="geterror" v-if="open" />
	</view>
</template>

<script>
	import topWindow from "@/pages/component/topWindow.vue"
	import QrScan from "@/pages/component/QrScan.vue"
	import config from '@/common/config.js'
	import {
		getProductFind
	} from '@/api/scan'
	var browser = { // 判断浏览器内核
		versions: (function() {
			var u = navigator.userAgent;
			return {
				trident: u.indexOf('Trident') > -1, //IE内核
				presto: u.indexOf('Presto') > -1, //opera内核
				webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
				gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
				weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
			};
		})(),
	};
	export default {
		components: {
			QrScan,
			topWindow
		},
		props: {

		},
		data() {
			return {
				open: false
			}
		},
		computed: {

		},
		onShow() {
			this.open = true
		},
		mounted() {
			if (browser.versions.webKit || browser.versions.weixin || browser.versions.gecko) {
				this.open = true;
			} else {
				Toast('Browser not supported');
			}
		},
		onLoad() {

		},
		methods: {
			playAudio() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '/static/audio/scanSound.mp3';
				innerAudioContext.play();
				innerAudioContext.onPlay(() => {
					alert('音频开始播放')
					console.log('音频开始播放');
				});
			},
			getResult(sn) {
				console.log(sn);
				// this.playAudio()
				this.open = false;
				// const regex = /((?<=\?sn=)|(?<=HDKSN:))\w+/;「零宽度正向断言」ios低版本不支持
				const regex = /(?:\?sn=|HDKSN:)(\w+)/;
				const match = regex.exec(sn);
				const sncode = match ? match[1] : sn;
				// let sncode = sn.substring(sn.lastIndexOf(":") + 1);
				getProductFind(sncode).then(res => {
					console.log(res);
					if (res.code === 1400001001) {
						uni.navigateTo({
							url: '/pages/product/invalidCode?snCode=' + sncode,
							success() {
								this.open = true
							}
						});
					} else {
						uni.navigateTo({
							url: "/pages/product/index?sn=" + sncode,
							success() {
								this.open = true
							}
						})
					}
				})

			},
			geterror(e) {
				console.log(e);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.containers {
		width: 100vw;
	}
</style>