<style lang="less">
  .db-img{
    height: 200px;
    width: 200px;
  }
</style>
<template>
  <div>
    <Row>
      <Col span="16" offset="8">
        <i-circle :percent="percent" :stroke-color="color" v-if="faceSuccess">
          <Icon v-if="percent == 100" type="ios-checkmark" size="60" style="color:#5cb85c"></Icon>
          <span v-else style="font-size:24px">{{ percent }}%</span>
        </i-circle>
      </Col>
      <Col span="24">
        <Alert type="error" v-if="errMsg.show">{{errMsg.msg}}</Alert>
      </Col>
      <Col span="8">
        <video id="video" width="200px" height="200px" autoplay="autoplay" v-if="!stock"></video>
          <img :src="stockData" width="200px" height="200px" v-if="stock">
      </Col>
      <Col span="8">
        <canvas id="canvas" width="200px" height="200px" v-if="!stock"></canvas>
          <img :src="catImg" width="200px" height="200px" v-if="stock">
      </Col >
      <Col span="8">
        <img :src="rest_idcard_header" id="db"/>
      </Col >
      <Col span="24">
        <Button type="primary" @click="TakePhoto">拍照</Button>
      </Col>
      <Col span="20">
        <Input v-model="user_idcard" placeholder="输入身份证号" style="width: 300px" />
      </Col >
      <Col span="4">
        <Button type="primary" :loading="loading" @click="savePhoto">
          <span v-if="!loading">比对身份信息</span>
          <span v-else>正在保存...</span>
        </Button>
      </Col>
      </Row>
  </div>
</template>

<script>
import { imgComparison, createUpLoadFiles, getSign } from '@/api/common'
import { getUserPhoto } from '@/api/mainv3'
import Camera from '_c/stock-camera'
export default {
  name: 'face-camera',
  props: {
    isPlay: false,
    filePath: {
      type: String,
      default: () => {
        return 'zi-tu'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'zi-tu'
      }
    }
  },
  data () {
    return {
      errMsg: {
        show: false,
        msg: ''
      },
      user_idcard: '',
      mediaStreamTrack: Object,
      loading: false,
      is_photo: false,
      result_photo: false,
      rest_idcard_header: '',
      faceSuccess: false,
      percent: 0,
      stockData: String,
      baseImg64: String,
      imgHeader: 'data:image/jpeg;base64,',
      stock: true // true是调用捷宇科技的设备，false调用本地的摄像头
    }
  },
  created () {
    let _this = this
    Camera.start(function (event) {
      // _this.acceptMsg(event)
    }, function (event) {
      _this.ShowInfo(event.data)
    })
    Camera.runmessage = this.acceptMsg
    this.result_photo = false
  },
  watch: {
    isPlay (bol) {
      if (bol === true) {
        if (this.stock) {
          console.log('iiiii')
          Camera.sendMsg('bStartPlay2')
          Camera.runmessage = this.acceptMsg
        } else {
          this.newOpenCamera()
        }
      } else {
        if (this.stock) {
          Camera.over()
        } else {
          this.mediaStreamTrack.stop()
        }
        console.log('准备关闭摄像头')
      }
    }
  },
  computed: {
    color () {
      let color = '#2db7f5'
      if (this.percent === 100) {
        color = '#5cb85c'
      }
      return color
    },
    catImg () {
      return this.imgHeader + this.baseImg64
    }
  },
  methods: {
    acceptMsg (event) {
      this.stockData = 'data:image/jpeg;base64,' + event.data
      // console.log('222222')
    },
    // 拍照
    TakePhoto () {
      if (this.stock) {
        Camera.cat()
        this.baseImg64 = Camera.endData.data
        this.upimg(Camera.endData.data)
      } else {
        let video = document.getElementById('video')
        let canvas = document.getElementById('canvas')
        let ctx = canvas.getContext('2d')
        ctx.drawImage(video, 0, 0, 200, 200)
      }
      this.is_photo = true
      this.result_photo = false
    },
    newOpenCamera () {
      let that = this
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
      if (navigator.getUserMedia) {
        navigator.getUserMedia({ audio: true, video: { width: 200, height: 200 } },
          function (stream) {
            let video = document.getElementById('video')
            that.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1]
            // video.src = (window.URL || window.webkitURL).createObjectURL(stream)
            video.srcObject = stream
            video.play()
          },
          function (err) {
            console.log('The following error occurred: ' + err.name)
          }
        )
      } else {
        console.log('getUserMedia not supported')
      }
    },
    modalChange (e) {
      this.$emit('modal-change', e)
      console.log(e, '模态框发生变化')
    },
    ShowInfo (op) {
      this.errMsg = { show: true, msg: op }
      let that = this
      setTimeout(function () {
        that.errMsg = { show: false, msg: '' }
      }, 4000)
    },
    savePhoto () {
      if (this.is_photo === true) {
        this.loading = true
        if (this.result_photo === false) {
          this.upimg()
        } else {
          this.comparison(this.user_idcard, this.baseImg64)
        }
      } else {
        this.ShowInfo('请先拍照！！！')
      }
    },
    upimg (base64img) {
      console.log(base64img, '11212')
      this.backImgUrl = ''
      let that = this
      this.loading = true
      let params = {}
      params.file = base64img
      params.filePath = this.filePath
      console.log(this.filePath)
      params.fileName = this.fileName
      var time = new Date().getTime()
      this.timeStep = time.toString()
      let param = {
        filePath: params.filePath,
        fileName: params.fileName,
        timestamp: this.timeStep
      }
      getSign(param).then(res => {
        if (res.data.errcode === 0) {
          console.log(this.filePath)
          createUpLoadFiles(res.data.data.docking_url, { sign: res.data.data.sign, timestamp: this.timeStep, filePath: this.filePath, fileName: this.fileName, file: base64img }).then(res => {
            if (res.data.errcode === 0) {
              that.loading = false
              // console.log(res.data.data, 's')
              // let data = JSON.parse(res.data.data)
              that.backImgUrl = res.data.data
              this.result_photo = true
              that.$emit('resultAction', { url: res.data.data })
            } else {
              that.loading = false
              that.$Notice.error({ title: '上传失败', desc: '请重新拍照' })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    },
    comparison (idcard, photo) {
      let img2 = photo
      let that = this
      if (idcard === '') {
        this.ShowInfo('身份证不能空')
        return false
      }
      getUserPhoto(idcard).then(rest => {
        that.loading = false
        let data = rest.data.data
        if (rest.data.errcode !== 0) {
          that.ShowInfo('没有用户信息，请先首次绑定用户信息')
          return false
        }
        that.rest_idcard_header = data.photo
        var div = document.getElementById('db')
        div.setAttribute('class', 'db-img')
        that.loading = true
        imgComparison(data.photo, img2).then(res => {
          console.log(res, '识别返回来的数据')
          that.loading = false
          if (res.data.confidence > 40) {
            that.faceSuccess = true
            let num = 0
            let one = true
            setInterval(function () {
              num += 10
              if (num <= 100) {
                that.percent = num
              }
              if (num > 120 && one) {
                one = false
                that.$emit('img-result', that.user_idcard)
              }
            }, 200)
          } else {
            that.ShowInfo('匹配度' + res.data.confidence + '%,不符合判定要求')
            console.log(res, '判断是否匹配啦啦111')
          }
        })
      })
    }
  }
}
</script>
