package xn.hxp.ui.still

import android.bluetooth.BluetoothDevice
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.feasycom.common.bean.ConnectType
import com.kongzue.dialogx.dialogs.PopTip
import com.rc.core.ui.activity.BaseActivity
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.GiveBackBean
import com.rc.httpcore.bean.LockVoListBean
import com.rc.httpcore.bean.ReturnDetailsBean
import com.rc.httpcore.bean.ReturnGiveBackBean
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.client.HttpTool
import com.rc.httpcore.exception.NetException
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.HttpException
import xn.hxp.R
import xn.hxp.app.ChemicalApp
import xn.hxp.comm.Constants
import xn.hxp.databinding.ActivityChemicalsAlsoBinding
import xn.hxp.receiver.OnSerialScanListener
import xn.hxp.receiver.PortScanHelper
import xn.hxp.receiver.UsbReceiver
import xn.hxp.ui.PrintBean
import xn.hxp.ui.adapter.ReturningChemicalsAdapter
import xn.hxp.ui.verify.TwoVerificationActivity
import xn.hxp.utils.*
import xn.hxp.utils.bluetooth.SppTool
import xn.hxp.utils.bluetooth.SppTool.BleSppCallback
import xn.hxp.weidith.*
import java.lang.Runnable
import java.net.ConnectException
import java.net.SocketTimeoutException

//化学品-归还   StorageDialog  柜字信息
class ChemicalsAlsoActivity : BaseActivity() {

    //归还列表
    private val mAdapter by lazy { ReturningChemicalsAdapter() }
    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数

    //    private var jobTow: Job? = null
    private lateinit var mGiveBackBean: GiveBackBean //归还参数
    private lateinit var mDataBean: ReturnDetailsBean //查询返回单挑信息
    private lateinit var timeUpdater: TimeUpdater
    private lateinit var mReturnDetailsBean: ReturnGiveBackBean  //归还数据显示
    private var mDoorId: String? = null
    private var mCabinetId: String? = null
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()  // 需要打开得柜锁数量
    private val handlerUtil = HandlerUtil.getInstance()
    private var mJoinType = 1   //称重方式 1 称重，2 录入
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10
    private var mWeighDialog: WeighDialog? = null
    private var isok = false // true  再次开门

    lateinit var viewBinding: ActivityChemicalsAlsoBinding

    override fun setViewBinding(): ViewBinding {
        viewBinding = ActivityChemicalsAlsoBinding.inflate(layoutInflater)
        return viewBinding
    }

    override fun onInit() {

        //注册广播
        EventBus.getDefault().register(this)
        initTitle()
        viewBinding.tvOutLogin.setOnClickListener {
            HttpTool.logout()
        }
        inAdapter()//初始化适配器
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }

