<template>
  <div>
    <Row>
      <i-col span="24">
        <Alert type="error" v-if="errMsg.show">{{errMsg.msg}}</Alert>
      </i-col>
      <i-col span="12">
        <img :src="stockData" width="200px" height="200px" v-if="stock">
      </i-col>
      <i-col span="12">
        <img :src="catImg" width="200px" height="200px" v-if="stock">
      </i-col >
      <i-col span="3">
        <Button type="primary" @click="TakePhoto">拍照</Button>
      </i-col>
      <!-- <i-col span="12">
        <Button type="primary" :loading="loading" @click="savePhoto">
          <span v-if="!loading">保存</span>
          <span v-else>正在保存...</span>
        </Button>
      </i-col> -->
      </Row>
  </div>
</template>

<script>
import { createUpLoadFiles, getSign } from '@/api/common'
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: ''
      },
      Camera: Object,
      mediaStreamTrack: Object,
      loading: false,
      is_photo: false,
      stockData: String,
      baseImg64: String,
      imgHeader: 'data:image/jpeg;base64,',
      stock: true // true是调用捷宇科技的设备，false调用本地的摄像头
    }
  },
  created () {
    let _this = this
    this.Camera = Camera
    this.Camera.start(function (event) {
      // _this.acceptMsg(event.data)
    }, function (event) {
      _this.ShowInfo(event.data)
    })
    this.Camera.runmessage = this.acceptMsg
  },
  watch: {
    isPlay (bol) {
      if (bol) {
        if (this.stock) {
          this.Camera.sendMsg('bStartPlay2')
          this.Camera.runmessage = this.acceptMsg
        } else {
          this.newOpenCamera()
        }
      } else {
        if (this.stock) {
          this.Camera.close()
        }
        console.log('准备关闭摄像头')
      }
    }
  },
  computed: {
    catImg () {
      return this.imgHeader + this.baseImg64
    }
  },
  methods: {
    acceptMsg (event) {
      this.stockData = this.imgHeader + event.data
    },
    ShowInfos (event) {
      this.stockData = this.imgHeader + event.data
    },
    // 拍照
    TakePhoto () {
      if (this.stock) {
        this.Camera.cat()
        this.baseImg64 = this.Camera.endData.data
        this.upimg(this.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)
    },
    ShowInfo (op) {
      this.errMsg = { show: true, msg: op }
      let that = this
      setTimeout(function () {
        that.errMsg = { show: false, msg: '' }
      }, 2000)
    },
    savePhoto () {
      if (this.is_photo) {
        this.loading = true
        // this.upimg()
      } else {
        this.ShowInfo('请先拍照！！！')
      }
    },
    upimg (base64img) {
      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
              that.$emit('img-result', { url: res.data.data })
            } else {
              that.loading = false
              that.$Notice.error({ title: '上传失败', desc: '请重新拍照' })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    }
  }
}
</script>
