<template>
	<view class="pages">
		<view class="scan">
			<!-- <view class="loop_line"></view> -->
			<u-icon class="close" name="close-circle" color="#fff" size="30" @click="closeScan"></u-icon>
		    <view class="video-container">
		      <video class="video" id="video_nav_id" :controls="false"></video>
		    </view>
		    <view class="camera-container" v-if="videoInputDevices.length>1">
		      <label>摄像头：</label>
		      <select v-model="currentVideoInputDevice">
		        <option
		          v-for="(videoInputDevice, index) in videoInputDevices"
		          :key="index"
		          :value="videoInputDevice"
		        >
		          {{ videoInputDevice.label }}
		        </option>
		      </select>
		    </view>
		  </view>
	</view>
</template>

<script>
	import {
	  BrowserMultiFormatReader,
	  ChecksumException,
	  FormatException,
	} from "@zxing/library";
	// import { LOG } from "@zxing/library/esm/core/datamatrix/encoder/constants";
	export default {
		data() {
			return {
				exchangeCode:'',
				codeReader: null,
				videoInputDevices: [],
				currentVideoInputDevice: {},
				decodeResult: undefined,
			}
		},
		onShow() {
		},
		beforeDestroy() {
			this.codeReader.reset(); //关闭摄像头
			alert('销毁')
		},
		mounted() {
			var video = document.getElementById('video_nav_id').getElementsByTagName('video')[0]
			video.setAttribute('id','video-1')
			video.setAttribute('class','video_calss')
			this.codeReader = new BrowserMultiFormatReader();
			this.openScan();
		},
		onLoad() {

		},
		watch: {
		   currentVideoInputDevice: function () {
		     this.decodeFromInputVideo();
		   },
		   decodeResult: function () {
		     this.successDecode();
		   },
		},
		methods: {
			async openScan() {
			      const _this = this;
				  // console.log('codeReader', this.codeReader);
				  // camera.setDisplayOrientation(90);
			      _this.codeReader
			        .getVideoInputDevices() //老版本listVideoInputDevices()
			        .then((videoInputDevices) => {
			          if (videoInputDevices && videoInputDevices.length) {
			            if (videoInputDevices.length > 1) {
			              videoInputDevices.reverse();
			            } //防止先唤出前摄像头
			            _this.videoInputDevices = videoInputDevices;
			            _this.currentVideoInputDevice = videoInputDevices[0];
			          }else{
						  alert('没有检测到摄像头')
					  }
			        })
			        .catch(() => {});
			    },
			
			    decodeFromInputVideo() {
			      const _this = this;
			      _this.codeReader.reset();
			      // 多次
				try {
					_this.codeReader.decodeFromVideoDevice(_this.currentVideoInputDevice.deviceId, 'video-1',(res,err) => {
						if(res) {
							_this.decodeResult = res.text;
						}
						if (err) {
												  // alert(err)
						  if (err instanceof ChecksumException) {
													alert("A code was found, but it's read value was not valid.")
						    console.log(
						      "A code was found, but it's read value was not valid."
						    );
						  }
						  if (err instanceof FormatException) {
													alert("A code was found, but it was in a invalid format.")
						    console.log("A code was found, but it was in a invalid format.");
						  }
						}
					})
				}catch(err){
					uni.showToast({title: `初始化失败${err}`,icon: 'none'});
				}
			},
			closeScan(){
				// this.$router.go(-1)
				// uni.navigateBack()
				uni.$u.route('/pages/index/index');
			},
			successDecode() {
			  const _this = this;
			  let result = JSON.parse(_this.decodeResult);
			  this.exchangeCode = result.qrcode;
			  
			  let pages = getCurrentPages();             //获取所有页面栈实例列表
			  let nowPage = pages[ pages.length - 1];    //当前页页面实例
			  let prevPage = pages[ pages.length - 2 ];  //上一页页面实例
			  prevPage.$vm.exchangeCode=  this.exchangeCode;         // 修改上一页data里面的数据
			  
			  this.closeScan();
			  // this.getCheckGoods();
			  // alert(_this.decodeResult);
			},
		}
	}
</script>

<style lang="scss" scoped>
#video_nav_id {
	height: 100%;
	width: 100%;
}
/deep/.uni-video-cover {
	display: none;
}

.scan {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ff9900;
  width: 100%;
  height: 100vh;
  background: #000;
  .video-container {
	width: 100%;
	height: 100%;
    display: flex;
    justify-content: center;
    /deep/ #video-1{
      width: 100%;
      height: 100%;
    }
    @media (min-width: 500px) {
      video {
        // width: 80vh;
        max-width: 96vw;
        height: 80vh;
      }
    }
  }
  .camera-container {
    margin-top: 5vh;
    width: 80%;
    height: 50px;
    line-height: 44px;
    border-radius: 10px;
    border: 3px solid #ff9900;
    display: flex;
    justify-content: center;
    select {
      width: calc(100% - 80px);
      color: #ff9900;
      background: transparent;
      border: none;
      outline: none;
    }
  }
  .close{
	  position: absolute;
	  right: 40rpx;
	  top: 40rpx;
	  z-index: 100;
  }
}
</style>