<template>
  <modal :show.sync="show" v-ref:modal backdrop="false"  width="739px" style="overflow: auto">
    <header slot="modal-header">
      <div class="header">
        <span class="glyphicon glyphicon-remove-circle close" style="margin-top: 35px;margin-right: 30px" @click="close"></span>
        <h4 class="title">高拍仪（哲林）</h4>
      </div>
    </header>
    <article slot="modal-body" class="form-control" style="padding: 0px">
      <div class="form-group">
        <div class="operation-group">
          <strong class="operation" style="margin-top: 2px">高拍仪操作:</strong>
          <button class="btn btn-info photo" @click="bb()">拍照</button>
          <button class="btn btn-info" @click="GetVideoStatus()">设备状态</button>
          <button class="btn btn-info" @click="CloseVideo()">关闭设备</button>
          <button class="btn btn-info" @click="openApp()">开启程序</button>
        </div>
        <div class="showInfo">
          <IMG ID="SafeBase64IMG" src="" class="img"></IMG>
          <!--          <button style="position: absolute;buttom:-10px;left:0px;" @click="splitsimg">旋转</button>-->
          <textarea id="Console" disabled="disabled"></textarea>
          <IMG id="cam"  :src="cameraurl" width="640" height="640"/>
        </div>
        <br/>
        <div id="result"></div>
      </div>

    </article>
    <footer slot="modal-footer" class="modal-footer">
    </footer>
  </modal>
</template>

