<template>
  <el-dialog :visible.sync="visible" title="核酸检测登记" :close-on-click-modal="false" :close-on-press-escape="false" top="10vh" width="55%" :before-close="handleClose">
    <el-form>
      <el-form-item>
        <el-button @click="connect" :hidden="connectStatus">连接</el-button>
        <!-- <el-button @click="getSamid">读安全模块号</el-button> -->
        <el-button @click="readCard" :disabled="!connectStatus">读卡</el-button>
        <!-- <el-button @click="disconnect" :disabled="!connectStatus">断开</el-button> -->
      </el-form-item>
    </el-form>
    <el-form :inline="true" :rules="dataRule" :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <!-- <el-form-item label="模块号:" prop="samid">
        <el-input type="text" v-model="dataForm.samid" placeholder="安全模块号" readonly></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="读卡时间:" prop="timeElapsed">
        <el-input type="text" v-model="dataForm.timeElapsed" placeholder="读卡时间" readonly></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="证件类别:" prop="certType">
        <el-input type="text" v-model="dataForm.certType" placeholder="证件类别" readonly></el-input>
      </el-form-item> -->
      <el-form-item label="姓名:" prop="name" label-width="100px">
        <el-input type="text" v-model="dataForm.name" placeholder="姓名" readonly></el-input>
      </el-form-item>
      <el-form-item label="照片:" prop="imgCode" label-width="100px">
        <img :hidden="!imageSrc" :src="imageSrc" style="height: 126px;"/>
        <div v-show="!imageSrc" class="image-src">照片</div>
      </el-form-item>
      <el-form-item label="手机号:" prop="mobile" class="under-name" label-width="100px">
        <el-input type="text" v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="性别:" prop="sex" label-width="100px">
        <el-input type="text" v-model="dataForm.sex" placeholder="性别" readonly></el-input>
      </el-form-item>
      <el-form-item label="民族:" prop="nation" label-width="100px">
        <el-input type="text" v-model="dataForm.nation" placeholder="民族" readonly></el-input>
      </el-form-item>
      <el-form-item label="出生日期:" prop="birthday" label-width="100px">
        <el-input type="text" v-model="dataForm.birthday" placeholder="出生日期" readonly></el-input>
      </el-form-item>
      <el-form-item label="住址:" prop="address" label-width="100px">
        <el-input type="text" v-model="dataForm.address" placeholder="住址" readonly></el-input>
      </el-form-item>
      <el-form-item label="身份证号:" prop="idcard" label-width="100px">
        <el-input type="text" v-model="dataForm.idcard" placeholder="身份证号" readonly></el-input>
      </el-form-item>
      <el-form-item label="签发机关:" prop="organ" label-width="100px">
        <el-input type="text" v-model="dataForm.organ" placeholder="签发机关" readonly></el-input>
      </el-form-item>
      <!-- <el-form-item label="开始期限:" prop="effDate">
        <el-input type="text" v-model="dataForm.effDate" placeholder="开始期限" readonly></el-input>
      </el-form-item>
      <el-form-item label="结束期限:" prop="expDate">
        <el-input type="text" v-model="dataForm.expDate" placeholder="结束期限" readonly></el-input>
      </el-form-item> -->
    </el-form>
    <template slot="footer">
      <el-button @click="handleClose">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()" :disabled="btnAble">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import axios from 'axios'
export default {
  data () {
    return {
      btnAble: false,
      visible: false,
      dataForm: {
        // samid: '',  // 安全模块号
        // certType: '', // 证件类型
        name: '', // partyName
        mobile: '', // 非必填
        sex: '',  // gender
        nation: '',
        birthday: '', // bornDay
        address: '',  // certAddress
        idcard: '', // certNumber
        organ: '', // certOrg
        imgCode: '', // identityPic
        // effDate: '',
        // expDate: '',
        // result: ''
      },
      imageSrc: '',
      connectStatus: false, // 是否已经连接设备
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sex: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        nation: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        address: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        idcard: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        organ: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // this.init()
  },
  methods: {
    init () {
      this.btnAble = false
      this.visible = true
      this.connect()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.imageSrc = ''
      })
    },
    handleClose () {
      // this.disconnect()
      this.visible = false
      this.$emit('refreshDataList')
    },
    formatDate (str) {
      return str.substring(0,4) + '-' + str.substring(4,6) + '-' + str.substring(6,8)
    },
    // 获取信息
    connect () {
      axios.get(`http://127.0.0.1:19196/OpenDevice`).then(({ data: res }) => {
        if (res.resultFlag == 0) {
          // this.$message({
          //   message: res.errorMsg,
          //   type: 'success'
          // })
          this.connectStatus = true
        } else {
          this.$message.error(res.errorMsg)
        }
      }).catch(() => {
        this.$message.error('连接失败')
      })
    },
    readCard () {
      axios.get(`http://127.0.0.1:19196/readcard`).then(({ data: res }) => {
        if (res.resultFlag == 0) {
          // this.$message({
          //   message: res.errorMsg,
          //   type: 'success'
          // })
          if (!this.dataForm.idcard) {
            this.getMobileById(res.certNumber)
          }
          this.dataForm.name = res.partyName
          this.dataForm.sex = res.gender
          this.dataForm.nation = res.nation,
          this.dataForm.birthday = this.formatDate(res.bornDay)
          this.dataForm.address = res.certAddress
          this.dataForm.idcard = res.certNumber
          this.dataForm.organ = res.certOrg
          this.dataForm.imgCode = res.identityPic
          this.imageSrc = 'data:image/png;base64,' + this.dataForm.imgCode
          console.log('读卡成功', this.dataForm.idcard)
        } else {
          // this.$message.error(res.errorMsg)
          this.$refs['dataForm'].resetFields()
          this.imageSrc = ''
        }
      }).catch(() => {
        this.$message.error('读取失败')
      })
    },
    getSamid () {
      axios.get(`http://127.0.0.1:19196/getsamid`).then(({ data: res }) => {
        this.$message({
          message: '获取安全模块号成功',
          type: 'success'
        })
        this.visible = true
        this.dataForm.samid = res.samid
      }).catch(() => {
        this.$message.error('获取失败')
      })
    },
    disconnect () {
      axios.get(`http://127.0.0.1:19196/CloseDevice`).then(({ data: res }) => {
        if (res.resultFlag == 0) {
          this.$message(res.errorMsg)
          this.connectStatus = false
          this.btnAble = false
          this.visible = true
          this.$refs['dataForm'].resetFields()
          this.imageSrc = ''
        } else {
          this.$message.error(res.errorMsg)
        }
      }).catch(() => {
        this.$message.error('断开失败')
      })
    },
    getMobileById (idcard) {
        this.$http.get(`/custom/persontesting/v2/getMobileByIdCard?idcard=${idcard}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm.mobile = res.data || ''
        }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.btnAble = true
        this.$http.post('/custom/persontesting/v2/saveScanningInfo', this.dataForm).then(({ data: res }) => {
          this.btnAble = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              // this.visible = false
              this.$emit('refreshDataList')
              this.$refs['dataForm'].resetFields()
              this.imageSrc = ''
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
.el-form {
  position: relative;
}
.under-name {
  position: absolute;
  left: 0;
  top: 80px;
}
.el-form--inline .el-form-item {
  width: 48%;
}
.el-input {
  width: 240px;
}
.image-src {
  height: 126px;
  width: 102px;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
</style>
