<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 style="text-align: center;line-height: 50px;">
                <el-checkbox v-model="isYDpatint">是否异地(<span style="color: red;">患者有多个参保信息时选择</span>)</el-checkbox>
             </div>
           
            <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="刷卡中，请稍后" v-loading="jiezhiLoading" 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-button @click="getmzxx('2')"
                        style="color: #3d7ff5; width: 97px; font-size: 17px; font-weight: 600; border-radius: 8px">读卡</el-button> -->
                    
                </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'
import { mzxx, mzxxs,queryBasicInfo,queryReadRard,getInfoByQrCode } from '@/api/mz'
export default {
    components: {},
    props: {
        isOpenCarded: Boolean,
        physicalCardType: {
            type: String,
            default() {
                return ''
            },
        },
        patientcard:Object,
        visible: Boolean,
        flag: String,
        xzbz: String,
        patientData:Object,
        selectTableArr:Array
    },
    data() {
        return {
            isYDpatint:false,
            jiezhiLoading:false,
            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: [], // 患者卡类型
            shenfenzhenghao:'',
            insurance:'',

        }
    },
    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
                }
            },
        },
        patientData:{
            handler:function(nv,ov){
                if(nv){
                    this.shenfenzhenghao = nv.id_card
                    this.insurance = nv.insurance_type?.value || ''
                }
            },
            immediate:true,
            deep:true,
        }
    },
    created() {
        // 就诊卡类型
        // this.getDic('DiagnosisCardType', 'DiagnosisCardOptions')
    },
    mounted() {
        // 初始化websocket
        this.initWebSocket()
    },
    methods: {
        // 当不关闭刷卡弹窗的时候需要对input框失去焦点的时候继续聚焦
        handleSetFocus() {
            this.$nextTick(() => {
                this.$refs.cardInput.focus()
            })
        },
        // 关闭弹窗
        handleCloseModal() {
            this.$emit('close', 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() {
                this.jiezhiLoading=true
            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.getmzxx('3')
                // 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)
                this.jiezhiLoading=false
              
                  this.$message({
                        message: '不支持此方式结算',
                        type: 'error',
                    })
            } else if (this.form.physicalCard.toString().length === 8) {
                // 输入患者id
                this.form.physicalCardType = 'PATIENT_ID'
                // this.$emit('getyibaoinfo', this.form)
                this.jiezhiLoading=false
                
                  this.$message({
                        message: '不支持此方式结算',
                        type: 'error',
                    })
            } 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)

              this.param = {
                    qr_code: this.form.physicalCard
                }
                getInfoByQrCode(this.param)
                    .then(response => {
                        this.form.physicalCard=response.data.data.cardNo
                       
                           this.form.physicalCardType = 'ID_CARD'
                this.getmzxx('1')
                    })
                    .finally((err) => {
                      
                    })

                this.jiezhiLoading=false
                //   this.$message({
                //         message: '不支持此方式结算',
                //         type: 'error',
                //     })
            } else if (this.form.physicalCard.toString().length === 18) {
                // 就诊卡
                this.form.physicalCardType = 'ID_CARD'
                this.getmzxx('1')
                // this.$emit('getyibaoinfo', this.form)
            }else{
                this.jiezhiLoading=false
                  this.$message({
                        message: '不支持此方式结算',
                        type: 'error',
                    })
            }

            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) {
            console.log(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.getmzxx('1')
                    // 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 = 'ID_CARD'
                            if (data.RespData?.CardNo) {
                                // 社保卡多回传[识别码&姓名]字段---刘春 2023年4月23日15:58:00
                                this.form.ksbm = data.RespData.ksbm
                                this.form.xm = data.RespData.xm
                                this.form.p_sbm = data.RespData.ksbm

                                this.form.physicalCard = data.RespData.sfzh
                                this.form.idcard = data.RespData.CardNo
                            }
                        }
                    }
                    this.getmzxx('2')

                    // this.$emit('getyibaoinfo', this.form)
                    if (this.form.physicalCard) {
                        clearInterval(this.interval)
                        // this.handleEnterModal()
                        this.closedevice()
                        return true
                    }
                    return false
                }
            }
        },
        getmzxx(e) {
          // 身份证
          if (e == '1') {
                this.param = {
                    is_yd:this.isYDpatint==true?'1':'0',
                    id_card:this.form.physicalCard,
                    insurance:this.insurance,
                    cache:'1',
                    yltclb:this.selectTableArr[0].settle_type.is_mb?'4':'6',
                    xzbz:this.selectTableArr[0].settle_type.is_gs?'D':'C',
                    card_type:'02'
                }
                queryBasicInfo(this.param)
                    .then(response => {
                        this.jiezhiLoading=false
                        this.dialogFormVisible = false
                         this.$emit('getyibaoinfo', response.data,'02')
                         this.form.physicalCard=''
                    })
                    .finally((err) => {
                        this.jiezhiLoading=false
                        this.dialogFormVisible = false
                    })
            }
            // 2=社保卡
            if (e == '2') {
                this.param = {
                    // is_yd:this.isYDpatint==true?'1':'0',
                    // insurance:this.insurance,//this.insurance
                    // cache:'1',
                    // yltclb:this.selectTableArr[0].settle_type.is_mb?'4':'6',
                    // card_type:'03',
                    // qr_code:'',
                    // id_card:'370983199001091827',//,'370104202109020049'
                    // dzpzywm:'301',
                    // xzbz:this.selectTableArr[0].settle_type.is_gs?'D':'C',
                    // card_no:'A83459572', //,'A73079277'
                    // sbm:'370100D1560000050022A5F32E307E9E' , //,'370100D156000005006ACF514551621F'
                    // name: '王敏',//'刘楚潇'
                    is_yd:this.isYDpatint==true?'1':'0',
                    insurance:this.insurance,//this.insurance
                    cache:'1',
                    yltclb:this.selectTableArr[0].settle_type.is_mb?'4':'6',
                    card_type:'03',
                    qr_code:'',
                    id_card:this.form.physicalCard,//,'370104202109020049'
                    dzpzywm:'301',
                    xzbz:this.selectTableArr[0].settle_type.is_gs?'D':'C',
                    card_no: this.form.idcard, //,'A73079277'
                    sbm:this.form.p_sbm , //,'370100D156000005006ACF514551621F'
                    name: this.form.xm,//'刘楚潇'
                }
                queryReadRard(this.param)
                    .then(response => {
                        this.jiezhiLoading=false
                        this.dialogFormVisible = false
                        this.$emit('getyibaoinfo', response.data,'03')
                        this.form.physicalCard=''
                    })
                    .finally(() => {
                        this.jiezhiLoading=false
                        this.$emit('close')
                        this.dialogFormVisible = false
                    })
            }
            // 医保电子凭证
            if (e == '3') {
                this.param = {
                    is_yd:this.isYDpatint==true?'1':'0',
                    insurance:this.insurance,//this.insurance
                    cache:'1',
                    yltclb:this.selectTableArr[0].settle_type.is_mb?'4':'6',
                    card_type:'01',
                    id_card:this.patientData.id_card,
                    qr_code:this.form.physicalCard,
                    dzpzywm:'301',
                    xzbz:this.selectTableArr[0].settle_type.is_gs?'D':'C',
                    card_no:this.patientData.patient_id,
                    sbm:this.patientData.p_sbm,
                    name:this.patientData.name,
                }
                queryReadRard(this.param)
                    .then(response => {
                        this.jiezhiLoading=false
                        this.dialogFormVisible = false
                        this.$emit('getyibaoinfo', response.data,'01',this.adminpingzhengma)
                        this.form.physicalCard=''
                    })
                    .finally(() => {
                        this.jiezhiLoading=false
                        this.loading = 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>
