package com.example.chemical.ui.verify

import android.content.IntentFilter
import android.graphics.Bitmap
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityTwoVerificationBinding
import com.example.chemical.receiver.OnSerialScanListener
import com.example.chemical.receiver.PortScanHelper
import com.example.chemical.receiver.UsbReceiver
import com.example.chemical.ui.DoubleDialogBean
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.utils.*
import com.example.chemical.weidith.CustomDialog
import com.example.chemical.weidith.DoublePeopleDialog
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.lztek.toolkit.Lztek
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.UserValidationBean
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import com.rc.httpcore.vo.request.FaceCompareReq
import io.fotoapparat.Fotoapparat
import io.fotoapparat.facedetector.processor.FaceDetectorProcessor
import io.fotoapparat.log.fileLogger
import io.fotoapparat.log.logcat
import io.fotoapparat.log.loggers
import io.fotoapparat.selector.back
import io.fotoapparat.selector.front
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.HttpException
import java.io.File
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.text.SimpleDateFormat
import java.util.*


//双人认证 整合 可随意调整刷卡扫码人脸业务
class TwoVerificationActivity : BaseCountDownActivity<ActivityTwoVerificationBinding>() {
    //扫码需要的
    private var mLztek: Lztek? = null
    private var mDeviceNum: String? = null  //设备唯一标识
    private var currentDateTimeOne: String? = null
    private var currentDateTimeTwo: String? = null

    //人脸识别
    private lateinit var mFotoapparat: Fotoapparat

    //第二个人
    private lateinit var mFotoapparatTwo: Fotoapparat

    //刷卡
    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数

    private var count = 1   //认证次数
    private var mChemicalLevel: Int = 0      //管控类  ·型
    private var mTag = 0     //0  新增入库    1 归还废弃空瓶等   2 待入库  3 领用认证需要换api 需要判断不同权限 进行验证通过
    private var mVerTyps = 0  //认证方式
    private var mUserId: String? = null  //第二个人
    private var mDoorId: String? = null
    private val mDoubleDialogBean = mutableListOf<DoubleDialogBean>() //双人认证 需要显示的
    private val handlerUtil = HandlerUtil.getInstance()  //所有语音多次提示
    private val handlerBackTwo = Handler(Looper.getMainLooper())  //人脸识别认证
    private val mHandler = Handler(Looper.getMainLooper()) //扫码查询
    private var mCertificationType = 1  //1 人脸+刷卡  2 人脸+扫码  3  刷卡+扫码  4 人脸+刷卡+扫码
    private var mVerOne = 1  //第一位    1：人脸  2：刷卡 3：扫码
    private var mVerTwo = 1  //第二位    1：人脸  2：刷卡 3：扫码
    private var isLogin = false  //是否是登陆人
    private lateinit var dialogsAut: DoublePeopleDialog
    private var timeLeftInSeconds = 2
    private var mTvView: TextView? = null
    private val handlerBack = Handler(Looper.getMainLooper())
    private var mVoiceCount = 1  //认证次数
    private lateinit var timeUpdater: TimeUpdater

