<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="3">
          <Button type="primary" @click="TakePhoto">拍照</Button>
        </i-col>
        <!-- <i-col span="12">
          <Button type="primary" :loading="loading">
            <span v-if="!loading">保存</span>
            <span v-else>正在保存...</span>
          </Button>
        </i-col> -->
      </Row>
    </div>
  </div>
</template>

<script>
import { createUpLoadFiles, getSign } from '@/api/common'
import Camera from '_c/stock-camera-2'

export default {
  name: 'DeYiPaiDevice',
  components: {},
  props: {
    isOpen: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    filePath: {
      type: String,
      default: () => {
        return 'de-yi-pai'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'de-yi-pai'
      }
    },
    type: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      errMsg: {
        show: false,
        msg: ''
      },
      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,
      pstockData: ''
    }
  },
  computed: {
    catImg () {
      return this.imgHeader + this.baseImg64
    }
  },
  created () {
    let _this = this
    this.Camera = Camera
    this.Camera.baseUrl = 'ws://127.0.0.1:3417'
    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.Camera.sendMsg('{ "command": 10001, "code": 1, "camidx":1,"autograp":0,"autocrop":0,"videoCanvas_width":640,"videoCanvas_height":480}')
          } else if (this.type === 'heightCamera') {
            this.Camera.sendMsg('{ "command": 10001, "code": 1, "camidx":0,"autograp":0,"autocrop":0,"videoCanvas_width":640,"videoCanvas_height":480,"videoformat":2,"bSelected":0}')
          }
          this.Camera.runmessage = this.acceptMsg
        } catch (e) {
          this.ShowInfo('没有发现设备')
        }
      } else {
        this.Camera.sendMsg('{ "command": 10001, "code":0, "camidx":0}')
      }
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
  },
  methods: {
    acceptMsg (event) {
      if (this.type === 'idcard') {
        let data = JSON.parse(event.data)
        if (data) {
          this.resultIdCart(data.IDNumber, data.Name, data.Sex, data.Adress, data.Nation, data.BornYear + '-' + data.BornMonth + '-' + data.BournDay, data.image)
        }
        this.stockData = 'data:image/jpeg;base64,' + data.image
      }
      if (this.type === 'heightCamera') {
        let data = JSON.parse(event.data)
        if (data.command === 20003) {
          // 拍照base64  清晰
          this.pstockData = data.pic
        } else {
          this.stockData = 'data:image/jpeg;base64,' + data.video
        }
        // this.stockData = 'data:image/jpeg;base64,' + data.video
      }
      if (this.type === 'faceCamera') {
        let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + data.video
      }
    },
    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 () {
      // this.Camera.cat()
      // if (this.Camera.endData.data) {
      //   let data = JSON.parse(this.Camera.endData.data)
      //   if (data.video) {
      //     this.imgUrl = data.result
      //     this.upimg(data.video)
      //   } else {
      //     this.ShowInfo('拍照失败！')
      //   }
      // } else {
      //   this.ShowInfo('拍照失败！')
      // }
      if (this.type === 'faceCamera') {
        this.Camera.sendMsg('{ "command": 10001, "code": 1, "camidx":1,"autograp":0,"autocrop":0,"videoCanvas_width":640,"videoCanvas_height":480}')
        this.Camera.cat()
        if (this.Camera.endData.data) {
          let data = JSON.parse(this.Camera.endData.data)
          if (data.video) {
            this.imgUrl = data.video
            this.upimg(data.video)
          } else {
            this.ShowInfo('拍照失败！')
          }
        } else {
          this.ShowInfo('拍照失败！')
        }
      } else if (this.type === 'heightCamera') {
        this.Camera.sendMsg('{ "command": 10003, "quality":75, "angle":0,"bShow":1}')
        this.Camera.runmessage = this.acceptMsg
        let that = this
        setTimeout(function () {
          if (that.pstockData) {
            that.imgUrl = that.pstockData
            that.upimg(that.pstockData)
          } else {
            that.ShowInfo('拍照失败！')
          }
        }, 2000)
      }
      this.is_photo = true
      this.result_photo = false
    },
    upimg (base64img) {
      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) {
          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('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.Camera.sendMsg('{ "command": 10010}')
        this.Camera.runmessage = this.acceptMsg
      } 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
      this.$emit('resultAction', cardInfo)
    }
  }
}
</script>
<style>
  .camera_btn {
    margin-right: 5px;
    margin-top: 5px;
  }
</style>
