<template>
  <div>
    <van-popup v-model="show" position="right" :style="{ height: '100%',width: '100%' }">
      <div class="all">
      <video style="display: none" ref="video"></video>
      <canvas style="width: 90vw; margin-top: 20vh;height: 40vh" id="canvas"></canvas>
      <canvas style="display: none" id="2d"></canvas>
      </div>
    </van-popup>
  </div>
</template>

<script>
import jsQR from "../../utils/jsQR";

export default {
  name: 'analyzeQRCode',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      streams: null,
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.anaQR()
    })
  },
  methods: {
    //解析二维码
    anaQR() {
      // if (this.streams) {
      //   this.streams.getTracks().forEach((track) => track.stop());
      // }
      // video.srcObject = null;
      let that = this
      var video = document.createElement("video");
      var canvasElement = document.getElementById("canvas");
      var canvas = canvasElement.getContext("2d");
      console.log(navigator.mediaDevices);
      // 尝试打开手机上安装后置摄像头
      navigator.mediaDevices
          .getUserMedia({
            video: {facingMode: "environment"},
          })
          .then((stream) => {
            this.streams = stream;
            video.srcObject = stream;
            // 阻止IOS视频全屏
            video.setAttribute("playsinline", true);
            video.play();
            requestAnimationFrame(tick);
          });

      function tick() {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
          canvasElement.hidden = false;

          canvasElement.height = video.videoHeight;
          canvasElement.width = video.videoWidth;
          canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
          var imageData = canvas.getImageData(
              0,
              0,
              canvasElement.width,
              canvasElement.height
          );

          // QR码解析
          var code = jsQR(
              imageData.data, // 图像数据
              imageData.width, // 宽度
              imageData.height, // 高度
              {
                inversionAttempts: "dontInvert",
              }
          );

          if (code) {
            console.log(code.data);
            //输出解析后的二维码
            getQR(code.data)

          }
        }
        requestAnimationFrame(tick);
      }
      function getQR(val) {
        that.$emit("getQRCode", val)
      }
    },

  }
}


</script>

<style lang="less" scoped>
 .all {
   background: black;
   height: 100vh;
   display: flex;
   justify-content: space-around;
 }
</style>