<style lang="less">
  .db-img {
    height: 200px;
    width: 200px;
  }
  .takePhoto {
    margin-top: 5px;
    margin-bottom: 5px;
  }
</style>
<template>
  <div>
    <div v-if="type==='heightCamera'">
      <Alert type="error" v-if="errMsg.show">{{errMsg.msg}}</Alert>
      <Row>
        <Col span="24">
          <div id='CameraCtl' style="width:100%; height: 400px">
            <img :src="stockData" style="width:100%; height: 400px">
          </div>
        </Col>
        <Col span="24">
          <Button type="primary" class="camera_btn" @click="TakePhoto" :loading="loading">拍照</Button>
        </Col>
      </Row>
    </div>
    <div v-if="type==='faceCamera'">
      <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">
        </i-col>
        <i-col span="12">
          <img :src="backImgUrl" width="200px" height="200px">
        </i-col>
        <i-col span="24" class="takePhoto">
          <Button type="primary" @click="TakePhoto">拍照</Button>
        </i-col>
      </Row>
    </div>
  </div>
</template>

<script>
import { createUpLoadFiles, getSign } from '@/api/common'
import Camera from '_c/stock-camera-2'
import { getUserPhoto } from '@/api/mainv3'
import SplitPane from '../../split-pane/split'

