package com.example.chemical.ui.warehousing

import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
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 com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.caysn.autoreplyprint.AutoReplyPrint
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.blu.BluetoothConnectionManager
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityWarehousingBinding
import com.example.chemical.ui.PrintBean
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.adapter.ChemicalsAdapter
import com.example.chemical.ui.adapter.InventoryListAdapter
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.ui.verify.TwoVerificationActivity
import com.example.chemical.utils.*
import com.example.chemical.weidith.*
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.ChemicalInfoBean
import com.rc.httpcore.bean.RuleBean
import com.rc.httpcore.bean.*
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.bean.HxpStockWaitListBean
import com.rc.httpcore.exception.NetException
import com.sun.jna.Pointer
import kotlinx.coroutines.*
import retrofit2.HttpException
import java.lang.Runnable
import java.math.BigDecimal
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.nio.charset.StandardCharsets

//待入库
class WarehousingActivity : BaseCountDownActivity<ActivityWarehousingBinding>() {

    private val mAdapter by lazy { InventoryListAdapter(this) }
    private val mAdapterChemicals by lazy { ChemicalsAdapter(this) }
    private var mChemicalInfoBean: ChemicalInfoBean? = null  //实验室信息
    private var mListData: List<RuleBean>? = null   //柜子信息
    private var mLabelDialog: LabelDialog? = null   //化学品信息生成

    //    private var jobTow: Job? = null
    private var mWeighingValue: EditText? = null
    private var mStockModeBean = StockModeBean(mutableListOf())
    private var mStockModelList = mutableListOf<StockModel>()
    private lateinit var timeUpdater: TimeUpdater
    private var mWeighDialog: WeighDialog? = null
    private var mCabinetId = ""   //柜子id
    private var mCabinetName = "" //柜子名称
    private var mDoorName = ""    //柜门名称
    private var mDoorId: String = ""
    private lateinit var mUnifiedVerBean: UnifiedVerBean  //当前是否需要双人认证
    private var mLayers = 1  //柜子层数
    private var mLayersTow = 1  //柜子选择层数
    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 mPrintTag = 0  //需要打印得内容条数
    private var mStockDetailsModel: MutableList<StockDetailsModel>? = null
    private var mLayer: Int = -1
    private val handlerPrint = HandlerUtil.getInstance()
    private var h = Pointer.NULL
    private var pritBot = false
    private var isClisLit = false  //是否点击称重关闭按钮
//    private lateinit var mChemicalConfsBean: ChemicalConfsBean  //获取化学品的称重超过比例or

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

    override fun initData() {
        super.initData()
        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()
        getRelList()//获取实验室 信息
    }

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        initTitle()
        initAdapter()
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }

        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
                HttpClient.token = null
                ChemicalApp.subjectId = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }

        //查询后根据返回集合数量  判断当天的显示
        viewBinding.options.setOnClickListener {
            //类别获取
            getOptions()
        }

        viewBinding.reSou.setOnClickListener {
            page = 1
            waitList()
        }

        //选择柜子信息
        viewBinding.imgPosition.setOnClickListener {
            //       mType = 1,   可以选择柜层
            val storageDialog =
                StorageDialog(ct = this,
                    listData = mListData!!,
                    lint = object : StorageDialog.IonClickListener {
                        override fun onClick(
                            cabinetId: String,
                            cabinetName: String,
                            doorName: String,
                            doorId: String,
                            cabinetLockVoList: List<LockVoListBean>,
                            layers: Int,
                            lockNum: String
                        ) {
                            mCabinetId = cabinetId
                            mCabinetName = cabinetName
                            mDoorName = doorName
                            mDoorId = doorId
                            mCabinetLockVoList = cabinetLockVoList
                            viewBinding.cabinet.text = "存储位置:${cabinetName}-${doorName}"
                            viewBinding.cabinet.tag = "$doorId"
                            mLayers = layers  //当前需要显示得层数
                            if (mStockModelList != null && mStockModelList.size > 0) {
                                mStockModelList.forEach {
                                    it.cabinetId = mCabinetId
                                    it.cabinetName = mCabinetName
                                    it.doorId = mDoorId
                                    it.doorName = mDoorName
                                    it.layers = mLayers
                                }
                            }
//
                            mAdapterChemicals.updateData(mLayers)
                        }

                        override fun onClose() {

                        }
                    })
            storageDialog.show()
        }

        viewBinding.butOpen.setOnClickListener {
            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 {
                    subAddData(0)
                }
            } else {
                subAddData(0)
            }
        }
        //待入库 确认入库
