<template>
	<view class="warpCss">
		<!-- 自定义扫码只在H5做展示，uni.scancode不支持H5，H5联盟暂未支持，需自行实现，H5扫码需https支持，若无则手动输入 -->
		<u-navbar title="扫码" placeholder :autoBack="true" v-if="isH5">
		</u-navbar>
		<!-- <Navbar canBack title="扫码" /> -->
		<!-- HTML -->
		<view class="scanCss" v-if="isH5">
			<mumu-get-qrcode ref="qrCode" :mode="mode" @refresh="handleRefresh" @success='qrcodeSucess'
				@error="qrcodeError" :key="componentKey"></mumu-get-qrcode>
		</view>
		<!-- Nvue模式可用以下代码创建自定义扫码窗口 -->
		<!-- <view class="scanBodyCss" v-if="isApp"> -->
		<!-- <barcode id='1' class="barcode" autostart="true" ref="barcode" background="rgb(0,0,0)" frameColor="#f6f6f6"
				scanbarColor="#f6f6f6" :filters="fil" @marked="success" @error="fail"></barcode> -->
		<!-- 扫码提示 -->
		<!-- <view class="tipsCss">
				<text class="text-white text-sm">请将二维码放入框内，即可自动扫描</text>
			</view> -->
		<!-- 闪光灯 -->
		<!-- <view class="FlashCss" @click="toFlash">
				<u-icon name="camera" size="25" color="#fff"></u-icon>
				<text class="text-white text-lg">{{isFlash?'关闭闪光灯':'打开闪光灯'}}</text>
			</view> -->
		<!-- 条码查询 -->
		<!-- <view class="codeCss" @click="goToCodeQuery">
				<u-icon name="/static/images/home/tmcx.png" class="margin-top-xs" color="#fff" size="20"></u-icon>
				<text class="text-white text-lg margin-left-xs">条码查询</text>
			</view> -->
		<!-- 相册 -->
		<!-- <view class="albumCss" @click="scanFromPic">
				<view class="roundCss">
					<u-icon name="photo" size="25" color="#fff"></u-icon>
				</view>
				<text class="text-white text-sm margin-top-xs">相册</text>
			</view> -->
		<!-- </view> -->
	</view>
</template>

