<template>
  <el-dialog title="读卡" :visible.sync="isOpenCardeds" :destroy-on-close="true" width="561px" custom-class="my-reader-card"
    :show-close="true" :close-on-click-modal="false" @close="handleCloseModal">
    <div class="my-card-body">
      <!-- <div style="position: absolute;right: 24px;top: 15px;width: 19px;" @click="handleCloseModal">X</div> -->
      <img :src="logo" style="display: block; " alt="logo" />
      <!-- 目前因为开发阶段没有很多扫码设备，需要先设置输入框和下拉框满足当下情况 -->
      <div class="swipe_user_select_content" style="margin:10px auto;">
        <!-- <el-select ref="physicalCardType" v-model="form.physicalCardType" style="width: 30%;" placeholder="请选择卡类型"
          @change="handleSelect">
          <el-option v-for="(item, i) in DiagnosisCardOptions" :key="i" :label="item.name" :value="item.code" />
        </el-select> -->
        <el-form  element-loading-text="刷卡中，请稍后" element-loading-spinner="el-icon-loading" @submit.native.prevent>
          <el-form-item>
            <el-input ref="cardInput" v-model.trim="form.physicalCard" style="width: 282px;margin-left: 10px; "
              placeholder="请输入卡号" @blur="handleSetFocus()" @keyup.enter.native="handleEnterModal()" />
          </el-form-item>
        </el-form>
        <!-- <el-input ref="cardInput" v-model.trim="form.physicalCard" style="width: 282px;margin-left: 10px; "
          placeholder="请输入卡号" @blur="handleSetFocus()" @keyup.enter.native="handleEnterModal()" /> -->
      </div>
    </div>
  </el-dialog>
