<template>
  <div style="width: 100%;height: 100%;">
    <div class="testTracking">
      <canvas style="display:none;" id="myCanvas" ref="canvas" :width="videoWidth" :height="videoHeight"></canvas>
      <!--图片展示-->
      <video ref="video" id="myVideo" :width="videoWidth" :height="videoHeight" autoplay style="display: block;margin:0 auto;border: 2px solid #333333;"></video>
      <!--确认-->
      <Button type="primary" @click="setImage" class="takePhoto">拍照</Button>
      <div id="res"></div>
    </div>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import {faceLogin} from "@/api/testModel";
  // import "tracking/build/data/face-min.js";
  // import "tracking/build/data/mouth-min.js";
  // import "tracking/build/data/tracking-min.js";
  // import "tracking/examples/assets/stats.min.js";
  export default {
    props:['src'],
    inject:['reload'],
    data () {
      return {
        videoWidth: 500,
        videoHeight: 400,
        videoArr:[],//所有的摄像头
        modelSel:'',//
        myInterval: null,
        imgSrc: '',
        isHasFace:false,//默认没有人脸
        tracker:null,
      }
    },
    created(){
    },
    mounted(){
      // this.openUserMedia();
      this.callCamera();
      this.changePhoto();
      // this.checkFace();
      if(this.src!='user'){
        // this.myInterval = setInterval(()=>{
        //   this.setImage();
        // },2000)
      }
    },
    methods: {
      // 调用摄像头
      callCamera () {
        // H5调用电脑摄像头API
        navigator.mediaDevices.getUserMedia({
          video: true
        }).then(success => {
          // 摄像头开启成功
          this.$refs['video'].srcObject = success;
          // 实时拍照效果
          this.$refs['video'].play()
        }).catch(error => {
          alert('摄像头开启失败，请检查摄像头是否可用！')
        })
      },
      // 拍照
      setImage () {
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext('2d');
        let video = document.getElementById("myVideo");
        context.drawImage(video,0,0,90,68);
        let image = new Image();
        image = canvas.toDataURL('image/png');
        document.getElementById('res').innerHTML = '<img src="'+image+'">';
        let img = image.split(',')[1];
        let imgData = {base64:img};
        faceLogin(imgData).then((res) => {
          if (res.code >= 200) {
            let data = res.data;
            this.$confirm("是否切换登陆人?", "提示", {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              type: "warning",
            }).then(async () => {
              await this.$store.dispatch("user/resetToken",data);
              await this.$store.dispatch("user/getInfo",data.access);
              // window.location.reload();
              this.$emit('func',false);
              debugger;
              console.log(getToken());
              debugger;
            })
              .catch((err) => {
                console.error(err);
              });
            this.$message.success("成功");
          }
        });
        },
      // 关闭摄像头
      closeCamera () {
        if (!this.$refs['video'].srcObject) return;
        let stream = this.$refs['video'].srcObject;
        let tracks = stream.getTracks();
        tracks.forEach(track => {
          track.stop()
        });
        this.$refs['video'].srcObject = null
      },
      //切换本地摄像头
      changePhoto(){
        /**得到所有的设备*/
        navigator.mediaDevices.enumerateDevices()
          .then((devices)=> {
            this.videoArr = [];
            devices.forEach((item)=> {
              if(item.kind == 'videoinput'){
                this.videoArr.push({
                  'label': item.kind,
                  'id': item.deviceId
                })
              }
            });
          })
          .catch(err=>{
          });
      },
      /**打开摄像头*/
      getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
          //最新的标准API
          navigator.mediaDevices.getUserMedia(constraints).then(success=>{
            // 摄像头开启成功
            this.$refs['video'].srcObject = success
            // 实时拍照效果
            this.$refs['video'].play()
          }).catch(error);

        } else if (navigator.webkitGetUserMedia) {
          //webkit核心浏览器
          navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
          //firfox浏览器
          navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
          //旧版API
          navigator.getUserMedia(constraints, success, error);
        }
      },
      /**
       * 检查取景框是否有人脸
       * */
      checkFace() {
        // var video = document.getElementById("video");
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext('2d');
        this.tracker = new tracking.ObjectTracker("face");
        this.tracker.setInitialScale(4);
        this.tracker.setStepSize(2);
        this.tracker.setEdgesDensity(0.1);
        this.trackerTask = tracking.track("#video",  this.tracker, { camera: true });
        let self = this;
        this.tracker.on("track", event=> {
          if (event.data.length <= 0) {
            self.setFace(false);
            return;
          }
          self.setFace(true);
          context.clearRect(0, 0, canvas.width, canvas.height);
          event.data.forEach(function (rect) {
            context.strokeStyle = '#a64ceb';
            context.strokeRect(rect.x, rect.y, rect.width, rect.height);
            context.font = '11px Helvetica';
            context.fillStyle = "#fff";
            context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
            context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
          });
        });
      },
      setFace(data){
        this.isHasFace = data;
      }
    },

    beforeDestroy () {
      clearInterval(this.myInterval);
      // 停止侦测
      // this.trackerTask.stop();
    }

  }
</script>

<style scoped>

  .testTracking {
    width: 100%;
    position: relative;
  }
  .takePhoto{
    margin: 30px auto;
    display: block;
  }
</style>

