<template>
  <el-dropdown style="margin: 0 10px" trigger="click" @command="beforeReadCard">
    <el-button type="primary">读卡<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item icon="el-icon-bank-card" command="sicard">社保卡</el-dropdown-item>
        <el-dropdown-item icon="el-icon-s-grid" command="qrcode">二维码</el-dropdown-item>
        <el-dropdown-item icon="el-icon-user" command="idcard">身份证</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <span class="readcard">
    <el-dialog v-model="showSelectBiztype" title="请选择读卡业务" width="300px">
      <el-radio-group v-model="currentBiztype">
        <el-radio label="01101">门诊挂号</el-radio>
        <el-radio label="01301">门诊结算</el-radio>
      </el-radio-group>
      <template #footer>
        <el-button type="primary" @click="handleConfirmBiztype">确定</el-button>
      </template>
    </el-dialog>
  </span>
</template>

<script>
import { readCardCallback } from '@/api/medical-insurance/si-inpatient'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  props: {
    patNo: {
      type: String,
      default: null,
    },
    biztype: {
      type: String,
      default: null,
    },
  },
  emits: ['success'],
  setup(props, ctx) {
    const showSelectBiztype = ref(false)
    const currentCardtype = ref(null)
    const currentBiztype = ref(null)
    const beforeReadCard = (cardtype) => {
      if (!props.patNo) {
        ElMessage({
          message: '请先选择患者',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      if (props.biztype) {
        executeReadCard(cardtype)
      } else {
        currentCardtype.value = cardtype
        showSelectBiztype.value = true
      }
    }

    const handleConfirmBiztype = () => {
      if (!currentBiztype.value) {
        ElMessage({
          message: '请选择读卡业务！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      showSelectBiztype.value = false
      executeReadCard(currentCardtype.value)
    }

    const executeReadCard = (cardtype) => {
      const nowbiztype = props.biztype || currentBiztype.value
      const param = `${cardtype}_${props.patNo}_${nowbiztype}`
      window.open(`ReadCard://${param}`, '_self')
      readCardCallback(param).then((res) => {
        const result = {
          mdtrtCertType: cardtype,
          readCardResult: res.data,
          readCardBizType: nowbiztype,
        }
        ctx.emit('success', result)
        ElMessageBox.alert(res.message, '提示', {
          type: 'success',
          showCancelButton: false,
        }).then(() => {})
      })
    }

    return {
      currentBiztype,
      showSelectBiztype,
      beforeReadCard,
      handleConfirmBiztype,
    }
  },
}
</script>
