<template>

  <div>

    <div>
      <div v-show="showContainer">
        <video id="video" ref="refVideo" width="300" height="200" preload autoPlay loop muted />
        <canvas id="canvas" ref="refCanvas" width="300" height="200" />
      </div>
      <div>
        <img v-show="!showContainer" :src="imgUrl" width="300" height="200">
      </div>
    </div>

    <div class="scanTip">
      <div v-if="faceInfo.faceToken==null || faceInfo.faceToken===''">
        {{ scanTip }}
      </div>
      <div v-else style="color: #1AAC1A; text-align: left">
        <div>姓名：{{ faceInfo.realName }}</div>
        <div>身份证：{{ faceInfo.idCard }}</div>
        <div>识别成功，请继续下一步操作</div>
      </div>
    </div>

  </div>

</template>

<script>
// 引入tracking
import 'tracking/build/tracking-min.js'
import 'tracking/build/data/face-min.js'
import { faceCheck } from '@/api/user'

export default {
  name: 'FaceCam',
  data() {
    return {
      showContainer: true,
      tracker: null,
      tipFlag: false, // 提示用户已经检测到
      flag: false, // 判断是否已经拍照
      context: null, // canvas上下文
      removePhotoID: null, // 停止转换图片
      scanTip: '请将人脸置于摄像头中央...', // 提示文字
      imgUrl: '',
      canvas: null,
      video: null,
      streamIns: null, // 视频流

      // 人脸校验结果
      faceInfo: {
        id: ''
      }
    }
  },

  mounted() {
    this.playVideo()
  },

  methods: {

    // 访问用户媒体设备
    getUserMedia(constrains, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        // 最新标准API
        navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error)
      } else if (navigator.webkitGetUserMedia) {
        // webkit内核浏览器
        navigator.webkitGetUserMedia(constrains).then(success).catch(error)
      } else if (navigator.mozGetUserMedia) {
        // Firefox浏览器
        navigator.mozGetUserMedia(constrains).then(success).catch(error)
      } else if (navigator.getUserMedia) {
        // 旧版API
        navigator.getUserMedia(constrains).then(success).catch(error)
      } else {
        this.scanTip = '你的浏览器不支持访问用户媒体设备'
      }
    },
    success(stream) {
      this.streamIns = stream
      // webkit内核浏览器
      this.URL = window.URL || window.webkitURL
      if ('srcObject' in this.$refs.refVideo) {
        this.$refs.refVideo.srcObject = stream
      } else {
        this.$refs.refVideo.src = this.URL.createObjectURL(stream)
      }
      this.$refs.refVideo.onloadedmetadata = e => {
        this.$refs.refVideo.play()
      }
    },
    error(e) {
      this.scanTip = '摄像头开启失败，请检查您的摄像头是否正常：' + e.name + ',' + e.message
    },

    playVideo() {
      this.getUserMedia({
        video: {
          width: 300, height: 200, facingMode: 'user'
        } /* 前置优先 */
      }, this.success, this.error)

      this.video = document.getElementById('video')
      this.canvas = document.getElementById('canvas')
      this.context = this.canvas.getContext('2d')
      // eslint-disable-next-line no-undef
      this.tracker = new tracking.ObjectTracker('face')
      this.tracker.setInitialScale(4)
      this.tracker.setStepSize(2)
      this.tracker.setEdgesDensity(0.1)

      // eslint-disable-next-line no-undef
      tracking.track('#video', this.tracker, { camera: true })

      this.tracker.on('track', this.handleTracked)
    },

    handleTracked(event) {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
      if (event.data.length === 0) {
        this.scanTip = '未识别到人脸，请将人脸置于摄像头中央！'
      } else {
        if (!this.tipFlag) {
          this.scanTip = '识别成功，请保持这个姿势！'
        }
        // 1秒后拍照，仅拍一次
        if (!this.flag) {
          this.scanTip = '正在拍照对比...'
          this.flag = true
          this.removePhotoID = setTimeout(() => {
            this.tackPhoto()
            this.tipFlag = true
          },
          1000
          )
        }
        event.data.forEach(this.plot)
      }
    },

    plot(rect) {
      this.context.strokeStyle = '#eb652e'
      this.context.strokeRect(rect.x, rect.y, rect.width, rect.height)
      this.context.font = '11px Helvetica'
      this.context.fillStyle = '#fff'
      this.context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11)
      this.context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22)
    },

    // 拍照
    tackPhoto() {
      this.context.drawImage(this.$refs.refVideo, 0, 0, 300, 200)
      // 保存为base64格式
      this.imgUrl = this.saveAsPNG(this.$refs.refCanvas)
      this.scanTip = '比对中，请稍等..'
      // 去除png文件头
      const base64 = this.imgUrl.substring(22, this.imgUrl.length)

      faceCheck({ base64: base64 }).then(res => {
        console.log('识别结果', res)
        this.faceInfo = res.data
        if (this.faceInfo.faceToken != null && this.faceInfo.faceToken !== '') {
          this.$message.success('人脸比对成功！')
          this.$emit('success', res.data)
          this.showContainer = false
        } else {
          this.$emit('fail')

          this.flag = false
          this.tipFlag = false
          this.showContainer = true
        }
      }).catch(() => {
        this.$emit('fail')
        this.flag = false
        this.tipFlag = false
        this.showContainer = true
      })
    },

    // 保存为png,base64格式图片
    saveAsPNG(c) {
      return c.toDataURL('image/png', 0.3)
    },

    // 关闭并清理资源
    close() {
      this.video.srcObject.getTracks()[0].stop()
      this.flag = false
      this.tipFlag = false
      this.showContainer = false
      // eslint-disable-next-line no-undef
      this.tracker && this.tracker.removeListener('track', this.handleTracked) && tracking.track('#video', this.tracker, { camera: false })
      this.tracker = null
      this.context = null
      this.scanTip = ''
      clearTimeout(this.removePhotoID)
      if (this.streamIns) {
        this.streamIns.enabled = false
        this.streamIns.getTracks()[0].stop()
        this.streamIns.getVideoTracks()[0].stop()
      }
      this.streamIns = null
    }

  }
}
</script>

<style scoped>

.form-box {
  font-size: 14px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  line-height: 42px;
}

video, canvas, img {
  position: absolute;
  left: 10px;
  top: 10px;
}

/deep/
.scanTip {
  position: absolute;
  text-align: center;
  top: 220px;
  width: 300px;
  left: 10px;
  font-size: 14px;
  font-weight: 700;
  line-height: 26px;
}
</style>