<script>
let ws
let server_addr = 'ws://127.0.0.1:38088'// 本机端口地址
export default {
  title: '高拍仪',
  data () {
    return {
      cameraurl: 'http://127.0.0.1:38088/video=stream&camidx=0',
      name: '',
      IdCardInfo: {},
      useType: '',
      jd: 'transform:rotate(0deg)',
      degs: 0
    }
  },
  props: ['show', 'fusetype', 'showid'],
  methods: {
    splitsimg () {
      this.degs += 90
      this.jd = `transform:rotate(${this.degs}deg)`
    },
    // 页面load消息
    onLoad () {
      return new Promise((resolve, reject) => {
        if (ws) {
          resolve()
        }
        ws = new WebSocket(server_addr)
        ws.onopen = (evt) => {
          if (this.connected) {
            resolve()
          }
          this.connected = true
          console.log('已连接服务器')
          this.output('已经连接到服务器')
          // 打开视频
          console.log('打开摄像头1')
          this.cam_switch(0)
          // 打开自动裁边
          // resolve()
        }
        ws.onclose = (evt) => {
          if (!this.connected) {
            window.location.href = 'FLShell://'
            setTimeout('this.onLoad()', 3)
          } else {
            this.output('已断开服务器连接')
            this.connected = false
          }
          ws = null
          reject(new Error('连接失败'))
        }
        ws.onmessage = (evt) => {
          if (evt.data.length === 0) {
            return
          }
          if (typeof evt.data === 'string') {
            let msg = JSON.parse(evt.data)
            console.log('msg1:', msg)
            if (msg.err && msg.err !== 0) {
              this.output('错误 - ' + msg.err + ', ' + msg.msg)
              reject('错误 - ' + msg.err + ', ' + msg.msg)
            } else if (msg.msg) {
              console.log('msg2:', msg)
              this.output(msg.msg)
            }
            if (msg.user_data) {
              this.callback[msg.user_data](msg)
              if (typeof msg.user_data === 'number') {
                this.callback[msg.user_data] = undefined
              }
            }
          } else {
            let file = new FileReader()
            file.onload = (evt) => {
              if (evt.target.readyState == FileReader.DONE) {
                let data = new Uint8Array(evt.target.result)
                if (data[0] == this.SVR_BIN_MSG.CAP_FRAME) {
                  return this.drawImage(data)
                }
              }
            }
            file.readAsArrayBuffer(evt.data)
          }
        }
        let canvas = document.getElementById('cam')
        canvas.onmousedown = (e) => {
          canvas.style.cursor = 'crosshair'
          this.clicked = true
          this.sendMsg(this.CLT_MSG.PRESET_MOUSEDOWN, {origX: e.layerX, origY: e.layerY}, function (msg) {
            if (msg.err !== 0) { }
          })
        }
        canvas.onmousemove = (e) => {
          if (!this.clicked) {
            canvas.style.cursor = 'default'
            return
          }
          canvas.style.cursor = 'crosshair'
          this.sendMsg(this.CLT_MSG.PRESET_MOUSEMOVE, {offx: e.layerX, offy: e.layerY}, (msg) => {
            if (msg.err !== 0) { }
          })
        }
        onmouseout = canvas.onmouseup = (e) => {
          canvas.style.cursor = 'default'
          if (!this.clicked) { return }
          this.sendMsg(this.CLT_MSG.PRESET_MOUSEUP, {offx: e.layerX, offy: e.layerY}, (msg) => {
            if (msg.err !== 0) {

            }
          })
          this.clicked = false
        }
      })
    },
    // 打开视频
    cam_switch (data) {
      let g_iCamIdx = data
      this.cameraurl = 'http://127.0.0.1:38088/video=stream&camidx=' + g_iCamIdx + '&tid=' + Date.parse(new Date())
    },
    // 关闭视频
    CloseVideo () {
      var params = ''
      var url = this.cameraurl.replace('stream', 'close')
      this.cameraurl = ''
      this.$resetpost(url, params).then((msg) => {   // 截图
        if (msg.data.code != '0') {
          document.getElementById('result').innerHTML = data.message
        }
      })
    },
    // 获取设备状态
    GetVideoStatus () {
      document.getElementById('result').innerHTML = ''
      var params = ''
      var url = 'http://127.0.0.1:38088/video=status'
      this.cameraurl = ''
      this.$resetpost(url, params).then((msg) => {   // 截图
        if (msg.data.code != '0') {
          document.getElementById('result').innerHTML = '获取设备状态失败，返回代码 = ' + data.code + '，返回信息 = ' + data.message
        } else {
          document.getElementById('result').innerHTML = '文档摄像头:' + msg.data.video0 +
            ', 人像1:' + msg.data.video1
        }
      })
    },
    openApp () {
      window.location.href = 'cameraServicetis:0' // 启动 CameraService 服务程序
    },
    // 设置截图保存的jpg格式压缩质量
    SetQuality () {
      if (this.iswaiting) return
      this.iswaiting = true
      this.sendMsg(this.CLT_MSG.SET_QUALITY, {quality: 50}, (msg) => {
        if (msg.err !== 0) {
          this.iswaiting = false
          return
        }
        this.output('设置拍照图片质量 : quality=' + 50)
        this.iswaiting = false
      })
    },
    // 设置自动裁边开启
    SetAutoCutOn () {
      console.log('设置自动采编')
      if (this.iswaiting) return
      this.iswaiting = true
      this.sendMsg(this.CLT_MSG.SET_AUTOCROP, {open: 1}, (msg) => {
        if (msg.err !== 0) {
          this.iswaiting = false
          return
        }
        this.output('设置自动裁边 : open=' + 1)
        this.iswaiting = false
      })
    },
    // 设置自动裁边关闭
    SetAutoCutOff () {
      if (this.iswaiting) return
      this.iswaiting = true
      this.sendMsg(this.CLT_MSG.SET_AUTOCROP, {open: 0}, (msg) => {
        if (msg.err !== 0) {
          this.iswaiting = false
          return
        }
        this.output('设置自动裁边 : open=' + 0)
        this.iswaiting = false
      })
    },
    // 取消预设框选
    ResetBox () {
      if (this.iswaiting) return
      this.iswaiting = true
      this.sendMsg(this.CLT_MSG.SET_PREST, {left: 0, top: 0, width: 0, height: 0}, (msg) => {
        if (msg.err !== 0) {
          this.iswaiting = false
          return
        }
        this.resetx = 0
        this.resety = 0
        this.resetwidth = 0
        this.resetheight = 0
        this.output('取消预设框选')
        this.iswaiting = false
      })
    },

    // //设置颜色模式 只针对截图
    bb () {
      let camidx = 0
      if (this.cameraurl.indexOf('http://127.0.0.1:38088/video=stream&camidx=0') != -1) {
        camidx = 0
      } else if (this.cameraurl.indexOf('http://127.0.0.1:38088/video=stream&camidx=1') != -1) {
        camidx = 1
      } else {
        this.$showAlert('请先打开视频', 'warning', 2000)
        return
      }
      let param = {
        camidx: camidx
      }
      this.$resetpost('http://127.0.0.1:38088/video=grabimage', param).then((msg) => {   // 截图
        if (msg.data.code != '0') {
          this.$showAlert(msg.data.message, 'warning', 2000)
          return
        }
        let s = 'data:image/jpg;base64,' + msg.data.photoBase64
        document.getElementById('SafeBase64IMG').src = s// 网页预览图片
        this.output('base64 长度 : ' + s.length)
        this.$emit('photo-finish', {img: msg.data.photoBase64})
        this.name = ''
      })
    },
    // 内存截图
    bbase64 () {
      if (this.iswaiting) return
      this.iswaiting = true
      this.sendMsg(this.CLT_MSG.GET_PICTURE_MEM, {turn: 0}, (msg) => {
        if (msg.err !== 0) {
          this.iswaiting = false
          return
        }
        let s = 'data:image/jpg;base64,' + msg.base64str
        document.getElementById('SafeBase64IMG').src = s// 网页预览图片
        alert(s)
        this.output('base64 长度 : ' + s.length)
        this.iswaiting = false
      })
    },
    sendMsg (proto, msg, cb) {
      if (!ws) {
        return
      }

      if (typeof msg !== 'object') {
        if (typeof msg === 'function') {
          cb = msg
          msg = {}
        } else {
          msg = {}
        }
      }

      msg.proto = proto
      if (typeof cb === 'function') {
        this.callback[++this.context] = cb
        msg.user_data = this.context
      }

      ws.send(JSON.stringify(msg))
    },
    output (content) {
      if (content.length == 0) {	return }
      let console = document.getElementById('Console')
      console.value += content
      console.value += '\r'
      console.scrollTop = console.scrollHeight
    },
    close () {
      this.show = !this.show
      if (this.isopen) {
        this.CloseVideo()
      }
    }
  },
  computed: {
    foptions () {
      return this.$appdata.getParam('使用类型')
    }
  },
  ready () {
    this.onLoad().then(() => {
      this.useType = this.fusetype
      this.$emit('ready')
    }).catch((error) => {
      this.$emit('error', error)
    })
  }
}
</script>