//        viewBinding.subAdd.setOnClickListener {
        ButtonDebouncer.setDebouncedOnClickListener(viewBinding.subAdd, 500L) {
            if (mAdapterChemicals.data.size > 0) {
                if (mUnifiedVerBean.verify) {
                    //需要双人认证   1人脸 2刷卡 3扫码  获取基础信息配置
                    if (ChemicalApp.confs!!.verifyType.length == 1) {
                        val map = mutableMapOf<String, Any>()
                        var chemicalLevel = 2
                        val dataList = mAdapterChemicals.data
                        dataList.forEach {
                            if (it.chemicalLevel == 1) {
                                chemicalLevel = it.chemicalLevel!!
                                return@forEach
                            }
                        }
                        map["chemicalLevel"] = chemicalLevel  //管控类型
                        map["doorId"] = "${viewBinding.cabinet.tag}"  //柜子id
                        map["mTag"] = 2

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

                            }

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


                            }

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

                            }
                        }

                        UiManager.switcher(
                            this,
                            map,
                            TwoVerificationActivity::class.java
                        )
//                        map["hides"] = 4   //隐藏扫码
//                        when (ChemicalApp.confs!!.verifyType) {
//                            "1" -> {//人脸
//                                UiManager.switcher(
//                                    this,
//                                    map,
//                                    TwoPersonActivity::class.java,
//                                    Constants.REQUEST_CODE
//                                )
//                            }
//
//                            "2" -> {//刷卡
//                                UiManager.switcher(
//                                    this,
//                                    map,
//                                    SwipeCodeTwoActivity::class.java,
//                                    Constants.REQUEST_CODE
//                                )
//
//                            }
//                            "3" -> {//扫码
//                                UiManager.switcher(
//                                    this,
//                                    map,
//                                    ScanCodeTwoActivity::class.java,
//                                    Constants.REQUEST_CODE
//                                )
//                            }
//                        }
                    } else {
                        verifyChecking()
                    }
                } else {
                    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 {
                            subAddData(0)
                        }
                    } else {
                        subAddData(0)
                    }

                }
            } else {
                showToast("缺少录入信息")
            }
        }

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

        viewBinding.butNext.setOnClickListener {
            //下一页
            if (mDataPage != 0) {
                if (mDataPage != page) {
                    page++
                    getRelList() //刷新页面
                }
            }
        }

    }

    //验证方式
    private fun verifyChecking() {
        val map = mutableMapOf<String, Any>()
        var chemicalLevel = 2
        val dataList = mAdapterChemicals.data
        dataList.forEach {
            if (it.chemicalLevel == 1) {
                chemicalLevel = it.chemicalLevel!!
                return@forEach
            }
        }
        map["chemicalLevel"] = chemicalLevel  //管控类型
        map["doorId"] = "${viewBinding.cabinet.tag}"  //柜子id
        map["mTag"] = 2
        map["mVerTyps"] = 0
        if (ChemicalApp.confs!!.verifyType == "1,2" || ChemicalApp.confs!!.verifyType == "2,1") {
            //人脸+刷卡
            map["hides"] = 1   //隐藏扫码
//            UiManager.switcher(this, map, TwoPersonActivity::class.java)
        } else if (ChemicalApp.confs!!.verifyType == "1,3" || ChemicalApp.confs!!.verifyType == "3,1") {
            //人脸+扫码
            map["hides"] = 2   //隐藏刷卡
//            UiManager.switcher(this, map, TwoPersonActivity::class.java)
        } else if (ChemicalApp.confs!!.verifyType == "2,3" || ChemicalApp.confs!!.verifyType == "3,2") {
            map["hides"] = 3   //隐藏扫码
//            UiManager.switcher(this, map, SwipeCodeTwoActivity::class.java)
        } else {
            //人脸+刷卡+扫码
            map["hides"] = 4
//            UiManager.switcher(this, map, TwoPersonActivity::class.java)
        }
        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)
    }

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

    private fun initAdapter() {
        //入库列表信息
        viewBinding.rvInventory?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvInventory?.adapter = mAdapter

        //待入库清单
        viewBinding.recyclerViewList?.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerViewList?.adapter = mAdapterChemicals
        mAdapterChemicals.setOnItemChildClickListener { adapter, view, position ->
            // 在这里处理子View的点击事件
            when (view.id) {
                R.id.imgDelete -> {
                    mAdapterChemicals.data.removeAt(position)
                    mStockModelList = mAdapterChemicals.data
                    RcLog.info("=======删除前${mStockModeBean.stockModelList.size}")
                    mStockModeBean.stockModelList = mStockModelList
                    if (mAdapterChemicals.data.size == 0) {
                        viewBinding.imgPosition.visibility = View.VISIBLE
                    }
                    RcLog.info("=======删除后${mStockModeBean.stockModelList.size}")
                    mAdapterChemicals.notifyItemRemoved(position)
                }
            }
        }
        //列表信息点击
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.data.forEach { it.isType = false }
            mAdapter.data[position].isType = true
            mAdapter.notifyDataSetChanged()
            getStockWait(mAdapter.data[position].waitId, mAdapter.data[position])
        }
    }


    private fun getStockWait(waitId: String, hxpStockWaitListBean: HxpStockWaitListBean) {
        showLoading("查询中...")
        val disposable = ApiRepository.getStockWaitDetails(waitId)
            .subscribe({ data ->
                dismissLoading()
                mUnifiedVerBean = data
                //当前需要生成的化学品信息
                modelA = hxpStockWaitListBean
                putDateInfo()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun subAddData(types: Int) {
        try {// 从 SharedPreferences 中取出集合
            val retrievedList =
                SharedPreferencesHelper.getList(this@WarehousingActivity)
            if (retrievedList != null && retrievedList.size > 0) {
                SharedPreferencesHelper.clearList(this@WarehousingActivity)
            }
        } catch (e: Exception) {

        }
        showLoading("入库中...")
        val disposable = ApiRepository.stockWaitAdd(mStockModeBean)
            .subscribe({ data ->
                dismissLoading()

                if (types == 0) {
                    MediaPlayerHelper.playRawMp3(this, R.raw.qingjianghuaxuekaimen)
                    customDialogView(1, "请将化学品放入化学品柜")
                } else {
                    MediaPlayerHelper.playRawMp3(this, R.raw.guimenyikai)
                    customDialogView(1, "柜门已开，请将化学品放入化学品柜")
                }
                mAdapterChemicals.data.clear()
                mStockModelList.clear()
                viewBinding.lintView.visibility = View.VISIBLE
                viewBinding.imgPosition.visibility = View.VISIBLE
                mAdapterChemicals.notifyDataSetChanged()
                getRelList() //刷新页面
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    private var modelA: HxpStockWaitListBean? = null
    private var mHandler: Handler = Handler(Looper.getMainLooper())
    private fun putDateInfo() {
//        val netContent = modelA!!.chemicalDensity * modelA!!.normsNum  // 净量 = 密度*规格
        var density = "${modelA!!.normsNum}${modelA!!.normsUnit}/${modelA!!.applyUnit}"
        mLabelDialog =
            LabelDialog(
                this,
                "${modelA!!.applyNum.subtract(BigDecimal(modelA!!.stockNum!!))}",
                mLayers,
                density,
                modelA!!.chemicalName,
                object : LabelDialog.IRfidClick {
                    override fun onItemClick(
                        modelList: MutableList<StockDetailsModel>?,
                        layer: Int
                    ) {
                        mStockDetailsModel = modelList
                        mLayersTow = layer
                        if (modelList == null) {
                            //取消
                        } else {
                            //确定  链接蓝牙
                            mWeighDialog = WeighDialog(this@WarehousingActivity, density,
                                object : WeighDialog.IViewLint {
                                    override fun weighingView(weighingValue: EditText) {
//                                        showLoading("蓝牙连接中...")
                                        mWeighingValue = weighingValue
                                        RcLog.info("========${mWeighingValue!!.isEnabled}")
                                        if (mWeighingValue!!.isEnabled) {
                                            // EditText允许输入
                                            // 在这里执行相应的操作
                                            weiView()
                                        } else {
                                            // EditText禁止输入
                                            // 在这里执行相应的操作
//                                            connectToDeviceWithTimeout()
                                            isClisLit = false
                                            lifecycleScope.launch {
                                                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() {
                                        isClisLit = true
                                        closEndTwo()
                                    }

                                    override fun onMovement() {
                                        weiView()
                                    }

                                    override fun onTimerReply() {
                                        stopCountDown()
                                    }
                                })
                            mWeighDialog!!.show()

                            mHandler.postDelayed({
                            }, 1000 * 60) // 60秒后关闭对话框
                        }
                    }

                    override fun onPrint(
                        tagCode: String,
                        wxCode: String,
                        rfidCode: String,
                        position: Int
                    ) {
                        RcLog.info("=======打印标记${mUnifiedVerBean.qrCodePrint} $position")
                        getCheckRfids(rfidCode, tagCode, wxCode, position)
                    }

                    override fun opTageCode(data: MutableList<StockDetailsModel>, layer: Int) {
                        if (mUnifiedVerBean.qrCodePrint) {
                            showLoading("打印中，请稍等")
                            mStockDetailsModel = data
                            mLayer = layer
                            mPrintTag = mStockDetailsModel!!.size
                            handlerPrint.startTask(taskPrint, 3000)
                        } else {
                            //打印完成
                            mLabelDialog!!.printingCom()
                        }
                    }
                })
        mLabelDialog!!.show()


    }


    private fun weiView() {
        showToast("请手动输入")
        mJoinType = 2
        mWeighingValue!!.isEnabled = true
        mWeighingValue!!.requestFocus()
    }

    private suspend fun connectToDeviceWithTimeout() {
        showToast("连接中...", Toast.LENGTH_SHORT)
        RcLog.info("===================weight=======1")

//        lifecycleScope.launch  {
        RcLog.info("===================weight=======2")
        val deviceAddress = withContext(Dispatchers.IO) {
            BluetoothConnectionManager.getDeviceAddress()
        }
        RcLog.info("===================weight=======2")
        if (deviceAddress != null) {
            val socket = withContext(Dispatchers.IO) {
                BluetoothConnectionManager.connectToDevice(deviceAddress)
            }
            RcLog.info("===================weight=======3")
            if (socket != null) {
                // 连接成功后的处理逻辑
                // 在这里使用返回的 BluetoothSocket 对象进行后续操作
                RcLog.info("===================weight=======4")
                MediaPlayerHelper.playRawMp3(this@WarehousingActivity, R.raw.qing_zheng_zhong)
                // 连接成功后的处理逻辑
                withContext(Dispatchers.Main) {
                    do {
//                            try {
                        val inputStream = socket!!.inputStream
                        val bt = ByteArray(1024)
                        val content = inputStream!!.read(bt)
                        if (content != null && content > 0) {
                            val contents = String(
                                bt,
                                0,
                                content,
                                StandardCharsets.UTF_8
                            )
                            val split = contents.split("\n")
                            val weight = split[0].trim()
                            RcLog.info("===================称重未处理之前=======$contents")
                            RcLog.info("===================weight=======$weight")
                            RcLog.info("=====称重数据$weight $taskStarted  ${mWeighingValue!!.text.toString()}")
                            if (weight.toDouble() > 2999) {
                                turnOffWeighing()
                            } else {
                                if (weight.toDouble() > 0) {
                                    if (mWeighingValue!!.text.toString().trim()
                                            .isNotEmpty()
                                    ) {
                                        if (weight.toDouble() == mWeighingValue!!.text.toString()
                                                .trim().toDouble()
                                        ) {
                                            if (taskStarted == false) {
                                                taskStarted = true
                                                RcLog.info("=====执行了")
                                                socket.close()
                                                delayedTaskToUpdateUI()
                                                break
                                            }
                                        }
                                    }
                                    mWeighingValue!!.setText("$weight")
                                } else {
                                    mWeighingValue!!.setText("")
                                }
                            }
                            delay(200)
                        } else {
//                                    jobTow?.cancel()
                            showToast("请手动输入")
                            weiView()
                            break
                        }
//                            } catch (e: Exception) {
//                                jobTow?.cancel()
//                                weiView()
//                                break
//                            }
                    } while (true)
                }

            } else {
                RcLog.info("===================weight=======4")
                // 连接失败的处理逻辑
                showToast("连接失败或超时", Toast.LENGTH_SHORT)
                weiView()
            }
        } else {
            // 根据设备名称获取的设备地址为空，处理无法找到设备的情况
            showToast("找不到设备", Toast.LENGTH_SHORT)
            weiView()
        }
//        }
    }

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

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

    }

    private fun closEnd() {
//        jobTow?.cancel()
        mWeighDialog!!.dismiss()


        val weigh =
            mWeighingValue!!.text.toString().trim()  //称重后的重量
        if (weigh.isEmpty()) {
            showToast("未称重")
            return
        }
        if (weigh.toDouble() <= 0) {
            showToast("当前重量有误")
            return
        }
        val netContent =
            modelA!!.chemicalDensity * modelA!!.normsNum  // 净含量=密度*规格
        var belongId = ""
        var belongName = ""
        var belongType = 2
        if (modelA!!.topicGroup) {
            belongId = modelA!!.topicGroupId
            belongName = modelA!!.topicGroupName
            belongType = 1
        } else {
            belongId = modelA!!.applyUserId
            belongName = modelA!!.applyUserName
        }
        if (mListData != null && mListData!!.size == 0) {
            showToast("化学品柜 未到找")
            return
        }
        var model = StockModel(
            belongId,
            belongName,
            belongType,  //死值
            modelA!!.buildId,
            modelA!!.buildName,
            mCabinetId,  //柜子信息
            mCabinetName,
            modelA!!.casNum,
            modelA!!.chemicalCategory.toInt(),
            modelA!!.chemicalId,  //化学品id
            modelA!!.chemicalLevel,
            modelA!!.chemicalName,
            "${mStockDetailsModel!!.size}",
            modelA!!.chemicalPurity,
            modelA!!.deptId,
            modelA!!.deptName,
            viewBinding.cabinet.tag.toString(),
            mDoorName,
            modelA!!.factory,
            modelA!!.floorId,
            modelA!!.floorName,
            true,   //11
            mJoinType,   //入库方式1 称重，2 录入
            "", //视频地址
            mLayersTow,     //当前选择得
            mLayers,     //一共几层
            modelA!!.applyNum,
            modelA!!.applyUnit,
            modelA!!.normsNum,
            modelA!!.normsUnit,
            mStockDetailsModel,   //每一条信息
            2,
            modelA!!.subId,
            modelA!!.subName,
            modelA!!.roomNum,
            modelA!!.waitId,
            mWeighingValue!!.text.toString().toDouble(),
            netContent,
            expireTime = modelA!!.expireTime
        )
        verificationData(model)
    }


    //校验当前数据是否合理
    private fun verificationData(model: StockModel) {
        showLoading("查询中...")
        val disposable = ApiRepository.addStockCheck(model)
            .subscribe({ data ->
                dismissLoading()
                mStockModelList.add(model)
                mStockModeBean = StockModeBean(mStockModelList)
                //创建需要提交的数据源
                mAdapterChemicals.updateData(mLayers)
                //创建需要提交的数据源
                if (mAdapterChemicals.data != null && mAdapterChemicals.data.size > 0) {
                    mAdapterChemicals.setList(mStockModelList)
                } else {
                    viewBinding.lintView.visibility = View.GONE
                    mAdapterChemicals.setNewInstance(mStockModelList.toMutableList())
                }
                viewBinding.imgPosition.visibility = View.GONE
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

//    private fun getControlConfigs(chemicalNumber: String) {
//        showLoading("提交中...")
//        val disposable = ApiRepository.controlConfigs(modelA.chemicalLevel)
//            .subscribe({ data ->
//                dismissLoading()
//                mChemicalConfsBean = data
//            }, { throwable ->
//                showNetError(throwable)
//                dismissLoading()
//            })
//        addDisposable(disposable)
//    }

    private fun getCheckRfids(rfid: String, tagCode: String, wxCode: String, position: Int) {
        showLoading("查询标签...")
        val disposable = ApiRepository.checkRfids(rfid)
            .subscribe({ data ->
                dismissLoading()
                RcLog.info("===========查询成功$data")
                if (data) {
                    customDialogView(2, "rfid标签不能重复,请重新扫描")
                    mLabelDialog!!.getRfidTag(position)
                } else {
                    if (mUnifiedVerBean.qrCodePrint) {
                        //需要打印
                        val print = PrintBean()
                        print.tag = tagCode  //化学品编码
                        print.wxCode = wxCode
                        print.name = modelA!!.chemicalName!! //化学品名称
                        if (modelA!!.casNum != null) {
                            print.casNo = modelA!!.casNum!!  //cas号
                        } else {
                            print.casNo = ""
                        }

                        if (modelA!!.topicGroup) {
                            print.person = modelA!!.topicGroupName //归属人
                        } else {
                            print.person = modelA!!.applyUserName //归属人
                        }
                        //管控 1     非管控  2
                        if (modelA!!.chemicalLevel == 1) {
                            print.level = "管控"
                        } else {
                            print.level = "非管控"
                        }
                        //
                        print.types = "${modelA!!.chemicalCategoryName}"
                        labelPrint(print)
                    }
                }
            }, { throwable ->
                showNetError(throwable)
                mLabelDialog!!.getRfidTag(position)
                dismissLoading()
            })
        addDisposable(disposable)
    }

    /**
     * 标签打印
     * 化学品信息
     */
    private fun labelPrint(printDate: PrintBean) {
        val thread = Thread {
            try {
                if (!pritBot) {
                    try {//关闭打印
                        h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x0FE6,PID:0x811E", 1)
                    } catch (e: Exception) {
                        RcLog.info("初始化异常")
                    }
                }
                pritBot = true
                val bitmap = BitmapUtils.generateBitmap(printDate)  //图片信息
                AutoReplyPrint.INSTANCE.CP_Label_BackPaperToPrintPosition(h)
                AutoReplyPrint.CP_Pos_PrintRasterImageFromData_Helper.PrintRasterImageFromBitmap(
                    h,
                    bitmap!!.width,
                    bitmap.height,
                    bitmap,
                    AutoReplyPrint.CP_ImageBinarizationMethod_Thresholding,
                    AutoReplyPrint.CP_ImageCompressionMethod_None
                )
                AutoReplyPrint.INSTANCE.CP_Label_PagePrint(h, 1)
                val result = AutoReplyPrint.INSTANCE.CP_Pos_HalfCutPaper(h) //全切
                if (result) {
                    //打印成功
                    MediaPlayerHelper.playRawMp3(this, R.raw.huaxuepinbiaoqian)
//                    closePort()
//                    customDialogView(0, "请将标签粘贴在化学品外包装上")
                } else {
                    //失败
//                    closePort()
                }
            } catch (e: Exception) {
//                closePort()
                // 监听子线程中抛出的异常
            }
        }
        thread.start() // 启动子线程
    }

    private fun closePort() {
        if (h !== Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h)
            h = Pointer.NULL
        }
    }

    private val taskPrint = Runnable {

        if (mPrintTag == 0) {
            //全部打印完成  关闭 并且调用下一步业务
            RcLog.info("=====csd====打印完成$mPrintTag")
            dismissLoading()
            handlerPrint.stopAllTasks()
            //打印完成
            mLabelDialog!!.printingCom()
        } else {
            val print = PrintBean()
            print.tag = mStockDetailsModel!![mPrintTag - 1].tagCode!!  //化学品编码
            print.wxCode = mStockDetailsModel!![mPrintTag - 1].wxCode!!  //化学品编码
            print.name = modelA!!.chemicalName!! //化学品名称
            if (modelA!!.casNum != null) {
                print.casNo = modelA!!.casNum!!  //cas号
            } else {
                print.casNo = ""
            }

            if (modelA!!.topicGroup) {
                print.person = modelA!!.topicGroupName //归属人
            } else {
                print.person = modelA!!.applyUserName //归属人
            }
            //管控 1     非管控  2
            if (modelA!!.chemicalLevel == 1) {
                print.level = "管控"
            } else {
                print.level = "非管控"
            }
            //
            print.types = "${modelA!!.chemicalCategoryName}"
            labelPrint(print)
        }
        mPrintTag--

    }

    //查询存储位置  默认第一个
    private fun getCabinet(subId: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(subId)
            .subscribe({ data ->
                dismissLoading()
                mListData = data
                viewBinding.cabinet.text =
                    "存储位置:${mListData!![0].cabinetName}-${mListData!![0].cabinetDoorVoList[0].doorName}"
                viewBinding.cabinet.tag =
                    "${mListData!![0].cabinetDoorVoList[0].doorUniqueId}"
                mCabinetId = mListData!![0].cabinetId
                mCabinetName = mListData!![0].cabinetName
                mDoorName = mListData!![0].cabinetDoorVoList[0].doorName
                mDoorId = mListData!![0].cabinetDoorVoList[0].doorUniqueId
                mCabinetLockVoList = mListData!![0].cabinetDoorVoList[0].cabinetLockVoList
                mLayers = mListData!![0].cabinetDoorVoList[0].doorLayers   //当前柜子一共几层
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }


    var taskStarted = false

    // 声明一个全局的 Handler 变量
    private var mHandlerTime: Handler? = null

    // 在需要执行任务的地方调用这个函数
    private fun delayedTaskToUpdateUI() {
        // 初始化 Handler，并关联到主线程 Looper
        if (isClisLit == false) {
            mHandlerTime = Handler(Looper.getMainLooper())

            // 定义一个延迟执行的任务
            val updateUITask = Runnable {
                RcLog.info("=====执行了")
                // 在这里执行更新 UI 的操作
                // 例如，更新 TextView 的文本
                // textView.text = "Updated text"
                closEnd()
                taskStarted = false
                // 执行完更新操作后，可以关闭 Handler
                mHandlerTime?.removeCallbacksAndMessages(null)
                mHandlerTime = null
            }
            // 延迟 3 秒执行任务
            mHandlerTime?.postDelayed(updateUITask, 3300)
        }

    }


    //超过量程
    private fun turnOffWeighing() {
        showToast("超过量程,手动输入")
        mJoinType = 2
        mWeighingValue!!.isEnabled = true

    }

    // 获取实验室基本信息
    private fun getRelList() {
        val disposable = ApiRepository.getRelList(ChemicalApp.subjectId!!)
            .subscribe({ data ->
                mChemicalInfoBean = data
                getCabinet(mChemicalInfoBean!!.subId)
                waitList()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }


    //化学品/cas搜索
    private fun waitList() {
        val map = mutableMapOf<String, Any>()
        map["subId"] = mChemicalInfoBean!!.subId
        val searchValue = viewBinding.searchValue.text.toString() //输入内容
        if (searchValue.isNotEmpty()) {
            map["searchValue"] = searchValue
        }
        try {
            val tag = viewBinding.value.tag  //类别id
            if (tag != null) {
                map["chemicalCategory"] = tag
            }
        } catch (e: Exception) {
        }
        map["page"] = page
        map["pageSize"] = pageSize

        showLoading("加载中...")
        val disposable =
            ApiRepository.waitList(map)
                .subscribe({ data ->
                    dismissLoading()
                    //   current 当前页    pages 共计多少页
                    mDataPage = data.pages  //总页
                    if (data.records != null && data.records.size == 0) {
                        mAdapter.data.clear()
                        mAdapter.notifyDataSetChanged()
                        initPagesView(data.pages)
                    }
                    RcLog.info("===条==${data.pages}    ===条==${data.current}")
                    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 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) {
        RcLog.info("======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 getOptions() {
        showLoading("查询中...")
        val disposable = ApiRepository.getOptions("chemicals_category")
            .subscribe({ data ->
                dismissLoading()
                val chemDialog = ChemicalTypeDialog(
                    this,
                    data.toMutableList(),
                    object : ChemicalTypeDialog.IonClickListener {
                        override fun onClick(data: ChemicalTypeBean) {
                            viewBinding.value.text = "${data.label}"
                            viewBinding.value.tag = "${data.value}"
                        }
                    })
                if (!chemDialog.isShowing) {
                    chemDialog.show()
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    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["lockNum"] = "$mLockNum"
//        map["lockNum"] = "guisuo001"
        map["lockNumList"] = mLockStr
        map["operationType"] = 2
        if (ChemicalApp.subRoom != null) {
            map["subRoom"] = ChemicalApp.subRoom!!
        }
        map["type"] = true
        try {// 从 SharedPreferences 中取出集合
            val retrievedList = SharedPreferencesHelper.getList(this)
            if (retrievedList != null && retrievedList.size > 0) {
                RcLog.info("从本地取出得双人信息${retrievedList[0].name}")
                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) {

        }
        showLoading("加载中...")
        val disposable = ApiRepository.lockOperate(map)
            .subscribe({ data ->
                dismissLoading()
                val containsFalse =
                    mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
                if (containsFalse) {
                    showLoading("查询中...")
                    startCountdownLock()
                    handlerUtil.startTask(task, 1000)
                } else {
                    dismissLoading()
                    //开锁成功
                    subAddData(1)
                    handlerUtil.stopAllTasks()
                    countdownTimer?.cancel()
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)


    }

    private var countdownTimer: CountDownTimer? = null
    private fun startCountdownLock() {
        val totalTime = 30 * 1000 // 30秒
        val interval = 1000 // 每秒更新一次
        if (countdownTimer != null) {
            countdownTimer!!.cancel()
        }
        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()
                viewBinding.butOpen.visibility = View.VISIBLE
                showToast("开锁超时,可重新操作")
                dismissLoading()
                handlerUtil.stopAllTasks()
                // 在这里执行合适的操作，比如退出应用程序
            }
        }

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

    override fun onResume() {
        super.onResume()
        try {
            if (Constants.AUTHENTICATION) {

                try {// 从 SharedPreferences 中取出集合
                    val retrievedList =
                        SharedPreferencesHelper.getList(this@WarehousingActivity)
                    if (retrievedList != null && retrievedList.size > 0) {
                        RcLog.info("===a===${retrievedList[0].userId}")
                        if (mStockModelList != null && mStockModelList.size > 0) {
                            mStockModelList.forEach {
                                it.oneUserId = "${retrievedList[0].userId}"
                                it.oneUserName = "${retrievedList[0].name}"
                                it.twoUserId = "${retrievedList[1].userId}"
                                it.twoUserName = "${retrievedList[1].name}"
                            }
                        }
//                        // 清空 SharedPreferences 中的集合
//                        SharedPreferencesHelper.clearList(this@WarehousingActivity)
                    }
                } catch (e: Exception) {

                }
                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                    mCabinetLockVoList!!.forEach { it ->
                        mLockStr.clear()
                        when (it.unlockingMethod) {
                            2 -> { //智能锁
                                mLockStr.add("${it.lockNum}")
                            }
                        }
                    }
                } else {
                    mLockStr.clear()
                }
                if (mLockStr != null && mLockStr.size > 0) {
                    openLock(mLockStr)
                } else {
                    subAddData(0)
                }
            }
            Constants.AUTHENTICATION = false
        } catch (e: Exception) {
            Constants.AUTHENTICATION = false
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        try {
            handlerUtil.stopAllTasks()
            mHandler.removeCallbacksAndMessages(null)
            countdownTimer?.cancel()
            closePort()
        } catch (e: Exception) {
        }
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
    }

    //=================开锁流程================
    private val task = Runnable {
        //判断所有的锁开锁成功
        val containsFalse = mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
        RcLog.info("=======查询调用开锁状态====$containsFalse")
        if (containsFalse) {
            getLocks()
        } else {
            dismissLoading()
            //开锁成功
            subAddData(1)
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
        }
    }


    //查询开锁信息
    private fun getLocks() {
        mCabinetLockVoList!!.forEachIndexed { index, fruit ->
            if (!fruit.isOk && 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)
    }

    /**
     * 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 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") }
    }

}