</template>
<script>
// import dictApi from '@/api/sys/dictionary'
export default {
  components: {},
  props: {
    isOpenCarded: Boolean,
    physicalCardType: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      listinfo:{
        type:'',

      },
      loadingapplyList:false,
      logo: require('@/assets/logo/CardReader.gif'),
      isOpenCardeds: this.isOpenCarded, // 是否开启读卡
      websocket: null, // 定义this.websocket
      interval: null, // 定时器每1秒钟去循环调用读卡的方法
      PatientInfo: {}, // 患者信息
      form: {
        physicalCardType: '4', // 卡类型 默认身份证
        physicalCard: '' // 卡号
      },
      DiagnosisCardOptions: [] // 患者卡类型
    }
  },
  watch: {
    isOpenCarded: {
      handler(v) {

        this.isOpenCardeds = v
        if (v === true) {
          this.$nextTick(() => {

            this.form.physicalCard = ''
            this.form={}
            this.$refs.cardInput.focus()
            setTimeout(() => {
              this.opendevice()
            }, 1000)
          })
        } else {
          this.closedevice()
          return false
        }
      }
    }
  },
  created() {
    // 就诊卡类型
    // this.getDic('DiagnosisCardType', 'DiagnosisCardOptions')
  },
  mounted() {
    // 初始化websocket
    this.initWebSocket()
  },
  methods: {
    // 当不关闭刷卡弹窗的时候需要对input框失去焦点的时候继续聚焦
    handleSetFocus() {
      this.$nextTick(() => {
        this.$refs.cardInput.focus()
      })
    },
    // 关闭弹窗
    handleCloseModal() {
      this.$emit('closeReadcard', false)
      // this.isOpenCarded = false
      if (this.DiagnosisCardOptions?.length > 0) {
        this.form.physicalCardType = this.DiagnosisCardOptions[0].code
      } else {
        this.form.physicalCardType = ''
      }
      this.form.physicalCard = ''
      this.PatientInfo = {}
      clearInterval(this.interval)
      this.closedevice()

    },
    // 输入框回车事件
    handleEnterModal() {

      if (this.form.physicalCard.toString().length === 28) {
        this.loadingapplyList=true
        // 电子医保码
        setTimeout(function(){
          this.loadingapplyList=false
        },1000)
        this.form.physicalCardType = 'YBEWM'
        this.listinfo.type='YBEWM'
        this.listinfo.value=this.form.physicalCard
        this.$emit('getyibaoinfo', this.form,this.listinfo)
      } else if (this.form.physicalCard.toString().length === 15) {
        // 就诊卡
        this.form.physicalCardType = 'HOSPITAL_CARD'
        this.$emit('getyibaoinfo', this.form)
      } else if (this.form.physicalCard.toString().length === 8) {
        // 输入患者id
        this.form.physicalCardType = 'PATIENT_ID'
        this.$emit('getyibaoinfo', this.form)
      }else if (this.form.physicalCard.toString().length > 64) {
        // 截取前64位获取电子健康卡编码
        this.form.physicalCard = this.form.physicalCard.toString().substring(0, 64)
        this.form.physicalCardType = 'ELECTRONIC_HEALTH_CARD'
        this.$emit('getyibaoinfo', this.form)
      } else if (this.form.physicalCard.toString().length === 18) {
        // 就诊卡
        this.form.physicalCardType = 'ID_CARD'
        this.$emit('getyibaoinfo', this.form)
      }

      const val = {
        physicalCardType: this.form.physicalCardType,
        physicalCard: this.form.physicalCard,
        PatientInfo: this.PatientInfo // 回显患者相关的信息
      }
      // 社保卡多回传[识别码&姓名]字段---刘春 2023年4月23日15:58:00
      if (this.form.physicalCardType === '3' || this.form.physicalCardType === 3) {
        val.physicalKsbm = this.form.ksbm
        val.physicalXm = this.form.Xm
      }
      this.$emit('handleEnterModal', val)
    },
    // 切换卡类型聚焦输入框
    handleSelect() {
      this.$nextTick(() => {
        this.$refs.physicalCardType.blur()
        this.$refs.cardInput.focus()
      })
    },
    // 字典
    async getDic(val, field) {
      const para = { TypeCode: val }
      const res = await dictApi.getFirstListByTypeCode(para)
      if (res.success) {
        this[field] = res.data
        if (val === 'DiagnosisCardType') this.form.physicalCardType = this[field][0].code
      }
    },
    // 初始化websocket,链接外部设备
    initWebSocket() {
      if (!window.WebSocket) {
        this.$message({
          message: '该版本浏览器不支持WebSocket',
          type: 'warning',
          showClose: true
        })
      }
      this.websocket = new WebSocket('ws://127.0.0.1:6932/')
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage
      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage
      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage() {
      // 初始化websocket
      this.initWebSocket()
    },
    setOnopenMessage() { },
    // 判断是否为json对象
    isJSON(str) {
      if (typeof str === 'string') {
        try {
          var obj = JSON.parse(str)
          if (typeof obj === 'object' && obj) {
            // 去除布尔类型等特殊情况
            return true // 字符串为JSON格式
          } else {
            return false
          }
        } catch (e) {
          return false
        }
      }
    },
    // 接收websocket返回的数据值
    // 卡类型：就诊卡1，身份证4，社保卡3，山东省健康码8，医保电子凭证2
    setOnmessageMessage(evt) {
      let data = ''
      if (this.isJSON(evt.data) && evt?.data) {
        data = JSON.parse(evt.data)
      }
      // 开启读卡设备并且设置定时任务
      if (data?.MethodName === 'OpenDevice' && data?.RespCode === 0) {
        this.interval = setInterval(() => {
          this.startwsReadCard() // 每两秒执行一次读卡的方法
        }, 2000)
      } else {
        if (data?.MethodName === 'ReadM1Card' && data?.RespCode === 0) {
          // 读取M1卡
          if (data) {
            if (data?.RespData) {
              this.PatientInfo = data.RespData
              this.form.physicalCardType = 'HOSPITAL_CARD'
              if (data.RespData?.AsciiData) {
                this.form.sfzhm = data.RespData.AsciiData
              }
            }
          }
          this.$emit('getyibaoinfo', this.form)

          if (this.form.sfzhm) {
            clearInterval(this.interval)
            // this.handleEnterModal()
            this.closedevice()

          }
        } else if (data?.MethodName === 'ReadIDCard' && data?.RespCode === 0) {
          // 读取身份证号
          if (data) {
            if (data?.RespData) {
              this.PatientInfo = data.RespData
              this.form.physicalCardType = 'ID_CARD'
              if (data.RespData?.CardId) {
                this.form.physicalCard = data.RespData.CardId
              }
            }
          }
          this.$emit('getyibaoinfo', this.form)
          if (this.form.physicalCard) {
            clearInterval(this.interval)
            // this.handleEnterModal()
            this.closedevice()
            return true
          }
        } else if (data?.MethodName === 'ReadSSSECard' && data?.RespCode === 0) {
          // 读取社保卡
          if (data) {
            if (data?.RespData) {
              this.PatientInfo = data.RespData
              this.form.physicalCardType = 'SOCIAL_CARD'
              if (data.RespData?.CardNo) {
                this.form.physicalCard = data.RespData.CardNo
                // 社保卡多回传[识别码&姓名]字段---刘春 2023年4月23日15:58:00
                this.form.ksbm = data.RespData.ksbm
                this.form.xm = data.RespData.xm
                 this.form.sfzh = data.RespData.sfzh
                this.form.kh=data.RespData.CardNo
                this.form.physicalCard = data.RespData.kh
              }
            }
          }
          this.$emit('getyibaoinfo', this.form)
          if (this.form.physicalCard) {
            clearInterval(this.interval)
            // this.handleEnterModal()
            this.closedevice()
            return false;
          }
          return false;
        }

      }

    },
    setOncloseMessage(evt) {
    },
    onbeforeunload() { // 组件销毁关闭websoket
      this.closeWebSocket()
    },
    closeWebSocket() {
      this.websocket.close()
    },
    // 读卡接口，当获取到患者卡号的时候停止监听事件
    startwsReadCard() {
      // 读医保卡号
      if (!this.form.physicalCard || this.form.physicalCard === '') {
        // 读身份证
        this.readIDcard()
      }
      if (!this.form.physicalCard || this.form.physicalCard === '') {
        // 读医保卡
        this.readSSSEcard()
      }
      if (!this.form.physicalCard || this.form.physicalCard === '') {
        // 读m1卡
        this.readM1card()
      }
    },
    // 打开设备
    opendevice() {
      this.websocket.send('{ "MethodName": "OpenDevice" }')
    },
    // 关闭设备
    closedevice() {
      this.websocket.send('{ "MethodName": "CloseDevice" }')
      this.$emit('closeReadcard', false)
    },
    // 读m1卡
    readM1card() {
      this.websocket.send('{ "MethodName": "ReadM1Card",  "Methoddata":  {    "Adr": 1,    "PassWord": "FFFFFFFFFFFF"  } }')
    },
    // 读社保卡
    readSSSEcard() {
      this.websocket.send('{ "MethodName": "ReadSSSECard" }')
    },
    // 读身份证
    readIDcard() {
      this.websocket.send('{ "MethodName": "ReadIDCard"}')
    },
    // 错误测试
    errortest() {
      this.websocket.send('{ "MethodName": "test"}')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .el-dialog__body {
    padding: 0 !important;
  }

  .my-reader-card {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    // position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: calc(100% - 30px);
    max-width: calc(100% - 30px);
    border-radius: 10px;

    .my-card-body,
    .swipe_user_card {
      width: 100%;
      height: 100%;
      cursor: pointer;
    }

    .my-card-body {
      position: relative;

      .colse-user-card {
        position: absolute;
        font-size: 20px;
        right: 3%;
        top: 6%;
        background: #ffffff;
      }

      .swipe_user_select_content {
        width: 100%;
        // position: absolute;
        // opacity: 0;
        bottom: 30px;
        display: flex;
        justify-content: center;
        // padding-left: 16%;
      }
    }
  }
}

.my-read-card-number {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.handle_enter_cardNumber {
  width: 50%;
}
</style>