        //归还
        viewBinding.revert.setOnClickListener {
            if (viewBinding.linTow.visibility == View.GONE) {
                return@setOnClickListener
            }
            if (mDataBean.verify) { //是否需要双人认证
                //需要双人认证
                val map = mutableMapOf<String, Any>()
                //当前 管控类型
                map["chemicalLevel"] = mDataBean.chemicalLevel  //管控类型
                map["doorId"] = "${viewBinding.cabinet.tag}"  //柜子id
                map["mTag"] = 1
//                map["hides"] = 4   //隐藏扫码
                //需要双人认证   1人脸 2刷卡 3扫码  获取基础信息配置
                if (ChemicalApp.confs!!.verifyType.length == 1) {

                    when (ChemicalApp.confs!!.verifyType) {
                        "1" -> {//人脸
                            map["mVerTyps"] = 1

                        }

                        "2" -> {//刷卡
                            map["mVerTyps"] = 2


                        }

                        "3" -> {//扫码
                            map["mVerTyps"] = 3

                        }
                    }

                    UiManager.switcher(
                        this,
                        map,
                        TwoVerificationActivity::class.java
                    )
                } else {
                    verifyChecking()
                }

            } else {
                //1无锁，2是智能锁，3是钥匙柜
                mCabinetLockVoList = mDataBean.cabinetLockVoList
                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                    mLockStr.clear()
                    mCabinetLockVoList!!.forEach { it ->
                        when (it.unlockingMethod) {
                            2 -> { //智能锁
                                mLockStr.add("${it.lockNum}")
                            }
                        }
                    }
                    if (mLockStr != null && mLockStr.size > 0) {
                        openLock(mLockStr)
                    } else {
                        weighData()
                    }
                } else {
                    weighData()
                }
            }

        }

        //废弃  不需要称重
        viewBinding.butDiscard.setOnClickListener {
            ////管控 1     非管控  2
            discardDialogShow()
//            if (mDataBean.chemicalLevel == 1) {
//                discardDialogShow()
//            } else {
//                //直接废弃
//                //调用归还API
//                mGiveBackBean = GiveBackBean(
//                    id = mDataBean.id,
//                    stockId = mDataBean.id,
//                    stockDetailsId = mDataBean.stockDetailsId,
//                    returnType = mJoinType,
//                    useStatus = 4,
//                    weigh = null,
//                    cabinetId = mDataBean.cabinetId,
//                    cabinetName = mDataBean.cabinetName,
//                    doorId = mDataBean.doorId,
//                    doorName = mDataBean.doorName,
//                    layers = mDataBean.layers.toInt(),
//                )
//                try {// 从 SharedPreferences 中取出集合
//                    val retrievedList = SharedPreferencesHelper.getList(this@ChemicalsAlsoActivity)
//                    if (retrievedList != null && retrievedList.size > 0) {
//                        mGiveBackBean.backOneUser = "${retrievedList[0].userId}"
//                        mGiveBackBean.backOneUser = "${retrievedList[0].name}"
//                        mGiveBackBean.backTwoUser = "${retrievedList[1].userId}"
//                        mGiveBackBean.backTwoUserName = "${retrievedList[1].name}"
//                        // 清空 SharedPreferences 中的集合
//                        SharedPreferencesHelper.clearList(this@ChemicalsAlsoActivity)
//                    }
//                } catch (e: Exception) {
//
//                }
//                //chemical/aio/giveBack  废弃
//                showLoading("加载中...")
//                val disposable = ApiRepository.giveBack(mGiveBackBean)
//                    .subscribe({ data ->
//                        dismissLoading()
//                        MediaPlayerHelper.playRawMp3(
//                            this@ChemicalsAlsoActivity,
//                            R.raw.feiqichuku
//                        )
//                        customDialogView(1, "已废弃出库,请及时进行废弃回收")
//                        mHandleScanEvent = false
//                        viewBinding.relOne.visibility = View.VISIBLE
//                        viewBinding.linTow.visibility = View.GONE
//                        mPages = 1
//                        useList()
//                    }, { throwable ->
//                        dismissLoading()
//                        showNetError(throwable)
//
//                    })
//                addDisposable(disposable)
//            }

        }

        //空瓶  不需要称重
        viewBinding.butEmpties.setOnClickListener {
            emptiesDialogsShow()
        }

        //柜子信息
        viewBinding.imgCabinet.setOnClickListener {
            getCabinet(ChemicalApp.subjectId!!, 1)
        }


        //化学品柜 查询
        viewBinding.relCabinet.setOnClickListener {
            getCabinet(ChemicalApp.subjectId!!, 0)
        }

        viewBinding.reLabel.setOnClickListener {
            //补打标签
            val print = PrintBean()
            print.tag = mDataBean.tagCode  //化学品编码
            print.wxCode = mDataBean.wxCode!!
            print.name = mDataBean.chemicalName!! //化学品名称
            if (mDataBean.casNum != null) {
                print.casNo = mDataBean.casNum!!  //cas号
            } else {
                print.casNo = ""
            }
//            if (mDataBean.topicGroup) {
//                print.person = mDataBean.topicGroupName //归属人
//            } else {
//                print.person = mDataBean.applyUserName //归属人
//            }
            print.person = mDataBean.belongName
            //管控 1     非管控  2
            if (mDataBean.chemicalLevel == 1) {
                print.level = "管控"
            } else {
                print.level = "非管控"
            }
            //
            print.types = "${mDataBean.chemicalCategoryName}"
            PrintTool.INSTANCE.print(mDataBean.isGr, mDataBean.belongType == 2, print)
        }

        viewBinding.replaceLabel.setOnClickListener {
//            //更换RFID
//            val airBottleNewDialog =
//                AirBottleNewDialog(this, mDataBean.rfidCode, object : AirBottleNewDialog.ILintDate {
//                    override fun onLintDate(cont: String) {
//                        if (mDataBean.rfidCode != null) {
//                            if (mDataBean.rfidCode!! != cont) {
//                                updateRfid(mDataBean.stockDetailsId, cont)
//                            } else {
//                                showToast("更换的标签不能重复")
//                            }
//                        } else {
//                            updateRfid(mDataBean.stockDetailsId, cont)
//                        }
//                    }
//                })
//            airBottleNewDialog.show()

            if (viewBinding.replaceLabel.text.toString().startsWith("更")) {
                val airBottleNewDialog =
                    AirBottleNewDialog(
                        this,
                        mDataBean.rfidCode,
                        object : AirBottleNewDialog.ILintDate {
                            override fun onLintDate(cont: String) {
                                if (mDataBean.rfidCode!! != cont) {
                                    updateRfid(mDataBean.stockDetailsId, cont)
                                } else {
                                    showToast("更换的标签不能重复")
                                }

                            }
                        })
                airBottleNewDialog.show()
            } else {
                //RFID打印
                var airBottleDialog = AirBottleDialog(this, object : AirBottleDialog.ILintDate {
                    override fun onLintDate(cont: String) {
                        if (cont.isNotEmpty()) {
                            updateRfid(mDataBean.stockDetailsId, cont)
                        }
                    }
                })
                airBottleDialog.show()
            }

        }

        //列表查询  EdContDialog
        viewBinding.reQuy.setOnClickListener {
            page = 1
            useList()
        }

        viewBinding.resetting.setOnClickListener {
            page = 1
            mCabinetId = null
            mDoorId = null
            viewBinding.edCont.setText("")
            viewBinding.cabinetName.text = "化学品柜"
            useList()
        }

        viewBinding.butUpper.setOnClickListener {
            //上一页
            if (mDataPage != 0) {
                if (page != 1) {
                    page--
                    useList()
                }
            }
        }

        viewBinding.butNext.setOnClickListener {
            //下一页
            if (mDataPage != page) {
                page++
                useList()
            }
        }

        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()
        //归还列表信息查询
        useList()

        AudioPlayer.getInstance().play(R.raw.scan_label)
        customDialogView(0, "请扫描标签")
    }

    private fun updateRfid(
        ids: String,
        rfid: String
    ) {
        showLoading("操作中...")
        val disposable = ApiRepository.updateRfid(ids, rfid).subscribe({ data ->
            dismissLoading()
            customDialogView(1, "更换成功")
            mHandleScanEvent = false
            //补打标签
            val print = PrintBean()
            print.tag = mDataBean.tagCode  //化学品编码
            print.wxCode = mDataBean.wxCode!!
            print.name = mDataBean.chemicalName!! //化学品名称
            if (mDataBean.casNum != null) {
                print.casNo = mDataBean.casNum!!  //cas号
            } else {
                print.casNo = ""
            }
//            if (mDataBean.topicGroup) {
//                print.person = mDataBean.topicGroupName //归属人
//            } else {
//                print.person = mDataBean.applyUserName //归属人
//            }
            print.person = mDataBean.belongName
            //管控 1     非管控  2
            if (mDataBean.chemicalLevel == 1) {
                print.level = "管控"
            } else {
                print.level = "非管控"
            }
            //
            print.types = "${mDataBean.chemicalCategoryName}"
            PrintTool.INSTANCE.print(mDataBean.isGr, mDataBean.belongType == 2, print)
        }, { throwable ->
            dismissLoading()
            showNetError(throwable)

        })
        addDisposable(disposable)
    }


    //验证方式
    private fun verifyChecking() {
        val map = mutableMapOf<String, Any>()
        map["chemicalLevel"] = mDataBean.chemicalLevel  //管控类型
        map["doorId"] = "${viewBinding.cabinet.tag}"  //柜子id
        map["mTag"] = 1
        map["mVerTyps"] = 0
        if (ChemicalApp.confs!!.verifyType == "1,2" || ChemicalApp.confs!!.verifyType == "2,1") {
            //人脸+刷卡
            map["hides"] = 1   //隐藏扫码
        } else if (ChemicalApp.confs!!.verifyType == "1,3" || ChemicalApp.confs!!.verifyType == "3,1") {
            //人脸+扫码
            map["hides"] = 2   //隐藏刷卡
        } else if (ChemicalApp.confs!!.verifyType == "2,3" || ChemicalApp.confs!!.verifyType == "3,2") {
            map["hides"] = 3   //隐藏扫码
        } else {
            //人脸+刷卡+扫码
            map["hides"] = 4
        }
        UiManager.switcher(
            this,
            map,
            TwoVerificationActivity::class.java,
            Constants.REQUEST_CODE
        )
    }

    private fun initTitle() {
        viewBinding.tvName.text = ChemicalApp.userData!!.userName
        val imageView = viewBinding.imageName
        // 使用 Glide 加载网络图片
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.userData!!.avatar}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(imageView)

        // 使用 Glide 加载网络图片
        viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)
    }

    //查询存储位置
    private fun getCabinet(subId: String, tag: Int) {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(subId)
            .subscribe({ data ->
                dismissLoading()
                val storageDialog =
                    StorageDialog(
                        ct = this,
                        mType = tag,
                        listData = data,
                        lint = object : StorageDialog.IonClickListener {
                            override fun onClick(
                                cabinetId: String,
                                cabinetName: String,
                                doorName: String,
                                doorId: String,
                                cabinetLockVoList: List<LockVoListBean>,
                                layers: Int,
                                lockNum: String,
                            ) {
                                if (tag == 1) {
                                    mDataBean.cabinetId = cabinetId
                                    mDataBean.cabinetName = cabinetName
                                    mDataBean.doorId = doorId
                                    mDataBean.doorName = doorName
                                    mDataBean.layers = "$layers"
                                    //柜锁类型
                                    viewBinding.cabinet.text =
                                        "${mDataBean.cabinetName}-${mDataBean.doorName}-${mDataBean.layers}层"
                                    viewBinding.cabinet.tag = "${mDataBean.doorId}"
                                    mDataBean.cabinetLockVoList = cabinetLockVoList
                                    mCabinetLockVoList = cabinetLockVoList
                                } else {
                                    mCabinetId = cabinetId
                                    mDoorId = doorId
                                    viewBinding.cabinetName.text = "$doorName"
                                }
                            }

                            override fun onClose() {
                                if (mCabinetId != null) {
                                    mCabinetId = null
                                    mDoorId = null
                                    viewBinding.cabinetName.text = "化学品柜"
                                }
                            }
                        })
                storageDialog.show()

            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    private fun discardDialogShow() {
        val discardDialog = DiscardDialog(
            this,
            "${mDataBean.collectStockNum}${mDataBean.specUnit}",
            object : DiscardDialog.IClickLit {
                override fun onClickClose() {

                }

                override fun onDetermineClick(cont: String?) {
                    //调用归还API
                    mGiveBackBean = GiveBackBean(
                        id = mDataBean.id,
                        stockId = mDataBean.id,
                        stockDetailsId = mDataBean.stockDetailsId,
                        returnType = mJoinType,
                        useStatus = 4,
                        weigh = null,
                        cabinetId = mDataBean.cabinetId,
                        cabinetName = mDataBean.cabinetName,
                        doorId = mDataBean.doorId,
                        doorName = mDataBean.doorName,
                        layers = mDataBean.layers.toInt(),
                        disuseReason = cont
                    )
//                    try {// 从 SharedPreferences 中取出集合
//                        val retrievedList =
//                            SharedPreferencesHelper.getList(this@ChemicalsAlsoActivity)
//                        if (retrievedList != null && retrievedList.size > 0) {
//                            mGiveBackBean.backOneUser = "${retrievedList[0].userId}"
//                            mGiveBackBean.backOneUser = "${retrievedList[0].name}"
//                            mGiveBackBean.backTwoUser = "${retrievedList[1].userId}"
//                            mGiveBackBean.backTwoUserName = "${retrievedList[1].name}"
//                            // 清空 SharedPreferences 中的集合
//                            SharedPreferencesHelper.clearList(this@ChemicalsAlsoActivity)
//                        }
//                    } catch (e: Exception) {
//
//                    }
                    //chemical/aio/giveBack  废弃
                    showLoading("加载中...")
                    val disposable = ApiRepository.giveBack(mGiveBackBean)
                        .subscribe({ data ->
                            dismissLoading()
                            AudioPlayer.getInstance().play(R.raw.revoked_recycle_hint)
                            customDialogView(1, "已废弃出库,请及时进行废弃回收")
                            viewBinding.relOne.visibility = View.VISIBLE
                            viewBinding.linTow.visibility = View.GONE
                            viewBinding.revert.isChecked = false
                            viewBinding.revert.isEnabled = false
                            mHandleScanEvent = false
                            mPages = 1
                            useList()
//                            finish()
                        }, { throwable ->
                            dismissLoading()
                            showNetError(throwable)

                        })
                    addDisposable(disposable)
                }

                override fun onTimerReply() {
                }
            })
        discardDialog.show()
    }

    //空瓶
    private fun emptiesDialogsShow() {
        val emptiesDialog = EmptiesDialog(
            this,
            mDataBean.chemicalName,
            "${mDataBean.collectStockNum}${mDataBean.specUnit}",
            object : EmptiesDialog.IClickLit {
                override fun onClickClose() {
                    //关闭
                }

                override fun onDetermineClick() {
                    //确定

                    //调用归还API
                    mGiveBackBean = GiveBackBean(
                        id = mDataBean.id,
                        stockId = mDataBean.id,
                        stockDetailsId = mDataBean.stockDetailsId,
                        returnType = mJoinType,
                        useStatus = 3,
                        weigh = null,
                        cabinetId = mDataBean.cabinetId,
                        cabinetName = mDataBean.cabinetName,
                        doorId = mDataBean.doorId,
                        doorName = mDataBean.doorName,
                        layers = mDataBean.layers.toInt()
                    )
                    //chemical/aio/giveBack
                    showLoading("加载中...")
                    val disposable = ApiRepository.giveBack(mGiveBackBean)
                        .subscribe({ data ->
                            dismissLoading()
                            AudioPlayer.getInstance().play(R.raw.empties_recycle_hint)
                            customDialogView(1, "已空瓶出库,请及时进行废弃回收")
                            viewBinding.relOne.visibility = View.VISIBLE
                            viewBinding.linTow.visibility = View.GONE
                            viewBinding.revert.isChecked = false
                            viewBinding.revert.isEnabled = false

                            mHandleScanEvent = false
                            mPages = 1
                            useList()
                        }, { throwable ->
                            dismissLoading()
                            showNetError(throwable)

                        })
                    addDisposable(disposable)

                }
            })
        emptiesDialog.show()

    }

    private var mWeighingValue: EditText? = null
    private var mHandler: Handler = Handler(Looper.getMainLooper())

    //称重
    private fun weighData() {
//        val netContent = mDataBean.chemicalDensity * mDataBean.specNum  // 净量 = 密度*规格
//        var density = "${netContent}/${mDataBean.packUnit}"
        if (::mDataBean.isInitialized) {
            var density = "${mDataBean.specNum}${mDataBean.specUnit}/${mDataBean.packUnit}"
            //确定  链接蓝牙
            mWeighDialog = WeighDialog(
                this@ChemicalsAlsoActivity,
                density, object : WeighDialog.IViewLint {
                    override fun weighingView(weighingValue: EditText) {
                        //称重页面 获取的文本TextView  后期可能是输入框
//                    showLoading("蓝牙连接中...")
                        mWeighingValue = weighingValue
                        if (mWeighingValue!!.isEnabled) {
                            // EditText允许输入
                            // 在这里执行相应的操作
                            weiView()
                        } else {
                            // EditText禁止输入
                            // 在这里执行相应的操作
                            connectToDeviceWithTimeout()
                        }

                        mWeighingValue!!.setOnEditorActionListener { v, actionId, event ->
                            if (event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                                // 确认是否触发了"actionDone"
                                true
                            } else {
                                closEnd()
                                false
                            }
                        }
                    }

                    //确定 关闭  获取文本值 跳转新的页面
                    override fun viewCloses() {
                        SppTool.INSTANCE.disconnect()
                        closEnd()
                        closEndTwo()
                        try {
                            lifecycleScope.cancel()
                            LogUtils.i("=====协程关闭成功")
                        } catch (e: Exception) {
                            LogUtils.i("=====协程关闭失败")
                        }
                    }

                    override fun onMovement() {
                        weiView()
                        try {
                            lifecycleScope.cancel()
                            LogUtils.i("=====协程关闭成功")
                        } catch (e: Exception) {
                            LogUtils.i("=====协程关闭失败")
                        }
                    }

                    override fun onTimerReply() {
                    }
                })
            mWeighDialog!!.show()
            mHandler.postDelayed({
//            try {
//                jobTow?.cancel()
//            } catch (e: Exception) {
//            }
            }, 1000 * 60) // 15秒后关闭对话框
        }
    }


    private fun weiView() {
        mJoinType = 2
        showToast("请手动输入")
//        try {
//            jobTow?.cancel()
//        } catch (e: Exception) {
//        }
        mWeighingValue!!.isEnabled = true
        mWeighingValue!!.requestFocus()
    }

    var weight: String = ""
    private fun connectToDeviceWithTimeout() {
        val sppMac = SPUtils.getInstance().getString("sppMac", "")
        if (!TextUtils.isEmpty(sppMac)) {
            showToast("连接中...", Toast.LENGTH_SHORT)
            SppTool.INSTANCE.connect(sppMac, object : BleSppCallback {
                override fun sppPeripheralConnected(
                    bluetoothDevice: BluetoothDevice?,
                    connectType: ConnectType?
                ) {
                    AudioPlayer.getInstance().play(R.raw.weight_hint)
                }

                override fun packetReceived(address: String, strValue: String) {
                    if (weight != strValue) {
                        runOnUiThread {
                            mWeighingValue!!.setText("$weight")
                        }
                    }
                    weight = strValue
                }

                override fun sppPeripheralDisconnected(address: String?) {
                }
            })
        } else {
            showToast("未配置蓝牙称!", Toast.LENGTH_SHORT)
        }
//        BleTool.INSTANCE.setBleCallback(object : BleTool.BleCallback {
//            override fun onSuccess() {
//
//            }
//
//            override fun onNotifyFailure(exception: java.lang.Exception?) {
//                showToast("请手动输入")
//                weiView()
//            }
//
//            override fun onChanged(weight: String) {
//                if (weight.isEmpty()) {
//                    showToast("请手动输入")
//                    weiView()
//                } else {
//                    mWeighingValue!!.setText("$weight")
//                }
//            }
//        })
    }

    private fun showToast(message: String, duration: Int) {
        Toast.makeText(ActivityUtils.getTopActivity(), message, duration).show()
    }

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

    private fun closEnd() {
//        jobTow?.cancel()

        mWeighDialog!!.dismiss()
        val weigh =
            mWeighingValue!!.text.toString().trim()  //称重后的重量
        if (weigh.isEmpty()) {
            showToast("未称重")
            return
        }
        if (weigh.toDouble() <= 0) {
            showToast("当前重量有误")
            return
        }
        //因为是先开锁  1无锁
        cabinetOpen()
    }


    private fun closEndTwo() {
//        jobTow?.cancel()
//        lifecycleScope.cancel()
        mWeighDialog!!.dismiss()
    }

    private fun cabinetOpen() {
//        mLockStr.clear()
//        isok = false
        //调用归还API
        mGiveBackBean = GiveBackBean(
            id = mDataBean.id,
            stockId = mDataBean.id,
            stockDetailsId = mDataBean.stockDetailsId,
            useStatus = 0,
            weigh = mWeighingValue!!.text.toString().toDouble(),
            cabinetId = mDataBean.cabinetId,
            cabinetName = mDataBean.cabinetName,
            doorId = mDataBean.doorId,
            doorName = mDataBean.doorName,
            returnType = mJoinType,
            layers = mDataBean.layers.toInt()
        )
        try {// 从 SharedPreferences 中取出集合
            val retrievedList = SharedPreferencesHelper.getList(this)
            if (retrievedList != null && retrievedList.size > 0) {
                mGiveBackBean.backOneUser = "${retrievedList[0].userId}"
                mGiveBackBean.backOneUserName = "${retrievedList[0].name}"
                mGiveBackBean.backTwoUser = "${retrievedList[1].userId}"
                mGiveBackBean.backTwoUserName = "${retrievedList[1].name}"
                // 清空 SharedPreferences 中的集合
                SharedPreferencesHelper.clearList(this)
            }
        } catch (e: Exception) {

        }
        //chemical/aio/giveBack
        showLoading("加载中...")
        val disposable = ApiRepository.returnGiveBack(mGiveBackBean)
            .subscribe({ data ->
                dismissLoading()
//                customDialogView(1, "归还成功")
                customDialogView(1, "请将化学品放入化学品柜")
                AudioPlayer.getInstance().play(R.raw.gui_men_yi_kai_fang_ru_hxp)
                //1无锁，2是智能锁，3是钥匙柜
                var isLock = false
                mCabinetLockVoList = mDataBean.cabinetLockVoList
                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                    mCabinetLockVoList!!.forEach { it ->
                        if (it.unlockingMethod == 2) {
                            isLock = true
                            return@forEach
                        }
                    }
                }

                val cabinetOpenDialog =
                    CabinetOpenDialog(
                        this@ChemicalsAlsoActivity,
                        isLock,
                        "${data.useAmount!!}${data.specUnit}",
                        "${data.remark!!}${data.specUnit}",
                        object : CabinetOpenDialog.IClickLit {
                            override fun onClickClo() {
                            }

                            override fun onOpenClick() {
                                mReturnDetailsBean = data
                                //再次开门
                                isok = true
                                //1无锁，2是智能锁，3是钥匙柜
                                mCabinetLockVoList = mDataBean.cabinetLockVoList
                                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                                    mLockStr.clear()
                                    mCabinetLockVoList!!.forEach { it ->
                                        when (it.unlockingMethod) {
                                            2 -> { //智能锁
                                                mLockStr.add("${it.lockNum}")
                                            }
                                        }
                                    }
                                    if (mLockStr != null && mLockStr.size > 0) {
                                        openLock(mLockStr)
                                    } else {
                                        isok = false
                                        customDialogView(1, "柜门已开")
                                    }
                                } else {
                                    isok = false
                                    customDialogView(1, "柜门已开")
                                }
                            }
                        })
                cabinetOpenDialog.show()
                mHandleScanEvent = false
                mPages = 1
                useList()
                viewBinding.relOne.visibility = View.VISIBLE
                viewBinding.linTow.visibility = View.GONE
                viewBinding.revert.isChecked = false
                viewBinding.revert.isEnabled = false
            }, { throwable ->
                dismissLoading()
                throwableView(throwable)
            })
        addDisposable(disposable)


    }

    private fun dloViews() {
        customDialogView(1, "请将化学品放入化学品柜")
        AudioPlayer.getInstance().play(R.raw.gui_men_yi_kai_fang_ru_hxp)
        val cabinetOpenDialog =
            CabinetOpenDialog(
                this@ChemicalsAlsoActivity,
                false,
                "${mReturnDetailsBean.useAmount!!}${mReturnDetailsBean.specUnit}",
                "${mReturnDetailsBean.remark!!}${mReturnDetailsBean.specUnit}",
                object : CabinetOpenDialog.IClickLit {
                    override fun onClickClo() {
                    }

                    override fun onOpenClick() {
                        //再次开门
                        isok = true
                        //1无锁，2是智能锁，3是钥匙柜
                        mCabinetLockVoList = mDataBean.cabinetLockVoList
                        if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                            mLockStr.clear()
                            mCabinetLockVoList!!.forEach { it ->
                                when (it.unlockingMethod) {
                                    2 -> { //智能锁
                                        mLockStr.add("${it.lockNum}")
                                    }
                                }
                            }
                            if (mLockStr != null && mLockStr.size > 0) {
                                openLock(mLockStr)
                            } else {
                                customDialogView(1, "柜门已开")
                            }
                        } else {
                            customDialogView(1, "柜门已开")
                        }
                    }
                })
        cabinetOpenDialog.show()
    }


    private fun useList() {
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["subId"] = "${ChemicalApp.subjectId!!}"
        mutableMap["backStatusCollect"] = "[1,2]"
        if (mCabinetId != null) {
            mutableMap["cabinetId"] = "$mCabinetId"
        }
        if (mDoorId != null) {
            mutableMap["doorId"] = "$mDoorId"
        }
//        mutableMap["layers"] = ""
        mutableMap["page"] = "$page"
        mutableMap["pageSize"] = "$pageSize"
        val searchValue = viewBinding.edCont.text.toString().trim()

        if (searchValue.isNotEmpty()) {
            mutableMap["searchValue"] = "$searchValue"
        }
        showLoading("查询中...")
        val disposable = ApiRepository.useList(mutableMap).subscribe({ data ->
            dismissLoading()
            mDataPage = data.pages  //总页
            if (data != null && data.records.size == 0) {
                mAdapter.data.clear()
                mAdapter.notifyDataSetChanged()
            }
            if (data.pages != 0) {
                if (data.pages > 1 && data.current > 1) {
                    //当前需要更新页码
                    upPagesView(data.pages, data.current)
                    mAdapter.setList(data.records.toMutableList())
                } else {
                    mAdapter.setNewInstance(data.records.toMutableList())
                    initPagesView(data.pages)
                }
            }
        }, { throwable ->
            dismissLoading()
            showNetError(throwable)

        })
        addDisposable(disposable)
    }


    private fun inAdapter() {
        viewBinding.rvUse?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvUse?.adapter = mAdapter
    }

    /**
     * 总页码 当前页  初始化
     */
    private fun initPagesView(pages: Int) {
        mPages = pages
        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.one.setTextColor(ContextCompat.getColor(this, R.color.white))
        viewBinding.two.setTextColor(ContextCompat.getColor(this, R.color.black))

        when (pages) {
            1 -> {
                viewBinding.one.visibility = View.VISIBLE
            }

            2 -> {
                viewBinding.two.visibility = View.VISIBLE
            }

            3 -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
            }

            else -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
                viewBinding.drop.visibility = View.VISIBLE
                viewBinding.many.visibility = View.VISIBLE
                viewBinding.many.text = "$pages"
            }
        }
        if (pages == 1 || pages == 0) {
            viewBinding.two.visibility = View.GONE
            viewBinding.three.visibility = View.GONE
            viewBinding.many.visibility = View.GONE
            viewBinding.drop.visibility = View.GONE
        }
        if (pages < 4) {
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
        }
    }

    //更新页码
    private fun upPagesView(pages: Int, current: Int) {
        LogUtils.i("======2")
        if (pages < 4) {
//            viewBinding.one.visibility = View.VISIBLE
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
//                    viewBinding.two.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
//                    viewBinding.three.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }
            }
        } else {
//            viewBinding.many.visibility = View.VISIBLE
            viewBinding.three.text = "3"
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }

                else -> {
                    viewBinding.three.text = "$current"
                    if (pages == current) {
                        viewBinding.three.text = "${current - 1}"

                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.white
                            )
                        )
                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_page)

                    } else {
                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.white
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )

                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    }
                }
            }
        }
    }

    private fun upView() {
        viewBinding.relOne.visibility = View.GONE
        viewBinding.linTow.visibility = View.VISIBLE
        viewBinding.revert.isChecked = true
        viewBinding.revert.isEnabled = true
        viewBinding.chemicalName.text = "${mDataBean.chemicalName}"
        viewBinding.chemicalName.setOnClickListener {
            TextTool.showPop(
                this,
                viewBinding.chemicalName
            )
        }
        viewBinding.chemicalLevelName.text = "${mDataBean.chemicalLevelName}"
        viewBinding.chemicalCategoryName.text = "${mDataBean.chemicalCategoryName}"
        viewBinding.tagCode.text = "编码${mDataBean.tagCode}"
        // specNum/specUnit/packUnit
        viewBinding.spec.text = "${mDataBean.specNum}${mDataBean.specUnit}/${mDataBean.packUnit}"
        viewBinding.belongName.text = "${mDataBean.belongName}"
        viewBinding.collectStockNum.text = "${mDataBean.collectStockNum}${mDataBean.specUnit}"
        viewBinding.createByName.text = "${mDataBean.createByName}"
        viewBinding.collectTime.text = "${mDataBean.collectTime} |"
        viewBinding.surplusTime.text = "${mDataBean.surplusTime}"
        viewBinding.cabinet.text =
            "${mDataBean.cabinetName}-${mDataBean.doorName}-${mDataBean.layers}层"
        viewBinding.cabinet.tag = "${mDataBean.doorId}"
        //柜锁类型
        mCabinetLockVoList = mDataBean.cabinetLockVoList
        LogUtils.i("========A========${mDataBean.rfidCode}")
        if (mDataBean.rfidCode == null) {
            LogUtils.i("========B========${mDataBean.rfidCode}")
            viewBinding.replaceLabel.text = "绑定RFID"
        } else {
            LogUtils.i("========C========${mDataBean.rfidCode}")
            viewBinding.replaceLabel.text = "更换RFID"
        }
//        mUnlockingMethod = mDataBean.unlockingMethod
    }

    //=========================刷卡start================
    //刷卡信息  调用当前化学品信息 进行归还
    private fun handleScanEvent(cont: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.backDetail(cont, ChemicalApp.subjectId.toString())
            .subscribe({ data ->
                dismissLoading()
                mDataBean = data
                upView()
            }, { throwable ->
                dismissLoading()
                mHandleScanEvent = false
                throwableView(throwable)

            })
        addDisposable(disposable)
    }

    private val mPortScanHelper by lazy {
        PortScanHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (!mHandleScanEvent) {
                    if (content.isNotBlank()) {
                        LogUtils.i("==========当前usb返回参数$content")
                        mHandleScanEvent = true
                        //所有通过查询二维码的参数 需要先判断  http开头的  然后进行截取
                        if (content.startsWith("http")) {
                            try {
                                val currentDateTimeString =
                                    BigDecimalUtils.extractParameterValue(content, "code")
                                LogUtils.i("=======ce  $currentDateTimeString")
                                handleScanEvent(currentDateTimeString!!)
                            } catch (e: Exception) {
                                mHandleScanEvent = false
                                showToast("请重新扫码")
                            }
                        } else {
                            handleScanEvent(content)
                        }
                    }

                }
            }

        })
    }

    //刷卡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)
        }
    }

    override fun onResume() {
        super.onResume()
        mPortScanHelper.onResume()
        if (Constants.AUTHENTICATION) {
//            mCabinetLockVoList = mDataBean.cabinetLockVoList
            if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                mLockStr.clear()
                mCabinetLockVoList!!.forEach { it ->
                    when (it.unlockingMethod) {
                        2 -> { //智能锁
                            mLockStr.add("${it.lockNum}")
                        }
                    }
                }
                if (mLockStr != null && mLockStr.size > 0) {
                    openLock(mLockStr)
                } else {
                    weighData()
                }
            } else {
                weighData()
            }
            Constants.AUTHENTICATION = false
        }
        registerUsbBroadcast()
    }

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

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

    override fun onDestroy() {
        super.onDestroy()
        SppTool.INSTANCE.disconnect()
        mPortScanHelper.onPause()
        try {
//            jobTow?.cancel()
            countdownTimer?.cancel()
            mHandler.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
        // 停止定时更新
        unregisterReceiver(mUsbReceiver)
        EventBus.getDefault().unregister(this) //关闭广播

    }

    override fun cdFinish() {
        finish()
    }

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

    }

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

    private fun openLock(mLockStr: ArrayList<String>) {
        val map = mutableMapOf<String, Any>()
        map["subId"] = ChemicalApp.subjectId!!
        map["subName"] = ChemicalApp.subjectName!!
//        map["cabinetId"] = "$mCabinetId"
//        map["cabinetName"] = "$mCabinetName"
//        map["doorId"] = "$mDoorId"
//        map["doorName"] = "$mDoorName"
        map["cabinetId"] = "${mDataBean.cabinetId}"
        map["cabinetName"] = "${mDataBean.cabinetName}"
        map["doorId"] = "${mDataBean.doorId}"
        map["doorName"] = "${mDataBean.doorName}"
//        map["lockNum"] = "guisuo001"
        map["lockNumList"] = mLockStr
        map["operationType"] = 4
        if (ChemicalApp.subRoom != null) {
            map["subRoom"] = ChemicalApp.subRoom!!
        }
        map["type"] = true
        try {// 从 SharedPreferences 中取出集合
            val retrievedList = SharedPreferencesHelper.getList(this)
            if (retrievedList != null && retrievedList.size > 0) {
                map["oneUserId"] = "${retrievedList[0].userId}"
                map["oneUserName"] = "${retrievedList[0].name}"
                map["twoUserId"] = "${retrievedList[1].userId}"
                map["twoUserName"] = "${retrievedList[1].name}"
                // 清空 SharedPreferences 中的集合
//                SharedPreferencesHelper.clearList(this)
            }
        } catch (e: Exception) {

        }
        PopTip.show("正在开门")
        val disposable = ApiRepository.lockOperate(map)
            .subscribe({ data ->
                val containsFalse =
                    mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
                LogUtils.i("====开锁信息${containsFalse}  $isok")
                if (containsFalse) {
                    PopTip.show("正在查询开门状态...")
                    // 开始执行任务，每 3 秒执行一次
                    startCountdownLock()
                    handlerUtil.startTask(task, 1000)
                } else {
                    if (isok) {//再次开门
                        handlerUtil.stopAllTasks()
                        countdownTimer?.cancel()
                        isok = false
                    } else {
                        PopTip.show("开锁成功!")
                        //开锁成功
                        handlerUtil.stopAllTasks()
                        countdownTimer?.cancel()
                        //开锁成功
                        weighData()
                    }
                }
            }, { throwable ->
                showNetError(throwable)

            })
        addDisposable(disposable)

    }


    private var countdownTimer: CountDownTimer? = null
    private fun startCountdownLock() {
        val totalTime = 30 * 1000 // 30秒
        val interval = 1000 // 每秒更新一次

        countdownTimer = object : CountDownTimer(totalTime.toLong(), interval.toLong()) {
            override fun onTick(millisUntilFinished: Long) {
                val secondsLeft = millisUntilFinished / 1000
                println("剩余时间: $secondsLeft 秒")
            }

            override fun onFinish() {
                println("倒计时结束！")
                mCabinetLockVoList = null
                mLockStr.clear()
                showToast("开锁超时,可重新操作")
                dismissLoading()
                handlerUtil.stopAllTasks()
                // 在这里执行合适的操作，比如退出应用程序
            }
        }

        println("倒计时开始...")
        countdownTimer?.start()
    }

    private val task = Runnable {
        LogUtils.i("======归还开锁查询")
        //判断所有的锁开锁成功
        val containsFalse = mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
        if (containsFalse) {
            getLocks()
        } else {
            if (isok) {//再次开门
                handlerUtil.stopAllTasks()
                countdownTimer?.cancel()
                dismissLoading()
                isok = false
            } else {
                //开锁成功
                handlerUtil.stopAllTasks()
                countdownTimer?.cancel()
                dismissLoading()
                //开锁成功
                weighData()
            }
        }
    }

    //查询开锁信息
    private fun getLocks() {
        mCabinetLockVoList!!.forEachIndexed { index, fruit ->
            if (fruit.isOk == false && fruit.unlockingMethod == 2) {
                getLocksDate(index, fruit.lockNum)
            }
        }
    }

    //查询开锁状态
    private fun getLocksDate(index: Int, fruit: String) {

        val disposable = ApiRepository.getLocks(ChemicalApp.subjectId!!, fruit)
            .subscribe({ data ->
                if (data) {
                    mCabinetLockVoList!![index].isOk = true
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    /**
     * 异常处理
     */
    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") }
    }
}