<style scoped>
.modal-bk{
  border-radius:18px 0;
}
.header{
  background-color: #d8e9f3;
  height: 88px;
}
.title{
  margin-top: 0;
  padding-top: 20px;
  text-align: center;
  font-family:PingFang-SC-Bold;
  font-size:36px;
  color: #666666;
  margin-bottom: 0px;
}
.operation{
  font-family:PingFang-SC-Medium;
  font-size: 22px;
  color:#666666;
  line-height: 5px;
}
.operation-group{
  margin-left: 36px;
  margin-top: 20px;
}
.photo{
  font-family: PingFang-SC-Medium;
  font-size: 20px;
  color: #ffffff;
  margin-left: 20px;
  border-radius: 4px;
  background-color: #2fadf5;
  height: 32px;
  width: 92px;
  line-height:12px;
}
.readIDCard{
  font-family: PingFang-SC-Medium;
  font-size: 20px;
  color: #ffffff;
  border-radius: 4px;
  background-color: #2fadf5;
  margin-left: 20px;
  width: 120px;
  height: 32px;
  line-height: 12px;
}
.stop{
  border-radius: 4px;
  border: 1px solid #2fadf5;
  font-family: PingFang-SC-Medium;
  font-size: 20px;
  color: #2fadf5;
  width: 120px;
  height: 32px;
  line-height: 12px;
}
.showInfo{
  float: left;
  width: 640px;
  display: inline-block;
  margin-top: 20px;
  margin-left: 36px;
}
#Console{
  margin-left: 18px;
  border-radius: 4px;
  border: 1px solid #b5b5b5;
  height:300px;
  width:322px;
  resize:none;
  background-color: #f6f6f6;
}
.img{
  height:300px;
  width:300px;
  float: left;
  border-radius: 4px;
  border: 1px solid #b5b5b5;
}
#cam{
  border-radius: 4px;
  border:1px solid #b5b5b5;
  display: inline-block
}
.IdCard{
  height: 950px;
  width: 692px;
  display: inline-block;
  border-radius: 20px;
  background-color: #fafafa;
  border: 1px solid #d8f1ff;
  margin-left: 40px;
  margin-top: 20px;
}
.IdInput{
  border-radius: 4px;
  border: 1px solid #939393;
  width: 400px;
  height: 38px;
  margin-left: 20px;
}
.IdInputDiv{
  margin-top: 20px;
  margin-left: 100px;
}
.IdHint{
  font-family: PingFang-SC-Medium;
  font-size: 18px;
  color: #7e7c81;
}
#PhotoBuffer,#PhotoDisplay{
  border-radius: 4px;
  background-color: #ffffff;
  border: 1px solid #939393;
  margin-left: 20px;
}
</style>