export default {
  name: 'WeiShanDevice',
  components: { SplitPane },
  props: {
    isOpen: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    filePath: {
      type: String,
      default: () => {
        return 'wei-shan'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'wei-shan'
      }
    },
    type: {
      type: String,
      default: () => {
        return '' // heightCamera----faceCamera----idcard
      }
    }
  },
  data () {
    return {
      errMsg: {
        show: false,
        msg: ''
      },
      NowTime: '',
      stockData: Object,
      loading: false,
      backImgUrl: '',
      imgHeader: 'data:image/jpeg;base64,',
      severUserInfo: {},
      user_idcard: '',
      is_photo: false,
      result_photo: false,
      rest_idcard_header: '',
      imgUrl: '', // 拍照返回图片的base64
      percent: 0,
      faceSuccess: false,
      imgSrc: '',
      infoData: []
    }
  },
  created () {
    let _this = this
    this.Camera = Camera
    this.Camera.baseUrl = 'ws://localhost:9000/'
    this.Camera.start(function (event) {
      // _this.acceptMsg(event)
    },
    function (event) {
      _this.ShowInfo(event.data)
    }
    )
    // this.Camera.runmessage = this.acceptMsg
  },
  watch: {
    isOpen (e) {
      this.backImgUrl = ''
      if (e) {
        try {
          if (this.type === 'faceCamera') {
            this.initSendMsg()
            let that = this
            setTimeout(function () {
              that.Camera.sendMsg('{"FuncName":"camOpenDev","argument":{"devIndex": 1,"subtype": 0,"width": 0,"height": 0}}')
            }, 2000)
            console.log('人脸识别')
          } else if (this.type === 'heightCamera') {
            this.initSendMsg()
            let that = this
            console.log('高拍仪')
            setTimeout(function () {
              that.Camera.sendMsg('{"FuncName":"camOpenDev","argument":{"devIndex": 0,"subtype": 0,"width": 0,"height": 0}}')
            }, 2000)
          }
          this.Camera.runmessage = this.acceptMsg
        } catch (e) {
          this.ShowInfo('没有发现设备')
        }
      } else if (this.type === 'faceCamera') {
        this.uinitSendMsg()
        let that = this
        setTimeout(function () {
          that.Camera.sendMsg('{"FuncName": "camCloseDev", "argument":{"devIndex": 1}}')
        }, 2000)
      } else if (this.type === 'heightCamera') {
        this.uinitSendMsg()
        let that = this
        setTimeout(function () {
          that.Camera.sendMsg('{"FuncName": "camCloseDev", "argument":{"devIndex": 0}}')
        }, 2000)
      }
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
  },
  methods: {
    initSendMsg () {
      this.Camera.sendMsg('{FuncName: "camInitCameraLib"}')
    },
    uinitSendMsg () {
      this.Camera.sendMsg('{FuncName: "camUnInitCameraLib"}')
    },
    acceptMsg (event) {
      console.log('=======')
      if (this.type === 'heightCamera') {
        // let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + event.data1
      }
      if (this.type === 'idcard') {
        console.log(event, '@@@@@')
        if (event.data.indexOf('$') !== -1) {
          this.stockData = 'data:image/jpeg;base64,' + event.data.substring(22)
          this.imgSrc = event.data.substring(22)
          this.resultIdCart(this.infoData[5], this.infoData[0], this.infoData[1], this.infoData[4], this.infoData[2], this.infoData[3], this.imgSrc)
        } else {
          let data = JSON.parse(event.data)
          if (data.result && data.result.length > 0) {
            let data1 = data.result.split('|')
            this.infoData = data1
            this.resultIdCart(data1[5], data1[0], data1[1], data1[4], data1[2], data1[3], this.imgSrc)
          }
        }
        // if (event.data1) {
        //   this.stockData = 'data:image/jpeg;base64,' + event.data.substring(22)
        //   console.log(this.stockData, '身份证照片')
        // }
      }
      if (this.type === 'faceCamera') {
        // let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + event.data1
      }
    },
    acceptMsg1 (event) {
      console.log('$%$%$%$%')
      if (this.type === 'heightCamera') {
        // let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + event.data1
      }
      if (this.type === 'idcard') {
        console.log(event, '@@@@!!!!!!!!!!!!!!!!!!')
        // let data = JSON.parse(event.data)
        // console.log(data, '!!!!!!!!!!!!!!!!!!')
        // if (data.result && data.result.length > 0) {
        //   let data1 = data.result.split('|')
        //   this.resultIdCart(data1[5], data1[0], data1[1], data1[4], data1[2], data1[3], data1.HeadPic)
        // }
        // this.stockData = 'data:image/jpeg;base64,' + data.result
      }
      if (this.type === 'faceCamera') {
        // let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + event.data1
      }
    },
    ShowInfo (op) {
      this.errMsg = { show: true, msg: op }
      let that = this
      setTimeout(function () {
        that.errMsg = { show: false, msg: '' }
      }, 2000)
    },
    formatDate (time) {
      let date = new Date(time)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let min = date.getMinutes()
      let sec = date.getSeconds()
      let newTime = year + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day) + (hour < 10 ? '0' + hour : hour) + (min < 10 ? '0' + min : min) + (sec < 10 ? '0' + sec : sec)
      return newTime
    },
    toOpenCamera () {
      this.ShowInfo('打开了设备！')
    },
    // 拍照
    TakePhoto () {
      console.log('paizhao')
      this.Camera.cat()
      if (this.Camera.endData.data1) {
        if (this.Camera.endData.data1) {
          this.imgUrl = this.Camera.endData.data1
          this.upimg(this.Camera.endData.data1)
        } else {
          this.ShowInfo('拍照失败！')
        }
      } else {
        this.ShowInfo('拍照失败！')
      }
      this.is_photo = true
      this.result_photo = false
    },
    upimg (base64img) {
      this.backImgUrl = ''
      let that = this
      this.loading = true
      let params = {}
      params.file = base64img
      params.filePath = 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
              that.backImgUrl = res.data.data
              that.$emit('resultAction', res.data, base64img)
            } else {
              that.loading = false
              that.$Notice.error({ title: '上传失败', desc: '请重新拍照' })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    },
    getIdcardInfo () {
      try {
        this.initSendMsg()
        this.NowTime = this.formatDate()
        let that = this
        setTimeout(function () {
          that.Camera.sendMsg('{"FuncName":"idcardrfidReadIDCard","argument":{"HeadPath": "headPic.bmp"}}')
          that.Camera.sendMsg('{"FuncName":"FileEncodeBase64","argument":{"filePath": "headPic.bmp"}}')
          that.Camera.runmessage = that.acceptMsg
        }, 2000)
      } catch (e) {
        this.ShowInfo('没有发现设备')
      }
    },
    resultIdCart (idcard, name, sex, domicile_address, folk, birthday, HeadPic) {
      let cardInfo = {}
      cardInfo.idcard = idcard
      cardInfo.cardno = idcard
      cardInfo.name = name
      cardInfo.sex = sex
      cardInfo.address = domicile_address
      cardInfo.folk = folk
      cardInfo.birthday = birthday
      cardInfo.HeadPic = HeadPic
      console.log(cardInfo, '123434')
      if (cardInfo.HeadPic !== '') {
        this.$emit('resultAction', cardInfo)
      }
    },
    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) {
            console.log('!@!@!@')
            that.faceSuccess = true
            let num = 0
            let one = true
            setInterval(function () {
              num += 10
              if (num <= 100) {
                that.percent = num
                console.log(that.percent, '121212')
              }
              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>
<style>
  .camera_btn {
    margin-right: 5px;
    margin-top: 5px;
  }
</style>