    override fun createViewBinding() =
        ActivityTwoVerificationBinding.inflate(LayoutInflater.from(this))

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        try {
            SharedPreferencesHelper.clearList(this)
        } catch (e: Exception) {

        }
        viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)
        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()

        mTag = intent.getIntExtra("mTag", 0)
        mVerTyps = intent.getIntExtra("mVerTyps", 0)   //只有某一个认证方法 1：人脸  2：刷卡 3：扫码
        mDoorId = intent.getStringExtra("doorId")  //柜子id
        mChemicalLevel = intent.getIntExtra("chemicalLevel", 0)
        mCertificationType = intent.getIntExtra("hides", 0)  //组合类型


        //扫码数据初始化
        mLztek = Lztek.create(this)
        val toUpperCase = mLztek!!.ethMac.toUpperCase()
        mDeviceNum = toUpperCase.replace(":", "")
        currentDateTimeOne = TimesUils.getCurrentDateTime()
        Thread.sleep(10)
        currentDateTimeTwo = TimesUils.getCurrentDateTime()
        var cont =
            HttpConfig.API_BASE_QC_URL + "?doorId=${mDoorId}&subId=${ChemicalApp.subjectId!!}&type=12&macId=${mDeviceNum}&code=${currentDateTimeOne}" // 要生成二维码的文本内容
        loadQRCodeIntoImageView(cont, 100, 100, viewBinding.imgOne)
        var tow =
            HttpConfig.API_BASE_QC_URL + "?doorId=${mDoorId}&subId=${ChemicalApp.subjectId!!}&type=12&macId=${mDeviceNum}&code=${currentDateTimeTwo}" // 要生成二维码的文本内容
        loadQRCodeIntoImageView(tow, 100, 100, viewBinding.imgRoa)
        opCards()
        mHandleScanEvent = true

        if (mVerTyps == 0) {
            RcLog.info("======当前认证方式$mTag")
            //初始化UI
            when (mCertificationType) {
                1 -> { //人脸+刷卡
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    viewBinding.scan.visibility = View.GONE
                    viewBinding.scanTwo.visibility = View.GONE
                    fotoapparatOpen()
                    handlerBackTwo.post(countdownRunnableTwo)
                }

                2 -> {//人脸+扫码
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    viewBinding.campus.visibility = View.GONE
                    viewBinding.campusTwo.visibility = View.GONE
                    fotoapparatOpen()
                    handlerBackTwo.post(countdownRunnableTwo)
                }

                3 -> {//刷卡+扫码
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiwei_shua_ka_renzheng)
                    mHandleScanEvent = false
                    mVerOne = 2
                    mVerTwo = 2
                    viewBinding.viewFace.visibility = View.GONE
                    viewBinding.tvMsgRob.visibility = View.GONE
                    viewBinding.viewCard.visibility = View.VISIBLE

                    viewBinding.viewFaceRoa.visibility = View.GONE
                    viewBinding.tvMsgRod.visibility = View.GONE
                    viewBinding.viewCardRoa.visibility = View.VISIBLE

                    viewBinding.campus.visibility = View.GONE
                    viewBinding.campusTwo.visibility = View.GONE

                    viewBinding.tvMsg.text = "请 第 一 位 刷 卡 验 证"
                    viewBinding.tvMsgRoe.text = "请 第 二 位 刷 卡 验 证"
                    viewBinding.tvMsgRoa.text = "请在刷卡区域进行刷卡验证"
                    viewBinding.tvMsgRoc.text = "请在刷卡区域进行刷卡验证"
                }

                4 -> {
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    replaceOnes()
                    replaceTwos()
                    fotoapparatOpen()
                    handlerBackTwo.post(countdownRunnableTwo)
                }
            }

        } else {
            RcLog.info("======当前认证方式$mTag")
            when (mVerTyps) {
                1 -> {
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    //只有人脸
                    viewGones()
                    fotoapparatOpen()
                    handlerBackTwo.post(countdownRunnableTwo)
                }

                2 -> {
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiwei_shua_ka_renzheng)
                    mHandleScanEvent = false
                    mVerOne = 2
                    mVerTwo = 2
                    //只有刷卡
                    viewBinding.tvMsg.text = "请 第 一 位 刷 卡 验 证"
                    viewBinding.tvMsgRoa.text = "请在刷卡区域进行刷卡验证"
                    viewBinding.tvMsgRob.visibility = View.GONE  //描述
                    viewBinding.viewCard.visibility = View.VISIBLE

                    viewBinding.tvMsgRoe.text = "请 第 二 位 刷 卡 验 证"
                    viewBinding.tvMsgRoc.text = "请在刷卡区域进行刷卡验证"
                    viewBinding.tvMsgRod.visibility = View.GONE
                    viewBinding.viewCardRoa.visibility = View.VISIBLE

                    viewGones()
                    viewBinding.viewFace.visibility = View.GONE
                    viewBinding.viewFaceRoa.visibility = View.GONE

                }

                3 -> {
                    MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_saoma)
                    mVerOne = 3
                    mVerTwo = 3
                    //只有扫码
                    viewBinding.tvMsg.text = "请 第 一 位 扫 码 验 证"
                    viewBinding.tvMsgRoa.text = "请打开微信扫描屏幕二维码"
                    viewBinding.tvMsgRob.text = "进行扫码验证"
                    viewBinding.viewScan.visibility = View.VISIBLE

                    viewBinding.tvMsgRoe.text = "请 第 二 位 扫 码 验 证"
                    viewBinding.tvMsgRoc.text = "请打开微信扫描屏幕二维码"
                    viewBinding.tvMsgRod.text = "进行扫码验证"
                    viewBinding.viewFace.visibility = View.GONE
                    viewBinding.viewFaceRoa.visibility = View.GONE
                    viewBinding.viewScanRoa.visibility = View.VISIBLE
                    viewGones()
                    // 在3秒后执行延迟任务
                    mHandler.postDelayed(delayedTask, 4000)
                }
            }
        }


        replaceOnes()
        replaceTwos()
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }
        handlerUtil.startTask(task, 10000)
    }


    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun cdTime(cd: Int) {
        viewBinding.tvReturn.text = "返回${cd}s"
    }

    //语音提示
    private val task = Runnable {
        if (mVoiceCount == 6) {
            finish()
        }
        if (count == 1) {
            if (mVerTyps == 0) {
                //第二个人的操作
                when (mVerOne) {
                    1 -> {
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    }

                    2 -> { //刷卡
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiwei_shua_ka_renzheng)
                    }

                    3 -> {//扫码
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_saoma)
                    }
                }
            } else {
                //只有一种认证方式
                RcLog.info("======当前认证方式$mTag")
                when (mVerTyps) {
                    1 -> {
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_renlianshibie)
                    }

                    2 -> {
                        //只有刷卡
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiwei_shua_ka_renzheng)
                    }

                    3 -> {
                        //只有扫码
                        MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_saoma)
                    }
                }
            }
        } else {
            if (mVerTyps == 0) {
                //第二个人的操作
                when (mVerTwo) {
                    1 -> { //关闭人脸
                        MediaPlayerHelper.playRawMp3(this, R.raw.dierwei_renlianshibie)
                    }

                    2 -> { //刷卡
                        MediaPlayerHelper.playRawMp3(this, R.raw.dierweishuakarenzheng)
                    }

                    3 -> {//扫码
                        MediaPlayerHelper.playRawMp3(this, R.raw.dierren_saoma)
                    }
                }
            } else {
                //只有一种认证方式
                RcLog.info("======当前认证方式$mTag")
                when (mVerTyps) {
                    1 -> {
                        MediaPlayerHelper.playRawMp3(this, R.raw.dierwei_renlianshibie)
                    }

                    2 -> {
                        //只有刷卡
                        MediaPlayerHelper.playRawMp3(this, R.raw.dierweishuakarenzheng)
                    }

                    3 -> {
                        //只有扫码
                        MediaPlayerHelper.playRawMp3(this, R.raw.shuangren_tongguo)
                    }
                }
            }
        }

        mVoiceCount++

    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            mPortScanHelper.onPause()
        } catch (e: Exception) {
        }
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
        //关闭语音播报
        try {
            handlerUtil.removeCallbacks(task)
            handlerUtil.stopAllTasks()
        } catch (e: Exception) {

        }


        // 停止定时更新
        try {
            mFotoapparat.stop()
        } catch (e: Exception) {
        }

        try {
            mFotoapparatTwo.stop()
        } catch (e: Exception) {
        }

        try {
            handlerBackTwo.removeCallbacks(countdownRunnableTwo)
            handlerBackTwo.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

        try {
            handlerBack.removeCallbacks(countdownRunnable)
            handlerBack.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

        try {
            EventBus.getDefault().unregister(this) //关闭广播
            unregisterReceiver(mUsbReceiver)
        } catch (e: Exception) {
        }

        try {
            mHandler.removeCallbacks(delayedTask)
            mHandler.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

    }

    private fun viewGones() {
        viewBinding.lint.visibility = View.GONE
        viewBinding.lintTwo.visibility = View.GONE
    }

    private val countdownRunnableTwo = object : Runnable {
        override fun run() {
            RcLog.info("=======双人人脸认证中")
            takePicture()
            handlerBackTwo.postDelayed(this, 4500)
        }
    }

    //验证通过
    private fun passThrough() {
        //关闭语音播报
        try {
            handlerUtil.removeCallbacks(task)
            handlerUtil.stopAllTasks()
        } catch (e: Exception) {

        }

        //
        try {
            mHandler.removeCallbacks(delayedTask)
            mHandler.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

        // 在需要时关闭定时器
        try {
            RcLog.info("=====清空双人认证3 人脸信息")
            mFotoapparatTwo.stop()
            handlerBackTwo.removeCallbacks(countdownRunnableTwo)
            RcLog.info("=====清空双人认证4 人脸信息")
            handlerBackTwo.removeCallbacksAndMessages(null)
        } catch (e: Exception) {

        }



        Constants.AUTHENTICATION = true
        // 存储集合到 SharedPreferences

        SharedPreferencesHelper.saveList(this, mDoubleDialogBean)
        dialogsAut =
            DoublePeopleDialog(this, mDoubleDialogBean, object : DoublePeopleDialog.IClickLit {
                override fun onUpView(tvView: TextView) {
                    mTvView = tvView
                }
            })
        dialogsAut.show()
        // 开始倒计时
        handlerBack.post(countdownRunnable)
        // 获取对话框的 Window 对象
        dialogsAut?.window?.decorView?.setOnTouchListener { _, event ->
            // 判断是否点击了对话框外部空白区域
            if (event.action == MotionEvent.ACTION_DOWN) {
                val x = event.x
                val y = event.y
                val dialogView = dialogsAut?.window?.decorView
                if (dialogView != null && (x < 0 || x > dialogView.width || y < 0 || y > dialogView.height)) {
                    // 在此处执行点击对话框外部空白区域时的操作
                    // 例如关闭对话框
                    dialogsAut.dismiss()
                    finish()
                    return@setOnTouchListener true
                }
            }
            return@setOnTouchListener false
        }
        MediaPlayerHelper.playRawMp3(this, R.raw.shuangren_tongguo)
    }

    private val countdownRunnable = object : Runnable {
        override fun run() {
            if (timeLeftInSeconds > 0) {
                mTvView!!.text = "${timeLeftInSeconds}秒后自动返回首页"
                timeLeftInSeconds--
                handlerBack.postDelayed(this, 1000)
            } else {
                dialogsAut!!.dismiss()
                finish()
            }
        }
    }

    private fun callFaceMatchingApi(
        featureData: File,
    ) {
        showLoading("认证中....")
        val param = FaceCompareReq().apply {
            data = null
            subId = ChemicalApp.subjectId
            doorId = mDoorId
        }
        val disposable = ApiRepository.checkUserFaceByPic(featureData, param)
            .subscribe({ data ->
                dismissLoading()
                if (count == 1) {
                    mUserId = data.userId
                    RcLog.info("第a一个人 $mUserId    ${data.userId}")
                } else {
                    if (mUserId.equals(data.userId) && count == 2) {
                        customDialogView(0, "不能是同一个人")
                        return@subscribe
                    }
                }
                //0  新增入库    1 领用归还废弃空瓶等   2 待入库   需要判断不同权限 进行验证通过
                when (mTag) {
                    0 -> {
                        //新增入库
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                isLogin = true
//                                    faceTwo()
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        customDialog()
//                                            faceTwo()
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
//                                            faceTwo()
                                        customDialog()
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            }
                        } else {
                            if (isLogin) {
                                //已经有登陆人
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    customDialogView(0, "无权限信息")
                                }
                            }
                        }
                    }

                    1 -> { //归还业务  标签管理
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                isLogin = true
//                                    faceTwo()
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                obtainCertification(data)
                            }
                        } else {
                            if (isLogin) {
                                if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                    var bean =
                                        DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    customDialogView(0, "认证失败")
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }

                    2 -> {//待入库
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                isLogin = true
//                                    faceTwo()
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                toBeStored(data)
                            }
                        } else {
                            if (isLogin) {
                                if (mChemicalLevel == 1) {
                                    //管控
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                } else {
                                    //非管控  实验室负责人or安全负责人or柜锁管理员
                                    if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }
                }

            },
                { throwable ->
                    dismissLoading()
//                mFotoapparat.stop()
//                handlerBack.removeCallbacks(countdownRunnable)
//                handlerBack.removeCallbacksAndMessages(null)
                    throwableView(throwable)
                })
        addDisposable(disposable)
    }


    private fun obtainCertification(data: UserValidationBean) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {

//            faceTwo()
            customDialog()
            var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
            mDoubleDialogBean.add(bean)
        } else {
            customDialogView(0, "认证失败")
        }
    }

    private fun toBeStored(data: UserValidationBean) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (mChemicalLevel == 1) {
            //管控
            if (data.belongUser == true || data.toipcUser == true || data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                customDialog()
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                customDialogView(0, "认证失败")
            }
        } else {
            //非管控  实验室负责人or安全负责人or柜锁管理员
            if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                customDialog()
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                customDialogView(0, "认证失败")
            }
        }
    }

    // 1 人脸验证通过的   2 刷卡认证通过的 3扫码认证通过的
    private fun customDialog() {
        count++
        //第二个人的操作a
        viewBinding.rlView.visibility = View.GONE
        viewBinding.rlResult.visibility = View.VISIBLE

        if (mVerTyps == 0) {
            //当前组合认证 第二个人
            RcLog.info("======当前认证方式$mTag")

            //第二个人的操作
            when (mVerTwo) {
                1 -> { //关闭人脸
                    MediaPlayerHelper.playRawMp3(this, R.raw.dierwei_renlianshibie)
                    viewBinding.imgFace.visibility = View.GONE
                    try {
                        mFotoapparat.stop()
                    } catch (e: Exception) {

                    }

                    if (::mFotoapparatTwo.isInitialized) {
                        mFotoapparatTwo.stop()
                        mFotoapparatTwo.start()
                    } else {
                        mFotoapparatTwo = Fotoapparat.with(this)
                            .into(viewBinding.cameraViewTwo)
                            .lensPosition(
                                if (Constants.FACE_TAG == 0) {
                                    front()
                                } else {
                                    back()
                                }
                            )//front（）前置  back 后置
                            .frameProcessor(
                                FaceDetectorProcessor.with(this)
                                    .listener { faces ->
                                        viewBinding.rectanglesViewTwo.setRectangles(faces)
                                    }.build()
                            )
                            .logger(loggers(logcat(), fileLogger(this)))
                            .build()
                        mFotoapparatTwo.stop()
                        mFotoapparatTwo.start()
                    }

                    //人脸
                    when (mVerOne) {

                        2 -> {
                            //关闭刷卡  打开第二个人脸线程
                            mHandleScanEvent = true
                            handlerBackTwo.post(countdownRunnableTwo)
                        }

                        3 -> {
                            //关闭扫码  打开第二个人脸线程
                            try {
                                mHandler.removeCallbacks(delayedTask)
                                mHandler.removeCallbacksAndMessages(null)
                            } catch (e: Exception) {
                            }

                            handlerBackTwo.post(countdownRunnableTwo)
                        }
                    }

                }

                2 -> { //刷卡
                    MediaPlayerHelper.playRawMp3(this, R.raw.dierweishuakarenzheng)
                    mHandleScanEvent = false
                    when (mVerOne) {
                        1 -> {
                            //关闭人脸
                            try {
                                mFotoapparat.stop()
                            } catch (e: Exception) {

                            }

                            try {
                                handlerBackTwo.removeCallbacks(countdownRunnableTwo)
                            } catch (e: Exception) {
                            }
                            try {
                                handlerBackTwo.removeCallbacksAndMessages(null)
                            } catch (e: Exception) {
                            }
//                            opCards()

                        }

                        2 -> {
                            RcLog.info("======第一位是刷卡  $mHandleScanEvent")
                        }

                        3 -> {
                            //关闭扫码
                            try {
                                mHandler.removeCallbacks(delayedTask)
                                mHandler.removeCallbacksAndMessages(null)
                            } catch (e: Exception) {
                            }
                        }
                    }


                }

                3 -> {//扫码
                    viewBinding.viewScanRoa.visibility = View.VISIBLE
                    viewBinding.imgRoa.visibility = View.VISIBLE
                    MediaPlayerHelper.playRawMp3(this, R.raw.dierren_saoma)
                    mHandleScanEvent = true
                    when (mVerOne) {
                        1 -> {
                            //关闭人脸
                            if (::mFotoapparatTwo.isInitialized) {
                                // mFotoapparat 已经被初始化
                                mFotoapparatTwo.stop()
                                try {
                                    handlerBackTwo.removeCallbacks(countdownRunnableTwo)
                                    handlerBackTwo.removeCallbacksAndMessages(null)
                                } catch (e: Exception) {
                                }
                            }
                            try {
                                mHandler.removeCallbacks(delayedTask)
                                mHandler.removeCallbacksAndMessages(null)
                            } catch (e: Exception) {
                            }
                            mHandler.postDelayed(delayedTask, 4000)
                        }

                        2 -> {//刷卡
                            try {
                                mHandler.removeCallbacks(delayedTask)
                                mHandler.removeCallbacksAndMessages(null)
                            } catch (e: Exception) {
                            }
                            mHandler.postDelayed(delayedTask, 4000)
                        }

                        3 -> {
                            //扫码  不需要操作
                            //关闭人脸
                            if (::mFotoapparatTwo.isInitialized) {
                                // mFotoapparat 已经被初始化
                                mFotoapparatTwo.stop()
                                try {
                                    handlerBackTwo.removeCallbacks(countdownRunnableTwo)
                                    handlerBackTwo.removeCallbacksAndMessages(null)
                                } catch (e: Exception) {
                                }
                            }
                        }
                    }


                }
            }
        } else {
            //只有一种认证方式
            RcLog.info("======当前认证方式$mTag")
            when (mVerTyps) {
                1 -> {
                    MediaPlayerHelper.playRawMp3(this, R.raw.dierwei_renlianshibie)
                    viewBinding.imgFace.visibility = View.GONE
                    //只有人脸
                    try {
                        mFotoapparat.stop()
                    } catch (e: Exception) {

                    }

                    if (::mFotoapparatTwo.isInitialized) {
                        mFotoapparatTwo.stop()
                        mFotoapparatTwo.start()
                    } else {
                        mFotoapparatTwo = Fotoapparat.with(this)
                            .into(viewBinding.cameraViewTwo)
                            .lensPosition(
                                if (Constants.FACE_TAG == 0) {
                                    front()
                                } else {
                                    back()
                                }
                            )//front（）前置  back 后置
                            .frameProcessor(
                                FaceDetectorProcessor.with(this)
                                    .listener { faces ->
                                        viewBinding.rectanglesViewTwo.setRectangles(faces)
                                    }.build()
                            )
                            .logger(loggers(logcat(), fileLogger(this)))
                            .build()
                        mFotoapparatTwo.stop()
                        mFotoapparatTwo.start()
                    }
                    handlerBackTwo.post(countdownRunnableTwo)
                }

                2 -> {
                    //只有刷卡
                    MediaPlayerHelper.playRawMp3(this, R.raw.dierweishuakarenzheng)
                    mHandleScanEvent = false
                }

                3 -> {
                    //只有扫码
                    MediaPlayerHelper.playRawMp3(this, R.raw.shuangren_tongguo)
                }
            }
        }

    }


    private fun takePicture() {
        val format = SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault())
        val fileName = "${format.format(Calendar.getInstance().time)}.jpg"
        val photoFile = File(this.getExternalFilesDir("photos"), fileName)
        RcLog.info("==========当前认证数 $count")
        if (count == 1) {
            mFotoapparat.takePicture()
                .saveToFile(photoFile)
                .whenAvailable {
                    RcLog.info("=====人脸识别D=${HttpClient.token} $it $photoFile")
                    callFaceMatchingApi(photoFile)
                }

        } else {
            if (::mFotoapparatTwo.isInitialized) {
                mFotoapparatTwo.takePicture()
                    .saveToFile(photoFile)
                    .whenAvailable {
                        RcLog.info("=====人脸识别B=${HttpClient.token}")
                        callFaceMatchingApi(photoFile)
                    }
            } else {
                showToast("第二个人脸初始化失败")
            }

        }

    }

    private fun fotoapparatOpen() {

        mFotoapparat = Fotoapparat.with(this)
            .into(viewBinding.cameraView)
            .lensPosition(
                if (Constants.FACE_TAG == 0) {
                    front()
                } else {
                    back()
                }
            )//front（）前置  back 后置
            .frameProcessor(
                FaceDetectorProcessor.with(this)
                    .listener { faces ->
                        RcLog.info("=========认证中")
                        viewBinding.rectanglesView.setRectangles(faces)
                    }.build()
            )
            .logger(loggers(logcat(), fileLogger(this)))
            .build()
        mFotoapparat.stop()
        mFotoapparat.start()

    }

    //关闭人脸，扫码，线程
    private fun closeOneMission() {
        try {
            mHandler.removeCallbacks(delayedTask)
            mHandler.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

        try {
            handlerBackTwo.removeCallbacks(countdownRunnableTwo)
            handlerBackTwo.removeCallbacksAndMessages(null)
            mFotoapparat.stop()
        } catch (e: Exception) {
        }

    }

    private fun replaceOnes() {
        //第一个人 人脸
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.face, 1000L) {
            mUIDelegate.clearDisposable()
            mVerOne = 1
            closeOneMission()
            mFotoapparat.stop()
            mFotoapparat.start()
            handlerBackTwo.post(countdownRunnableTwo)
            viewBinding.tvMsg.text = "请 第 一 位 人 脸 验 证"
            viewBinding.tvMsgRoa.text = "请正对屏幕并使脸位于取景框内"
            viewBinding.tvMsgRob.visibility = View.VISIBLE
            viewBinding.tvMsgRob.text = "请保持光线充足，避免光照过强或过弱"
            viewBinding.viewFace.visibility = View.VISIBLE
            viewBinding.face.visibility = View.GONE

            if (viewBinding.viewCard.visibility == View.VISIBLE) {
                viewBinding.viewCard.visibility = View.GONE
                viewBinding.campus.visibility = View.VISIBLE
            }

            if (viewBinding.viewScan.visibility == View.VISIBLE) {
                viewBinding.viewScan.visibility = View.GONE
                viewBinding.scan.visibility = View.VISIBLE
            }
        }

        //刷卡
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.campus, 1000L) {
            mUIDelegate.clearDisposable()
            mVerOne = 2
            closeOneMission()
            mHandleScanEvent = false
            viewBinding.tvMsg.text = "请 第 一 位 刷 卡 验 证"
            viewBinding.tvMsgRoa.text = "请在刷卡区域进行刷卡验证"
            viewBinding.tvMsgRob.visibility = View.GONE  //描述
            viewBinding.viewCard.visibility = View.VISIBLE
            viewBinding.campus.visibility = View.GONE

            if (viewBinding.viewFace.visibility == View.VISIBLE) {
                viewBinding.viewFace.visibility = View.GONE
                viewBinding.face.visibility = View.VISIBLE
            }


            if (viewBinding.viewScan.visibility == View.VISIBLE) {
                viewBinding.viewScan.visibility = View.GONE
                viewBinding.scan.visibility = View.VISIBLE
            }
        }

        //扫码
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.scan, 1000L) {
            mUIDelegate.clearDisposable()
            closeOneMission()
            mHandleScanEvent = true
            mVerOne = 3
            viewBinding.tvMsg.text = "请 第 一 位 扫 码 验 证"
            viewBinding.tvMsgRoa.text = "请打开微信扫描屏幕二维码"
            viewBinding.tvMsgRob.text = "进行扫码验证"
            viewBinding.viewScan.visibility = View.VISIBLE
            viewBinding.scan.visibility = View.GONE

            if (viewBinding.viewFace.visibility == View.VISIBLE) {
                viewBinding.viewFace.visibility = View.GONE
                viewBinding.face.visibility = View.VISIBLE
            }

            if (viewBinding.viewCard.visibility == View.VISIBLE) {
                viewBinding.viewCard.visibility = View.GONE
                viewBinding.campus.visibility = View.VISIBLE
            }
            mHandler.postDelayed(delayedTask, 4000)
        }
    }


    private fun replaceTwos() {

        //第二个人 人脸
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.faceRoa, 1000L) {
            mHandleScanEvent = true
            mVerTwo = 1
            viewBinding.tvMsgRoe.text = "请 第 二 位 人 脸 验 证"
            viewBinding.tvMsgRoc.text = "请正对屏幕并使脸位于取景框内"
            viewBinding.tvMsgRod.visibility = View.VISIBLE
            viewBinding.tvMsgRod.text = "请保持光线充足，避免光照过强或过弱"
            viewBinding.viewFaceRoa.visibility = View.VISIBLE
            viewBinding.faceRoa.visibility = View.GONE

            if (viewBinding.viewCardRoa.visibility == View.VISIBLE) {
                viewBinding.viewCardRoa.visibility = View.GONE
                viewBinding.campusTwo.visibility = View.VISIBLE
            }

            if (viewBinding.viewScanRoa.visibility == View.VISIBLE) {
                viewBinding.viewScanRoa.visibility = View.GONE
                viewBinding.scanTwo.visibility = View.VISIBLE
            }
            if (count == 2) {

                try {
                    mHandler.removeCallbacks(delayedTask)
                    mHandler.removeCallbacksAndMessages(null)
                } catch (e: Exception) {

                }
                viewBinding.imgFace.visibility = View.GONE
                //正在进行第二个人 认证
                if (::mFotoapparatTwo.isInitialized) {
                    // mFotoapparat 已经被初始化
                    mFotoapparatTwo.stop()
                    mFotoapparatTwo.start()
                    handlerBackTwo.post(countdownRunnableTwo)
                } else {
                    // mFotoapparat 还没有被初始化
                    mFotoapparatTwo = Fotoapparat.with(this)
                        .into(viewBinding.cameraViewTwo)
                        .lensPosition(
                            if (Constants.FACE_TAG == 0) {
                                front()
                            } else {
                                back()
                            }
                        )//front（）前置  back 后置
                        .frameProcessor(
                            FaceDetectorProcessor.with(this)
                                .listener { faces ->
                                    viewBinding.rectanglesViewTwo.setRectangles(faces)
                                }.build()
                        )
                        .logger(loggers(logcat(), fileLogger(this)))
                        .build()
                    mFotoapparatTwo.stop()
                    mFotoapparatTwo.start()
                    handlerBackTwo.post(countdownRunnableTwo)
                }

            } else {
                if (mVerOne == 2) {
                    mHandleScanEvent = false
                } else {
                    mHandleScanEvent = true
                }
            }
        }

        //刷卡
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.campusTwo, 1000L) {
            mVerTwo = 2
            RcLog.info("=======当前刷卡====$count")
            if (count == 2) {
                if (::mFotoapparatTwo.isInitialized) {
                    RcLog.info("=======当前刷卡A====$count")
                    try {
                        mFotoapparatTwo.stop()
                    } catch (e: Exception) {
                    }
                    try {
                        handlerBackTwo.removeCallbacks(countdownRunnableTwo)
                        handlerBackTwo.removeCallbacksAndMessages(null)
                    } catch (e: Exception) {

                    }
                } else {
                    RcLog.info("=======当前刷卡B====$count")
                }
                try {
                    mHandler.removeCallbacks(delayedTask)
                    mHandler.removeCallbacksAndMessages(null)
                } catch (e: Exception) {
                }
                mHandleScanEvent = false
            } else {
                if (mVerOne == 2) {
                    mHandleScanEvent = false
                } else {
                    mHandleScanEvent = true
                }
            }

            viewBinding.tvMsgRoe.text = "请 第 二 位 刷 卡 验 证"
            viewBinding.tvMsgRoc.text = "请在刷卡区域进行刷卡验证"
            viewBinding.tvMsgRod.visibility = View.GONE  //描述
            viewBinding.viewCardRoa.visibility = View.VISIBLE
            viewBinding.campusTwo.visibility = View.GONE

            if (viewBinding.viewFaceRoa.visibility == View.VISIBLE) {
                viewBinding.viewFaceRoa.visibility = View.GONE
                viewBinding.faceRoa.visibility = View.VISIBLE
            }


            if (viewBinding.viewScanRoa.visibility == View.VISIBLE) {
                viewBinding.viewScanRoa.visibility = View.GONE
                viewBinding.scanTwo.visibility = View.VISIBLE
            }
        }

        //扫码
        TextViewDebouncer.setDebouncedOnClickListener(viewBinding.scanTwo, 1000L) {
//            closeFace(4)

            mVerTwo = 3
            viewBinding.tvMsgRoe.text = "请 第 二 位 扫 码 验 证"
            viewBinding.tvMsgRoc.text = "请打开微信扫描屏幕二维码"
            viewBinding.tvMsgRod.text = "进行扫码验证"
            if (count == 2) {
                viewBinding.viewScanRoa.visibility = View.VISIBLE
                viewBinding.imgRoa.visibility = View.VISIBLE
                viewBinding.scanTwo.visibility = View.GONE
                if (viewBinding.viewFaceRoa.visibility == View.VISIBLE) {
                    viewBinding.viewFaceRoa.visibility = View.GONE
                    viewBinding.faceRoa.visibility = View.VISIBLE
                }
                if (::mFotoapparatTwo.isInitialized) {
                    try {
                        mFotoapparatTwo.stop()
                    } catch (e: Exception) {
                    }
                    try {
                        handlerBackTwo.removeCallbacks(countdownRunnableTwo)
                        handlerBackTwo.removeCallbacksAndMessages(null)
                    } catch (e: Exception) {

                    }
                }
                try {
                    mHandler.removeCallbacks(delayedTask)
                    mHandler.removeCallbacksAndMessages(null)
                } catch (e: Exception) {
                }

                mHandler.postDelayed(delayedTask, 4000)
            } else {
                if (mVerOne == 2) {
                    mHandleScanEvent = false
                } else {
                    mHandleScanEvent = true
                }
                viewBinding.viewScanRoa.visibility = View.VISIBLE
                viewBinding.scanTwo.visibility = View.GONE
                if (viewBinding.viewFaceRoa.visibility == View.VISIBLE) {
                    viewBinding.viewFaceRoa.visibility = View.GONE
                    viewBinding.faceRoa.visibility = View.VISIBLE
                }
            }


            if (viewBinding.viewCardRoa.visibility == View.VISIBLE) {
                viewBinding.viewCardRoa.visibility = View.GONE
                viewBinding.campusTwo.visibility = View.VISIBLE
            }

        }
    }


    //========================刷卡认证=================================

    //调用刷卡信息
    private fun handleScanEvent(cont: String) {
        //只有 0  1    1代表 已经需要第二次进行验证
        showLoading("验证中...")
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["cardNum"] = "$cont"
        mutableMap["subId"] = "${ChemicalApp.subjectId}"
        mutableMap["doorId"] = "$mDoorId"
        val disposable = ApiRepository.useCardVerify(mutableMap)
            .subscribe({ data ->
                dismissLoading()
                if (count == 1) {
                    mUserId = data.userId
                    RcLog.info("第a一个人 $mUserId    ${data.userId}")
                } else {
                    RcLog.info("第b一个人 $mUserId    ${data.userId}")
                    if (mUserId.equals(data.userId) && count == 2) {
                        customDialogView(0, "不能是同一人")
                        mHandleScanEvent = false
                        return@subscribe
                    }
                }

                //0  新增入库    1 领用归还废弃空瓶等   2 待入库   需要判断不同权限 进行验证通过
                when (mTag) {
                    0 -> {
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        mHandleScanEvent = false
                                        customDialog()
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        mHandleScanEvent = false
                                        customDialog()
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)

                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                }

                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                //已经有登陆人
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "无权限信息")
                                }
                            }
                        }

                    }

                    1 -> { //归还业务  标签管理
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                obtainCertification(data)
                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }

                    2 -> {//待入库
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog()
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                toBeStored(data)
                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                if (mChemicalLevel == 1) {
                                    //管控
                                    if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "认证失败")
                                    }
                                } else {
                                    //非管控  实验室负责人or安全负责人or柜锁管理员
                                    if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }
                }
            }, { throwable ->
                dismissLoading()
//                showNetError(throwable)
                mHandleScanEvent = false
                throwableView(throwable)
            })
        addDisposable(disposable)

    }

    //停止 销毁广播传递
    override fun onPause() {
        mPortScanHelper.onPause()
        super.onPause()
    }

    //必须写这个方法  防止注册失败
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUpdateEventEvent(event: KeyEvent) {

    }

    //获取刷卡信息
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        mPortScanHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

    private fun opCards() {
        EventBus.getDefault().register(this)
        mPortScanHelper.onResume()
        registerUsbBroadcast()
    }

    //刷卡usb链接
    private fun registerUsbBroadcast() {
        if (null == mUsbReceiver) {
            val filter = IntentFilter().apply {
                addAction(UsbReceiver.ACTION_USB_PERMISSION)
                addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
                addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
                addAction(UsbReceiver.ACTION_USB_STATE) // usb连接状态广播
            }
            mUsbReceiver = UsbReceiver()
            registerReceiver(mUsbReceiver, filter)
        }
    }

    private val mPortScanHelper by lazy {
        PortScanHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (!mHandleScanEvent) {
                    if (content.isNotBlank()) {
                        mHandleScanEvent = true
                        handleScanEvent(content)
                    }
                }
            }

        })
    }

    //========================扫码认证=================================


    private fun obtainCertification(data: UserValidationBean, macId: String) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
            scanLogin(macId)
            customDialog()
            var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
            mDoubleDialogBean.add(bean)
        } else {
            customDialogView(0, "认证失败")
        }
    }

    private fun toBeStored(data: UserValidationBean, macId: String) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (mChemicalLevel == 1) {
            //管控
//            if (data.belongUser == true || data.toipcUser == true || data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
            if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                scanLogin(macId)
                customDialog()
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                customDialogView(0, "认证失败")
            }
        } else {
            //非管控  实验室负责人or安全负责人or柜锁管理员
            if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                scanLogin(macId)
                customDialog()
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                customDialogView(0, "认证失败")
            }
        }
    }

    private fun scanLogin(macId: String) {
        if (count == 2) {
            currentDateTimeOne = currentDateTimeTwo
        }
        showLoading("查询中...")
        val disposable =
            ApiRepository.aioScanLogin(ChemicalApp.subjectId!!, mDoorId!!, currentDateTimeOne!!)
                .subscribe({ data ->
                    dismissLoading()
                    if (count == 1) {
                        mUserId = data.userId
                        RcLog.info("第a一个人 $mUserId    ${data.userId}")
                    } else {
                        if (mUserId.equals(data.userId) && count == 2) {
                            customDialogView(0, "不能是同一个人")
                            return@subscribe
                        }
                    }

                    //0  新增入库    1 领用归还废弃空瓶等   2 待入库   需要判断不同权限 进行验证通过
                    when (mTag) {
                        0 -> {
                            //新增入库
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    isLogin = true
                                    scanLogin(macId)
                                    customDialog()
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                } else {
                                    if (mChemicalLevel == 1) {
                                        //管控 校级管理员或院级管理
                                        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                            scanLogin(macId)
                                            customDialog()
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)

                                        } else {
                                            customDialogView(0, "无权限信息")
                                        }
                                    } else {
                                        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                            scanLogin(macId)
                                            customDialog()
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                        } else {
                                            customDialogView(0, "无权限信息")
                                        }
                                    }
                                }
                            } else {
                                if (isLogin) {
                                    //已经有登陆人
                                    if (mChemicalLevel == 1) {
                                        //管控 校级管理员或院级管理
                                        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        } else {
                                            customDialogView(2, "无权限信息")
                                        }
                                    } else {
                                        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        } else {
                                            customDialogView(0, "无权限信息")
                                        }
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            }
                        }

                        1 -> { //归还业务 领用  标签管理
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    isLogin = true
                                    scanLogin(macId)
                                    customDialog()
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                } else {
                                    obtainCertification(data, macId)
                                }
                            } else {
                                if (isLogin) {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            }
                        }

                        2 -> {//待入库
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    isLogin = true
                                    scanLogin(macId)
                                    customDialog()
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                } else {
                                    toBeStored(data, macId)
                                }
                            } else {
                                if (isLogin) {
                                    if (mChemicalLevel == 1) {
                                        //管控
                                        if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        } else {
                                            customDialogView(0, "认证失败")
                                        }
                                    } else {
                                        //非管控  实验室负责人or安全负责人or柜锁管理员
                                        if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        } else {
                                            customDialogView(0, "认证失败")
                                        }
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            }
                        }
                    }

                }, { throwable ->
                    dismissLoading()
                    throwableView(throwable)
                })
        addDisposable(disposable)
    }

    private val delayedTask = object : Runnable {
        override fun run() {
            // 在这里编写需要延迟执行的代码
            scanLogin(mDeviceNum!!)
            // 调度下一次延迟任务，确保在执行完后再延迟3.5秒
            mHandler.postDelayed(this, 4000)
        }
    }

    // 使用 Glide 加载二维码到 ImageView
    private fun loadQRCodeIntoImageView(
        text: String,
        width: Int,
        height: Int,
        imageView: ImageView
    ) {
        val bitmap = generateQRCode(text, width, height)
        bitmap?.let {
            Glide.with(this)
                .load(it)
                .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                .into(imageView)
        }
    }

    // 生成二维码的函数
    private fun generateQRCode(text: String, width: Int, height: Int): Bitmap? {
        try {
            val bitMatrix: BitMatrix =
                MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height)
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            for (x in 0 until width) {
                for (y in 0 until height) {
                    bitmap.setPixel(
                        x,
                        y,
                        if (bitMatrix[x, y]) 0xFF000000.toInt() else 0xFFFFFFFF.toInt()
                    )
                }
            }
            return bitmap
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 0  没有图标 1 绿色(成功)   2红色（失败）
     *   失败或者成功的弹框
     */
    private fun customDialogView(types: Int, msg: String) {
        val customDialog = CustomDialog(this, types, msg)
        if (!this.isFinishing && !this.isDestroyed) {
            customDialog.show()
        }
    }

    /**
     * 异常处理
     */
    private fun throwableView(throwable: Throwable) {
        when (throwable) {
            is NetException -> {
                if (throwable.message.isNullOrEmpty()) {
                    "接口请求失败(${throwable.code})"
                } else {
                    throwable.message!!
                }
            }

            is SocketTimeoutException -> "请求超时，请稍后重试"
            is ConnectException -> "无法连接服务器，请检查网络"
            is HttpException -> "服务器繁忙，请稍后重试"
            else -> null
        }?.let { customDialogView(2, "$it") }
    }
}