<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==='heightCameraErCode'">
      <Alert type="error" v-if="errMsg.show">{{errMsg.msg}}</Alert>
      <Row>
        <Col span="24">
          <div id='CameraErCode' style="width:50%; height: 400px;float: left">
            <img :src="stockData1" style="width:100%; height: 400px">
          </div>
          <div style="width:49%; height: 400px;float: left;margin-left: 1%">
            <img :src="'data:image/jpeg;base64,' + pstockData1" style="width:100%; height: 400px">
          </div>
        </Col>
        <Col span="12">
          <Button type="primary" class="camera_btn" @click="catPureErCode()" >拍摄二维码</Button>
          <Button type="primary" class="camera_btn"  @click="GetBarCodeBase64(pstockData1)" :loading="loading1">识别二维码</Button>
          <span v-if="this.erCode === 0">
            <p style="color: red">识别错误，请从新拍摄！</p>
          </span>
        </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 SplitPane from '../../split-pane/split'

export default {
  name: 'ZiTuDevice',
  components: { SplitPane },
  props: {
    isOpen: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    filePath: {
      type: String,
      default: () => {
        return 'zi-tu'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'zi-tu'
      }
    },
    type: {
      type: String,
      default: () => {
        return '' // heightCamera----faceCamera----idcard
      }
    }
  },
  data () {
    return {
      erCode: '',
      item: {},
      timeStep: '',
      errMsg: {
        show: false,
        msg: ''
      },
      stockData: Object,
      pstockData: Object,
      stockData1: Object,
      pstockData1: Object,
      tackStockData: Object,
      loading: false,
      loading1: 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,
      apparatus_type: 0,
      errorTitle: '错误'
    }
  },
  created () {
    let _this = this
    this.Camera = Camera
    this.Camera.baseUrl = 'ws://127.0.0.1:8341'
    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') {
            console.log('人脸识别')
            this.Camera.sendMsg('{"Func": "StartRunSub", "arg": "0"}')
          } else if (this.type === 'heightCamera') {
            console.log('高拍仪')
            this.Camera.sendMsg('{"Func": "StartRunMain", "arg": "1"}')
            this.Camera.sendMsg('{"Func": "ChangeVideoResolution", "arg": "0"}')
            // this.Camera.sendMsg('{"Func": "SetWaterMark", "arg": {"watertext":"全市通办","waterfont":"宋体","position":"5","fontsize":"200","rvalue":"220","gvalue":"20","bvalue":"60", "sapceing":"100","Opacity":"1","open":"1"}}')
          } else if (this.type === 'heightCameraErCode') {
            console.log('识别市民码')
            this.Camera.sendMsg('{"Func": "StartRunMain", "arg": "1"}')
            this.Camera.sendMsg('{"Func": "ChangeVideoResolution", "arg": "0"}')
            // this.Camera.sendMsg('{"Func": "SetWaterMark", "arg": {"watertext":"全市通办","waterfont":"宋体","position":"5","fontsize":"200","rvalue":"220","gvalue":"20","bvalue":"60", "sapceing":"100","Opacity":"1","open":"1"}}')
          }
          this.Camera.runmessage = this.acceptMsg
        } catch (e) {
          this.ShowInfo('没有发现设备')
        }
      } else {
        this.Camera.sendMsg('{"Func": "StopVideo", "arg": "1"}')
      }
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
  },
  methods: {
    catPureErCode () {
      let data = { Func: 'CaptureBase64', arg: 0 }
      this.Camera.sendMsg(JSON.stringify(data))
      this.Camera.runmessage = this.acceptMsg
    },
    GetBarCodeBase64 (e) {
      this.loading1 = true
      let base64Str = e
      console.log(base64Str)
      var strOneLength = Math.ceil(base64Str.length / 470)
      try {
        for (var i = 0; i < strOneLength; i++) {
          let data = { Func: 'FingerBase64One', arg: { stringOne: base64Str.substr(i * 470, 470) } }
          this.Camera.sendMsg(JSON.stringify(data))
          this.Camera.runmessage = this.acceptMsg
        }
        // eslint-disable-next-line no-redeclare
        let data = { Func: 'GetBarCodeBase64', arg: 0 }
        this.Camera.sendMsg(JSON.stringify(data))
        this.Camera.runmessage = this.acceptMsg
      } catch (e) {

      }
    },
    recognition (e) {
      // console.log(e, '条形码')
      let d = e.replace(':\\apparatus', ':\\\\apparatus\\')
      // console.log(d, '结果')
      this.Camera.sendMsg('{"Func": "GetBarCode", "arg": "' + d + '"}')
      this.Camera.runmessage = this.acceptMsg222
      // console.log(this.Camera.runmessage, 'ddd')
    },
    acceptMsg222 (event) {
      let data = JSON.parse(event.data)
      console.log(event)
      if (data.FuncName === 'GetBarCodeBase64') {
        // 拍照base64  清晰
        let msg = JSON.parse(data.result)
        console.log(msg)
        console.log(msg.Result, 'lllllll')
        this.$emit('setMsg', msg.Result)
        // return msg.Result
        // console.log(data.result, '结果')
      }
    },
    setPath () {
      this.Camera.sendMsg('{"Func": "SetSavePath", "arg": "D:\\\\apparatus"}')
      this.apparatus_type = 1
    },
    merge (e1, e2) {
      console.log(e1, e2)
      let a = e1.replace(':\\apparatus\\', ':\\\\apparatus\\\\')
      let b = e2.replace(':\\apparatus\\', ':\\\\apparatus\\\\')
      var time = new Date().getTime()
      let y = time.toString()
      let x = 'D:\\\\apparatus\\\\' + y + '.jpg'
      this.Camera.sendMsg('{"Func": "CombineImages", "arg": {"pic1":"' + a + '","pic2":"' + b + '","savePic":"' + x + '","type":"1"}}')
    },
    acceptMsg (event) {
      if (this.type === 'idcard') {
        let data = JSON.parse(event.data)
        let data1 = {}
        if (data.result && data.result.length > 0) {
          data1 = JSON.parse(data.result)
          this.resultIdCart(data1.ID, data1.Name, data1.Sex, data1.Addr, data1.Nation, data1.BirthDate, data1.HeadPic)
        }
        this.stockData = 'data:image/jpeg;base64,' + data1.HeadPic
      }
      if (this.type === 'heightCamera') {
        let data = JSON.parse(event.data)
        if (data.FuncName === 'CaptureBase64') {
          // 拍照base64  清晰
          this.pstockData = data.result
        } else {
          this.stockData = 'data:image/jpeg;base64,' + data.result
        }
      }
      if (this.type === 'heightCameraErCode') {
        let data = JSON.parse(event.data)
        console.log(data, 'kkk')
        if (data.FuncName === 'CaptureBase64') {
          // 拍照base64  清晰
          this.pstockData1 = data.result
        } else if (data.FuncName === 'GetBarCodeBase64') {
          console.log(data.result, 'lllllll')
          this.erCode = data.result
          this.loading1 = false
          this.$emit('setMsg', data.result)
          this.pstockData1 = ''
        } else {
          this.stockData1 = 'data:image/jpeg;base64,' + data.result
          this.loading1 = false
        }
      }
      if (this.type === 'faceCamera') {
        let data = JSON.parse(event.data)
        this.stockData = 'data:image/jpeg;base64,' + data.result
      }
    },
    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 () {
      if (this.apparatus_type === 0) {
        console.log('paizhao')
        if (this.type === 'faceCamera') {
          console.log('人脸识别')
          this.Camera.sendMsg('{"Func": "StartRunSub", "arg": "0"}')
          this.Camera.cat()
          if (this.Camera.endData.data) {
            let data = JSON.parse(this.Camera.endData.data)
            if (data.result) {
              this.imgUrl = data.result
              this.upimg(data.result)
            } else {
              this.ShowInfo('拍照失败！')
            }
          } else {
            this.ShowInfo('拍照失败！')
          }
        } else if (this.type === 'heightCamera') {
          console.log('高拍仪')
          this.Camera.sendMsg('{"Func": "CaptureBase64", "arg": "0"}')
          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
      } else {
        console.log(this.apparatus_type, '此时为1')
        var time = new Date().getTime()
        this.timeStep = time.toString()
        this.Camera.sendMsg('{"Func": "CaptureFile", "arg": "' + this.timeStep + '.jpg' + '"}')
        this.Camera.runmessage = this.acceptMsg111
        let that = this
        setTimeout(function () {
          if (that.pstockData) {
            that.imgUrl = that.pstockData
          } else {
            that.ShowInfo('拍照失败！')
          }
        }, 2000)
      }
      this.is_photo = true
      this.result_photo = false
    },
    acceptMsg111 (event) {
      let data = JSON.parse(event.data)
      if (data.FuncName === 'CaptureFile') {
        // 拍照base64  清晰
        this.storagePath = data.result
        this.$emit('getPath', this.storagePath)
        console.log(data.result)
      }
    },
    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
              // 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('{"Func": "ReadIDCard", "arg": "0"}')
        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)
    },
    getCardInfo (item) {
      this.item = item
      try {
        this.Camera.sendMsg('{"Func": "ReadIDCard", "arg": "0"}')
        this.Camera.runmessage = this.acceptMsg3
      } catch (e) {
        this.ShowInfo('没有发现设备')
      }
    },
    acceptMsg3 (event) {
      let data = JSON.parse(event.data)
      if (data.result === '0') {
        // this.$Notice.error({ title: '错误', desc: '没找到二代证设备' })
        var content = '没找到二代证'
        this.$Modal.error({
          title: this.errorTitle,
          content: content,
          onOk: () => {
            this.$router.push({
              name: 'mainv3'
            })
          }
        })
        this.$emit('goonTodo')
      } else {
        // this.$emit('goonTodo', this.item)
      }
    }
  }
}
</script>
<style>
  .camera_btn {
    margin-right: 5px;
    margin-top: 5px;
  }
</style>