<script>
	import mumuGetQrcode from '@/uni_modules/mumu-getQrcode/components/mumu-getQrcode/mumu-getQrcode.vue'
	let barcode = null;
	export default {
		name: "ScanCode",
		components: {
			mumuGetQrcode
		},
		data() {
			return {
				environment: uni.$u.platform,
				isH5: uni.$u.platform === 'h5',
				isMP: uni.$u.platform === 'mp-weixin',
				isApp: uni.$u.platform === 'plus',
				scanShow: false,
				isFlash: false,
				fil: [0, 2, 1],
				mode: 1,
				name: '请将二维码放入框内，即可自动扫描', //要在扫码界面自定义的内容
				flash: false, //是否打开摄像头
				queryParams: {
					qptm: "",
					lx: "ckxx",
					ddId: ""
				},
				componentKey: 0, //组件key
				isRefresh: false,
				pathName: "", //从那个页面跳转过来
			};
		},
		onLoad(data) {
			/* mode模式 跳转模式/传参模式
				模式1为跳转到气瓶页
				模式2为获取气瓶条码传递给其他页面
			*/
			if (data.mode) {
				this.mode = parseInt(data.mode);
				console.log("扫码模式", this.mode);
			}
			if (data.lx) {
				// 默认类型为ccxx
				this.queryParams.lx = data.lx;
				console.log("扫码操作类型", this.queryParams.lx);
			}

			if (data.ddid) {
				this.queryParams.ddId = data.ddid;
			}

			this.getCurrentPath();

			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(true); //全屏
			var currentWebview = page.$getAppWebview();
			this.createBarcode(currentWebview); //创建二维码窗口
			this.createView(currentWebview); //创建操作按钮及tips界面
			// #endif
		},
		onShow() {
			//更新key重新刷新扫码组件
			if (this.isRefresh) {
				this.componentKey += 1;
			}
		},
		mounted() {
			console.log("当前环境", this.environment);
			console.log("当前环境平台", uni.$u.os());
		},
		methods: {
			getCurrentPath() {
				var pages = getCurrentPages();
				var page = pages[pages.length - 2];
				this.pathName = page.route.substring(page.route.lastIndexOf('/') + 1);
				console.log("from地址", this.pathName);
			},
			open() {
				this.scanShow = true;
				let that = this;
				if (this.environment !== 'h5') {
					uni.scanCode({
						success: function(res) {
							console.log("扫描结果", res);
							console.log('条码类型：' + res.scanType);
							console.log('条码内容：' + res.result);
							that.$emit('scanCode', res.result)
							that.close();
						},
						fail: function(e) {
							console.log("扫描失败", e);
							that.close();
						},
					})
				}
			},
			close() {
				console.log("关闭扫码");
				this.scanShow = false;
				this.$emit('close');
			},
			qrcodeSucess(s) {
				console.log('ddddddddddddd',s);
				// this.$emit('scanCode', s)
				this.codeMethod(s);
			},
			qrcodeError(e) {
				console.log(e);
			},
			// 刷新组件
			handleRefresh(refresh) {
				console.log("刷新组件", refresh);
				this.isRefresh = refresh;
			},
			goToCodeQuery() {
				uni.navigateTo({
					url: '/pages/scan/barcodeQuery?mode=' + this.mode
				})
			},
			// 从相册中选择
			scanFromPic() {
				let that = this
				plus.gallery.pick(function(path) {
					plus.barcode.scan(path, that.onmarked, that.onerror);
				}, function(err) {
					alert('选择相片失败: ' + JSON.stringify(err.message));
				});
			},
			/* 获取到正确code后统一调用 
				模式1为跳转到气瓶页
				模式2为获取气瓶条码传递给其他页面
			*/
			async codeMethod(code) {
				console.log("CODE", code);
				let that = this;
				this.$modal.showLoading('查询中...');
				let query = {
					qptm: code,
          // lx:'ckxx',
				}
				// const result = await this.$api.gasApi.getDetailByQuery(query);
				this.queryParams.qptm = code;
				let result = null;
				if(this.mode === 1){
          result = await this.$api.gasApi.getDetailByQuery(query);
        }else{
          result = await this.$api.gasApi.getliquefiedGasBottle(this.queryParams);
        }
				// const result = await this.$api.gasApi.getliquefiedGasBottle(this.queryParams);
				// console.log("查询参数", query);
				that.$modal.closeLoading();
				let {
					state,
					message,
					value
				} = result;
        console.log('打印扫描气瓶二维码value',value);
				if (!state) {
					uni.$u.toast(message);
					setTimeout(() => {
						that.componentKey += 1;
						that.$forceUpdate()
					}, 1000)
					return;
				}
				if (this.mode === 1) {
					uni.redirectTo({
						url: '/pages/home/appList/gasInformation/gasInformation?qptm=' + value.fQptm
					})
				} else if (this.mode === 2) {
					let fQptm = value.fQptm;
					// let fQptmObj = JSON.stringify(value);
					let fQptmObj = value;
					//在需要扫码获取code的地方使用uni.$on监听scanCode即可获取code
					console.log("模式2");
					let fQpgg = value.fQpgg;
					console.log("气瓶规格",fQpgg);
					let name = that.pathName;
					uni.$emit("scanCode",fQptm,name,fQptmObj,fQpgg);
					this.closeScan();
				}
			},
			// 传递code模式关闭扫码
			closeScan() {
				// 返回时退出全屏
				this.$goBack();
				// barcode.close();
				// plus.navigator.setFullscreen(false);
			},
			// 识别成功
			onmarked(type, result) {
				console.log('扫描结果', result);
				this.codeMethod(result);
				//0.5s后再次扫码
				setTimeout(() => {
					barcode.start()
				}, 1000)
			},
			// 识别失败
			onerror(err) {
				console.log('扫码失败', err);
				console.log('扫码失败', JSON.stringify(err))
				uni.$u.toast('扫码失败,请更换二维码重试')
				this.$refs.barcode && this.$refs.barcode.close();
				this.$refs.barcode = null;
			},
			success(e) {
				console.log("success1:" + JSON.stringify(e));
				console.log("扫码结果", e.detail.message);
				let code = e.detail.message
				this.codeMethod(code)
				this.toStart();
			},
			fail(e) {
				console.log("fail1:" + JSON.stringify(e));
			},
			toStart: function() {
				this.$refs.barcode.start({
					conserve: false,
					// filename: '_doc/barcode/',
					sound: "default"
				});
			},
			tocancel: function() {
				this.$refs.barcode.cancel();
			},
			toFlash: function() {
				this.isFlash = !this.isFlash;
				this.$refs.barcode.setFlash(this.isFlash);
			},
			toscan: function() {
				console.log("scan:");
				const barcodeModule = uni.requireNativePlugin('barcodeScan');
				barcodeModule.scan("/static/barcode1.png", (e) => {
					console.log("scan_error:" + JSON.stringify(e));
				});
			},
			// 创建二维码窗口
			createBarcode(currentWebview) {
				//自定义窗口大小
				//条码类型常量数组，默认情况支持QR、EAN13、EAN8类型。 通过此参数可设置扫码识别支持的条码类型（注意：设置支持的条码类型越多，扫描识别速度可能将会降低）
				barcode = plus.barcode.create('barcode', [plus.barcode.QR, plus.barcode.EAN13, plus.barcode.EAN8], {
					top: '0%',
					left: '0',
					width: '100%',
					height: '100%',
					scanbarColor: '#f6f6f6',
					position: 'static',
					frameColor: '#f6f6f6'
				});
				barcode.onmarked = this.onmarked;
				barcode.onerror = this.onerror;
				barcode.setFlash(this.flash);
				currentWebview.append(barcode);
				barcode.start();
			},
			// 创建操作按钮及tips
			createView(currentWebview) {
				// 创建返回原生按钮
				var backVew = new plus.nativeObj.View('backVew', {
						top: '20px',
						left: '0px',
						height: '40px',
						width: '100%'
					},
					[{
						tag: 'img',
						id: 'backBar',
						src: 'static/images/scan/backBar.png',
						position: {
							top: '2px',
							left: '3px',
							width: '35px',
							height: '35px'
						}
					}]);
				// 创建打开手电筒的按钮
				var scanBarVew = new plus.nativeObj.View('scanBarVew', {
						top: '60%',
						left: '40%',
						height: '10%',
						width: '20%'

					},
					[{
							tag: 'img',
							id: 'scanBar',
							src: 'static/images/scan/scanBar.png',
							position: {
								width: '28%',
								left: '36%',
								height: '30%'
							}
						},
						{
							tag: 'font',
							id: 'font',
							text: '打开闪光灯',
							textStyles: {
								size: '10px',
								color: '#ffffff'
							},
							position: {
								width: '80%',
								left: '10%'
							}
						}
					]);
				/* tips提示 */
				var scanTipVew = new plus.nativeObj.View('scanTipVew', {
						top: '63%',
						left: '0%',
						height: '10%',
						width: '100%'

					},
					[{
						tag: 'font',
						id: 'tips',
						text: '请将二维码放入框内，即可自动扫描',
						textStyles: {
							size: '10px',
							color: '#ffffff'
						},
						position: {
							width: '80%',
							left: '10%'
						}
					}]);
				/* 条码查询 */
				var codeVew = new plus.nativeObj.View('codeVew', {
						top: '75%',
						left: '0%',
						height: '10%',
						width: '100%'
					},
					[{
							tag: 'rect',
							id: 'tmcx',
							rectStyles: {
								color: '#4C4C4C',
								radius: "30px"
							},
							position: {
								width: '30%',
								height: '50%',
								left: '35%'
							}
						},
						{
							tag: 'img',
							id: 'scanBar',
							src: 'static/images/scan/tmcx.png',
							position: {
								width: '6%',
								left: '38%',
								top: '15%',
								height: '28%'
							}
						},
						{
							tag: 'font',
							id: 'tmcxText',
							text: '条码查询',
							textStyles: {
								size: '14px',
								color: '#ffffff'
							},
							position: {
								width: '25%',
								height: '50%',
								left: '41%'
							}
						},
					]);
				/* 相册 */
				var albumVew = new plus.nativeObj.View('albumVew', {
						top: '88%',
						right: '0%',
						height: '30%',
						width: '100%'
					},
					[{
							tag: 'rect',
							id: 'xc',
							rectStyles: {
								color: '#4C4C4C',
								radius: "100%"
							},
							position: {
								width: '50px',
								height: '50px',
								right: '5%'
							}
						},
						{
							tag: 'img',
							id: 'sc',
							src: 'static/images/scan/xc.png',
							position: {
								width: '25px',
								height: '25px',
								top: '6%',
								right: '8.5%'
							}
						},
						{
							tag: 'font',
							id: 'scText',
							text: '相册',
							textStyles: {
								size: '12px',
								color: '#ffffff'
							},
							position: {
								width: '25px',
								height: '25px',
								top: '22%',
								right: '8.5%'
							}
						},
					]);
				// 创建展示类内容组件
				var content = new plus.nativeObj.View('content', {
						top: '20px',
						left: '0px',
						height: '100%',
						width: '100%',
						background: '#fff'
					},
					[{
							tag: 'font',
							id: 'scanTitle',
							text: '扫码',
							textStyles: {
								size: '18px',
								color: '#ffffff'
							},
							position: {
								top: '0px',
								left: '0px',
								width: '100%',
								height: '40px'
							}
						},
						{
							tag: 'font',
							id: 'scanTips',
							text: this.name,
							textStyles: {
								size: '14px',
								color: '#ffffff',
								whiteSpace: 'normal'
							},
							position: {
								top: '90px',
								left: '10%',
								width: '80%',
								height: 'wrap_content'

							}
						}

					]);
				backVew.interceptTouchEvent(true);
				scanBarVew.interceptTouchEvent(true);
				codeVew.interceptTouchEvent(true);
				albumVew.interceptTouchEvent(true);
				currentWebview.append(content);
				// currentWebview.append(scanTipVew);
				currentWebview.append(codeVew);
				currentWebview.append(albumVew);
				currentWebview.append(scanBarVew);
				currentWebview.append(backVew);
				backVew.addEventListener("click", function(e) { //返回按钮
					uni.navigateBack({
						delta: 1
					});
					barcode.close();
					plus.navigator.setFullscreen(false);
				}, false);
				var temp = this;
				codeVew.addEventListener("click", function(e) { //条码查询
					uni.navigateTo({
						url: '/pages/scan/barcodeQuery?mode=' + temp.mode
					})
				}, false)

				albumVew.addEventListener("click", function(e) { //相册
					temp.scanFromPic();
				}, false)


				scanBarVew.addEventListener("click", function(e) { //点亮手电筒
					temp.flash = !temp.flash;
					if (temp.flash) {
						scanBarVew.draw([{
								tag: 'img',
								id: 'scanBar',
								src: 'static/images/scan/yellow-scanBar.png',
								position: {
									width: '28%',
									left: '36%',
									height: '30%'
								}
							},
							{
								tag: 'font',
								id: 'font',
								text: '关闭闪光灯',
								textStyles: {
									size: '10px',
									color: '#ffffff'
								},
								position: {
									width: '80%',
									left: '10%'
								}
							}
						]);
					} else {
						scanBarVew.draw([{
								tag: 'img',
								id: 'scanBar',
								src: 'static/images/scan/scanBar.png',
								position: {
									width: '28%',
									left: '36%',
									height: '30%'
								}
							},
							{
								tag: 'font',
								id: 'font',
								text: '打开闪光灯',
								textStyles: {
									size: '10px',
									color: '#ffffff'
								},
								position: {
									width: '80%',
									left: '10%'
								}
							}
						])
					}
					if (barcode) {
						barcode.setFlash(temp.flash);
					}
				}, false)

			}
		},
		onBackPress() {
			// #ifdef APP-PLUS
			// 返回时退出全屏
			barcode.close();
			console.log("onBackPress");
			plus.navigator.setFullscreen(false);
			// #endif
		},
		onUnload() {
			console.log("onUnload");
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(false);
			// #endif
		}
	}
