<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>
      </Row>
    </div>
  </div>
</template>

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

export default {
  name: 'LiangTianDevice',
  components: {},
  props: {
    isOpen: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    filePath: {
      type: String,
      default: () => {
        return 'liang-tian'
      }
    },
    fileName: {
      type: String,
      default: () => {
        return 'liang-tian'
      }
    },
    type: {
      type: String,
      default: () => {
        return '' // heightCamera----faceCamera----idcard
      }
    }
  },
  data () {
    return {
      errMsg: {
        show: false,
        msg: ''
      },
      stockData: Object,
      loading: false,
      backImgUrl: '',
      imgHeader: 'data:image/jpeg;base64,',
      num: 5,
      num1: 3,
      num2: 2,
      heightUrl: ''
    }
  },
  computed: {
    catImg () {
      return this.imgHeader + this.baseImg64
    }
  },
  created () {
    let _this = this
    this.Camera = Camera
    this.Camera.baseUrl = 'ws://127.0.0.1:12345'
    this.Camera.start(function (event) {
      // _this.acceptMsg(event)
    },
    function (event) {
      _this.ShowInfo(event.data)
    }
    )
    this.Camera.runmessage = this.acceptMsg
  },
  watch: {
    isOpen (e) {
      if (e) {
        try {
          console.log(this.num, 'type')
          this.num += 1
          if (this.type === 'faceCamera') {
            this.sendMsg()
            this.Camera.sendMsg('{"type":6,"object":"dialog","method":23,"args":["single_pri"],"id":' + this.num + '}')
            // this.Camera.sendMsg('{"type":6,"object":"dialog","method":24,"args":["subDev_:USB CAM2"],"id":' + this.num + '}')
            this.Camera.runmessage = this.acceptMsg
          } else if (this.type === 'heightCamera') {
            this.sendMsg()
            this.Camera.sendMsg('{"type":6,"object":"dialog","method":23,"args":["single_sub"],"id":' + this.num + '}')
            this.Camera.sendMsg('{"type":6,"object":"dialog","method":24,"args":["primaryDev_:2592 * 1944"],"id":' + this.num1 + '}')
            // this.Camera.sendMsg('{"type":6,"object":"dialog","method":24,"args":["primaryDev_:S520R"],"id":' + this.num + '}')
            this.Camera.runmessage = this.acceptMsg
            console.log('高拍仪')
            // this.Camera.sendMsg('{"type":6,"object":"dialog","method":26,"args":["closePriVideo"],"id":11}')
          }
          this.Camera.runmessage = this.acceptMsg
        } catch (e) {
          this.ShowInfo('没有发现设备')
        }
      } else {
        this.num += 1
        this.Camera.sendMsg('{"type":6,"object":"dialog","method":26,"args":["closePriVideo"],"id":' + this.num + '}')
        this.Camera.sendMsg('{"type":6,"object":"dialog","method":26,"args":["closeSubVideo"],"id":' + this.num + '}')
        this.stockData = ''
        // this.Camera.sendMsg('{"Func": "StopVideo", "arg": "1"}')
      }
      // if (e) {
      //   try {
      //     this.Camera.sendMsg('{"type":6,"object":"dialog","method":23,"args":["one"],"id":1}')
      //     this.Camera.runmessage = this.acceptMsg
      //   } catch (e) {
      //     this.ShowInfo('没有发现设备')
      //   }
      // } else {
      //   this.Camera.sendMsg('{"type":6,"object":"dialog","method":26,"args":["closeSignal"],"id":3}')
      // }
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
  },
  methods: {
    sendMsg () {
      this.num += 1
      this.Camera.sendMsg('{"type":3"id":' + this.num + '}')
      this.Camera.sendMsg('{"type":7,"object":"dialog","signal":5}')
      this.Camera.sendMsg('{"type":7,"object":"dialog","signal":6}')
      this.Camera.sendMsg('{"type":7,"object":"dialog","signal":9}')
      this.Camera.sendMsg('{"type":4}')
    },
    acceptMsg (event) {
      if (this.type === 'idcard') {
        let data = JSON.parse(event.data)
        // console.log(data)
        if (data.args && data.args.length > 0) {
          let arrInfo = data.args[0].split(' ')
          // o/this.Camera.sendMsg('"type":6,"object":"dialog","method":26,"args":["idFaceInfo"],"id":' + this.num + '}')
          console.log('arrsss', arrInfo)
          this.resultIdCart(arrInfo[7], arrInfo[0].split(':')[1], arrInfo[1], arrInfo[6], arrInfo[2], arrInfo[3] + arrInfo[4] + arrInfo[5], arrInfo[15].substr(arrInfo[15].indexOf('/'), arrInfo[15].length))
          console.log(arrInfo[15].substr(arrInfo[15].indexOf('/'), arrInfo[15].length), '666666')
        }
        this.stockData = 'data:image/jpeg;base64,' + data.args[0]
      }
      if (this.type === 'heightCamera') {
        let data = JSON.parse(event.data)
        if (data.args) {
          if (!data.args[0].startsWith('priModel') && !data.args[0].startsWith('priResolution')) {
            this.stockData = 'data:image/jpeg;base64,' + data.args[0]
          }
        }
      }
      if (this.type === 'faceCamera') {
        let data = JSON.parse(event.data)
        // console.log(data, 'dddd')
        if (data.args) {
          if (!data.args[0].startsWith('priModel') && !data.args[0].startsWith('priResolution')) {
            this.stockData = 'data:image/jpeg;base64,' + data.args[0]
          }
        }
      }
    },
    acceptMsg111 (event) {
      if (this.type === 'heightCamera') {
        let data = JSON.parse(event.data)
        if (data.signal === 9) {
          console.log(data.args[0])
          if (data.args) {
            if (!data.args[0].startsWith('priModel') && !data.args[0].startsWith('priResolution')) {
              this.stockData = 'data:image/jpeg;base64,' + data.args[0]
              this.heightUrl = data.args[0]
            }
          }
        }
      }
    },
    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.type === 'heightCamera') {
        console.log('高拍仪高拍仪')
        this.Camera.sendMsg('{"type":6,"object":"dialog","method":25,"args":["primaryDev_"],"id":' + this.num2 + '}')
        this.Camera.runmessage = this.acceptMsg111
        let that = this
        setTimeout(function () {
          if (that.heightUrl) {
            console.log(that.heightUrl)
            that.upimg(that.heightUrl)
          } else {
            that.ShowInfo('拍照失败！')
          }
        }, 2000)
        // this.backImgUrl = ''
        // this.Camera.cat()
        // if (this.Camera.endData.data) {
        //   let data = JSON.parse(this.Camera.endData.data)
        //   if (data.args && data.args.length > 0) {
        //     this.upimg(data.args[0])
        //   } else {
        //     this.ShowInfo('拍照失败！')
        //   }
        // } else {
        //   this.ShowInfo('拍照失败！')
        // }
      } else {
        this.backImgUrl = ''
        this.Camera.cat()
        if (this.Camera.endData.data) {
          let data = JSON.parse(this.Camera.endData.data)
          if (data.args && data.args.length > 0) {
            this.upimg(data.args[0])
          } else {
            this.ShowInfo('拍照失败！')
          }
        } 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
              console.log(that.backImgUrl, '1111')
              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.num += 1
        this.Camera.sendMsg('{"type":6,"object":"dialog","method":26,"args":["singleReadIDCard2"],"id":' + this.num + '}')
        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
      console.log(cardInfo, 'cccc')
      this.$emit('resultAction', cardInfo)
    }
  }
}
</script>
<style>
  .camera_btn {
    margin-right: 5px;
    margin-top: 5px;
  }
</style>
