<template>
	<view class="scan-container">
		<!-- 如果scanMode是normal去掉下面的@scancode方法 -->
		<view class="scan-cameraCon">
			<camera
				class="scan-camera"
				device-position="back"
				flash="off"
				@error="error"
				:mode="scanMode"
				@scancode="cameraScan"
				:style="{ width: scanCameraWid, height: scanCameraHei }"
			>
				<view v-if="scanMode == 'scanCode'">
					<!-- 温馨提示：如果你觉得自定义弄四个角的边框太麻烦，可以叫ui切四个角的图片，直接插进来即可，本人因为没有ui才这样做 -->
					<!-- 左上角 -->
					<cover-view class="scan-border scan-left-top scan-verLine"></cover-view>
					<cover-view class="scan-border scan-left-top scan-horLine"></cover-view>
					<!-- 左下角 -->
					<cover-view class="scan-border scan-left-bottom scan-verLine"></cover-view>
					<cover-view class="scan-border scan-left-bottom scan-horLine"></cover-view>
					<!-- 右上角 -->
					<cover-view class="scan-border scan-right-top scan-verLine"></cover-view>
					<cover-view class="scan-border scan-right-top scan-horLine"></cover-view>
					<!-- 右下角 -->
					<cover-view class="scan-border scan-right-bottom scan-verLine"></cover-view>
					<cover-view class="scan-border scan-right-bottom scan-horLine"></cover-view>
					<!-- 上下移动的动画线 -->
					<cover-view class="scan-animation" :animation="scanAnimation"></cover-view>
				</view>
			</camera>
		</view>

		<!-- 下面两种模式暂时写死，具体样式要根据你们的代码来写，也可以使用插槽模式 -->
		<view class="" v-if="scanMode == 'normal'">
			<button type="primary" @click="takePhoto">拍照</button>
			<view>预览</view>
			<image mode="widthFix" :src="src"></image>
		</view>
		<view class="" v-if="scanMode == 'scanCode'">
			<!-- <view class="">扫码结果如下：</view>
			<view v-for="(item, index) in kingList" key="index">{{ item }}</view> -->
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
// 移动动画
let animation = wx.createAnimation({});
// 提示音（如果有可以导入，这个我用手机震动来提示扫码完成）
let innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src = '/static/music/beep.mp3';
export default {
	data() {
		return {
			// 照相模式下图片临时路径
			src: '',
			// 扫码模式下的多次扫码列表
			kingList: [],
			// 动画
			scanAnimation: null
		};
	},
	props: {
		// 照相模式还是扫码模式（normal：代表照相模式，scanCode：代表扫码模式，注意微信暂不支持扫描小程序码，不要问为什么，微信功能是这样）
		scanMode: {
			type: String,
			default: 'scanCode'
		},
		// 扫码成功用是否用震动来提示（1：表示震动模式，2：表示mp3模式）
		scanTip: {
			type: Number,
			default: 1
		},
		// 相机的宽度
		scanCameraWid: {
			type: String,
			default: '250px'
		},
		// 相机的高度
		scanCameraHei: {
			type: String,
			default: '250px'
		}
	},
	created() {
		if (this.scanMode == 'scanCode') {
			// 初始化扫码动画
			this.initAnimation();
		}
	},
	methods: {
		initAnimation() {
			var that = this;
			// 控制向上还是向下移动
			let m = true;
			setInterval(
				function() {
					if (m) {
						animation.translateY(240).step({ duration: 3000 });
						m = !m;
					} else {
						animation.translateY(10).step({ duration: 3000 });
						m = !m;
					}
					that.scanAnimation = animation.export();
				}.bind(this),
				3000
			);
		},
		cameraScan(e) {
			if (e) {
				let result = e.detail.result;
				// 如果已经扫描过了，就不添加到列表里面了
				if (this.kingList.indexOf(result) == -1) {
					switch (this.scanTip) {
						case 1:
							// 方式1，扫码成功后让手机震动
							uni.vibrateShort({
								success: function() {
									console.log('success');
								}
							});
							break;
						case 2:
							// 方式2，扫码成功后让手机播放声音
							innerAudioContext.play();
							break;
						default:
							// 方式1，扫码成功后让手机震动
							uni.vibrateShort({
								success: function() {
									console.log('success');
								}
							});
							break;
					}
					
					this.kingList.push(result);
					let list = JSON.parse(this.kingList[0])
					let sysTime = Date.parse(new Date()) / 1000;
					let time = list.time;
					console.log('list.time',list.time);
					let date = (new Date(Date.parse(time.replace(/-/g,"/")))).getTime() / 1000;
					let count= list.id;
					let last =list.type;
					console.log('sysTime',sysTime)
					console.log('date',date)
					console.log('sysTime-date',sysTime-date)
					console.log('sysTime-date <= 300000',sysTime-date <= 300000);
					if(sysTime-date <= 300000){
						this.$emit('handle', count, last);
					}
				} else {
					this.$refs.uToast.show({
						title: '扫描过了,二维码已失效!',
						type: 'default',
					})
				}
			}
		},
		// 如果不是扫码模式就用这个
		takePhoto() {
			const ctx = uni.createCameraContext();
			ctx.takePhoto({
				quality: 'high',
				success: res => {
					this.src = res.tempImagePath;
				}
			});
		},
		error(e) {
			if (e) {
				let that = this;
				// 如果用户不允许使用摄像头，需要提示引导用户授权
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.camera']) {
							//获取摄像头权限
							wx.authorize({
								scope: 'scope.camera',
								success() {
									console.log('授权成功');
								},
								fail() {
									wx.showModal({
										title: '提示',
										content: '尚未进行摄像头权限授权，摄像头功能将无法使用',
										showCancel: false,
										success(res) {
											that.openAuthor();
										}
									});
								}
							});
						}
					},
					fail(res) {}
				});
			}
		},
		// 打开设置进行授权
		openAuthor(){
			let that = this;
			wx.openSetting({
				//这里的方法是调到一个添加权限的页面，可以自己尝试
				success: res => {
					console.log(1111);
					if (!res.authSetting['scope.camera']) {
						wx.showModal({
							title: '提示',
							content: '尚未进行摄像头权限授权，摄像头功能将无法使用',
							showCancel: false,
							success(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									that.openAuthor();
									
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}else {
						wx.showModal({
							title: '提示',
							content: '授权成功！',
							showCancel: false,
							success: resData => {
								// 授权成功后，需要重新进入页面能调起相机组件
								uni.reLaunch({
									url:'/pages/index/index'
								})
							}
						});
					}
				},
				fail: function() {
					console.log('授权摄像头权限失败');
				}
			});
		}
		
	}
};
</script>

<style lang="scss">
.scan-container {
	.scan-cameraCon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100vw;
		height: 50vh;
		.scan-camera {
			width: 250px;
			height: 250px;
			position: relative;
			// 四个角边框
			.scan-border {
				background-color: #007aff;
				position: absolute;
			}
			.scan-verLine {
				width: 5px;
				height: 20px;
			}
			.scan-horLine {
				width: 20px;
				height: 5px;
			}
			// 左上角
			.scan-left-top {
				left: 0;
				top: 0;
			}
			// 左下角
			.scan-left-bottom {
				left: 0;
				bottom: 0;
			}
			// 右上角
			.scan-right-top {
				right: 0;
				top: 0;
			}
			// 右下角
			.scan-right-bottom {
				right: 0;
				bottom: 0;
			}
			// 相机中上下移动的线条
			.scan-animation {
				position: absolute;
				top: 5px;
				left: 5px;
				width: 240px;
				height: 4px;
				background-color: #007aff;
				border-radius: 50%;
			}
		}
	}
}
</style>