</script>

<style lang="scss" scoped>
	.warpCss {
		position: relative;
		width: 750rpx;
		flex: 1;
	}

	.scanCss {
		position: relative;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100vw;
		height: 100vh;
		background: #000;
		overflow: hidden;
		display: flex;
		flex-direction: row;
	}

	.scanBodyCss {
		width: 750rpx;
		flex: 1;
	}

	.tipsCss {
		position: absolute;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 750rpx;
		bottom: 500rpx;
		color: #fff;
	}

	.codeCss {
		position: absolute;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		width: 250rpx;
		left: 250rpx;
		border-radius: 50rpx;
		height: 100rpx;
		bottom: 200rpx;
		background: #4C4C4C;
		border: 1px solid #fff;
	}

	.FlashCss {
		position: absolute;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 200rpx;
		height: 100rpx;
		left: 280rpx;
		bottom: 350rpx;
		color: #fff;
	}

	.albumCss {
		position: absolute;
		bottom: 50rpx;
		right: 50rpx;
		align-items: center;
	}

	.roundCss {
		width: 100rpx;
		height: 100rpx;
		justify-content: center;
		align-items: center;
		border-radius: 50rpx;
		background: #4C4C4C;
	}

	.barcode {
		width: 750rpx;
		flex: 1;
		background-color: #808080;
	}

	.btn {
		top: 20rpx;
		width: 730rpx;
		margin-left: 10rpx;
		margin-top: 10rpx;
		background-color: #458B00;
		border-radius: 10rpx;
	}
</style>