package com.example.chemical.ui.discard

import android.content.IntentFilter
import android.hardware.usb.UsbManager
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 androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityWasteChemicalsBinding
import com.example.chemical.iml.IBankTeps
import com.example.chemical.receiver.OnSerialScanListener
import com.example.chemical.receiver.PortScanHelper
import com.example.chemical.receiver.UsbReceiver
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.adapter.WasteChemicalsAdapter
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.ui.verify.TwoVerificationActivity
import com.example.chemical.utils.*
import com.example.chemical.weidith.CustomDialog
import com.example.chemical.weidith.DiscardDialog
import com.example.chemical.weidith.EdContDialog
import com.example.chemical.weidith.StorageDialog
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.*
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException

//废弃-  化学品
class WasteChemicalsActivity : BaseCountDownActivity<ActivityWasteChemicalsBinding>() {
    private val mAdapter by lazy { WasteChemicalsAdapter(this) }
    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数
    private lateinit var mDataBean: ReturnDetailsBean //查询返回单挑信息
    private lateinit var mGiveBackBean: GiveBackBean //归还参数
    private lateinit var timeUpdater: TimeUpdater
    private var mCabinetId: String? = null
    private var mDoorId: String? = null
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()   //需要打开得柜锁数量
    private val handlerUtil = HandlerUtil.getInstance()
//    private var mWasteChemicalsListBean: WasteChemicalsListBean? = null

    private var mPages = 1  //总页码
    private var mDataPage = 10  //返回得总条数
    private var page = 1
    private var pageSize = 10

    private var mTyps = 1

    //    private var mStockModelList = mutableListOf<ReturnDetailsBean>()
    private var mIsLock = false //是否打开过锁  只要是只能锁被打开 就需要进行异常数据上报

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        inAdapter()
        Constants.VIEW_TYPE = true
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
                ChemicalApp.subjectId = null
//                HttpClient.token = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }

        viewBinding.tvReturn.setOnClickListener {
//            if (mStockModelList != null && mStockModelList.size > 0) {
            if (mIsLock) {
                outTimeWarnData()
            } else {
                finish()
            }

        }

        //废弃  不需要称重
        viewBinding.butDiscard.setOnClickListener {
            if (viewBinding.linTow.visibility == View.VISIBLE) {
                val discardDialog = DiscardDialog(
                    this,
                    "${mDataBean.surplus}${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 = 1,
                                useStatus = 3,
                                remark = "repeal",
                                weigh = 1.0,
                                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@WasteChemicalsActivity)
                                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@WasteChemicalsActivity)
                                }
                            } catch (e: Exception) {

                            }
                            //chemical/aio/giveBack
                            showLoading("加载中...")
                            val disposable = ApiRepository.giveBack(mGiveBackBean)
                                .subscribe({ data ->
                                    dismissLoading()
                                    MediaPlayerHelper.playRawMp3(
                                        this@WasteChemicalsActivity,
                                        R.raw.feiqichuku
                                    )
                                    customDialogView(1, "已废弃出库,请及时进行废弃回收")
                                    viewBinding.relOne.visibility = View.GONE
                                    viewBinding.lint3.visibility = View.GONE
                                    viewBinding.linTow.visibility = View.GONE
                                    viewBinding.lintComplete.visibility = View.VISIBLE
                                    viewBinding.surplusTow.text =
                                        "废弃量：${mDataBean.surplus}${mDataBean.specUnit}"
                                    mHandleScanEvent = false
                                    mIsLock = false
                                    stockDetailsList()
                                }, { throwable ->
                                    dismissLoading()
                                    showNetError(throwable)

                                })
                            addDisposable(disposable)
                        }

                        override fun onTimerReply() {
                            stopCountDown()
                        }
                    })
                if (!this.isFinishing && !this.isDestroyed) {
                    discardDialog.show()
                }
//                discardDialogShow()
            } else {
                showToast("请扫描或点击需要废弃的化学品")
            }
        }

        viewBinding.butOpen.setOnClickListener {
            //再次开门
            if (mLockStr != null && mLockStr.size > 0) {
                openLock(mLockStr)
            } else {
                upList(
                    mDataBean!!.cabinetName,
                    mDataBean!!.doorName,
                    mDataBean!!.layers
                )
            }
        }
        //化学品柜 查询
        viewBinding.relCabinet.setOnClickListener {
            getCabinet()
        }

        viewBinding.edCont.setOnClickListener {
            val edDialog = EdContDialog(this, object : EdContDialog.IClickLit {
                override fun onClickClo(str: String?) {
                    if (str != null) {
                        viewBinding.edCont.text = "$str"
                    } else {
                        stockDetailsList()
                    }
                }

            })
            edDialog.show()
        }

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

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

    }

    override fun initData() {
        super.initData()

        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()
        initTitle()
        stockDetailsList()
        viewBinding.butUpper.setOnClickListener {
            //上一页
            if (mDataPage != 0) {
                if (mDataPage != 0) {
                    if (page != 1) {
                        page--
                        stockDetailsList()
                    }
                }
            }
        }

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

    private fun outTimeWarnData() {
        var mStockModelList = mutableListOf<TimeWarBean>()
        val map = mutableMapOf<String, Any>()
        val bean = TimeWarBean()
        bean.floorId = ChemicalApp.labInfo!!.floorId
        bean.floorName = ChemicalApp.labInfo!!.floorName
        bean.subId = ChemicalApp.labInfo!!.subjectId
        bean.subName = ChemicalApp.labInfo!!.subjectName
        bean.subRoom = ChemicalApp.labInfo!!.room
        bean.cabinetName = mDataBean.cabinetName
        bean.doorName = mDataBean.doorName
        bean.deptName = ChemicalApp.confs!!.deptName
        bean.stockTypeStr = "废弃"
        mStockModelList.add(bean)
        showLoading("提交中...")
        map["stockModelList"] = mStockModelList  //管控类型
        val disposable =
            ApiRepository.outTimeWarn(map)
                .subscribe({ data ->
                    dismissLoading()
                    finish()
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)

                })
        addDisposable(disposable)
    }

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


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

    //查询柜子  存储位置  默认第一个
    private fun getCabinet() {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(ChemicalApp.subjectId!!)
            .subscribe({ data ->
                dismissLoading()
                val storageDialog =
                    StorageDialog(ct = this,
                        listData = data!!,
                        lint = object : StorageDialog.IonClickListener {
                            override fun onClick(
                                cabinetId: String,
                                cabinetName: String,
                                doorName: String,
                                doorId: String,
                                cabinetLockVoList: List<LockVoListBean>,
                                layers: Int,
                                lockNum: String,
                            ) {
                                mCabinetId = cabinetId
                                mDoorId = doorId
                                viewBinding.cabinetName.text = "$doorName"
                            }

                            override fun onClose() {
                                if (mCabinetId != null) {
                                    mCabinetId = null
                                    mDoorId = null
                                    viewBinding.cabinetName.text = "化学品柜"
                                }
                            }
                        })
                if (!this.isFinishing && !this.isDestroyed) {
                    storageDialog.show()
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    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 discardDialogShow() {
        if (mDataBean.chemicalLevel == 1) {
            val discardDialog = DiscardDialog(
                this,
                "${mDataBean.surplus}${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 = 1,
                            useStatus = 3,
                            remark = "repeal",
                            weigh = 1.0,
                            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@WasteChemicalsActivity)
                            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@WasteChemicalsActivity)
                            }
                        } catch (e: Exception) {

                        }
                        //chemical/aio/giveBack
                        showLoading("加载中...")
                        val disposable = ApiRepository.giveBack(mGiveBackBean)
                            .subscribe({ data ->
                                dismissLoading()
                                MediaPlayerHelper.playRawMp3(
                                    this@WasteChemicalsActivity,
                                    R.raw.feiqichuku
                                )
                                customDialogView(1, "已废弃出库,请及时进行废弃回收")
                                viewBinding.relOne.visibility = View.GONE
                                viewBinding.lint3.visibility = View.GONE
                                viewBinding.linTow.visibility = View.GONE
                                viewBinding.lintComplete.visibility = View.VISIBLE
                                viewBinding.surplusTow.text =
                                    "废弃量：${mDataBean.surplus}${mDataBean.specUnit}"
                                mHandleScanEvent = false
                                mIsLock = false
                                stockDetailsList()
                            }, { throwable ->
                                dismissLoading()
                                showNetError(throwable)

                            })
                        addDisposable(disposable)
                    }

                    override fun onTimerReply() {
                        stopCountDown()
                    }
                })
            if (!this.isFinishing && !this.isDestroyed) {
                discardDialog.show()
            }
        } else {
            //调用归还API
            mGiveBackBean = GiveBackBean(
                id = mDataBean.id,
                stockId = mDataBean.id,
                stockDetailsId = mDataBean.stockDetailsId,
                returnType = 1,
                useStatus = 3,
                remark = "repeal",
                weigh = 1.0,
                cabinetId = mDataBean.cabinetId,
                cabinetName = mDataBean.cabinetName,
                doorId = mDataBean.doorId,
                doorName = mDataBean.doorName,
                layers = mDataBean.layers.toInt()
            )

            try {// 从 SharedPreferences 中取出集合
                val retrievedList = SharedPreferencesHelper.getList(this@WasteChemicalsActivity)
                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@WasteChemicalsActivity)
                }
            } catch (e: Exception) {

            }

            //chemical/aio/giveBack
            showLoading("加载中...")
            val disposable = ApiRepository.giveBack(mGiveBackBean)
                .subscribe({ data ->
                    dismissLoading()
                    MediaPlayerHelper.playRawMp3(
                        this@WasteChemicalsActivity,
                        R.raw.feiqichuku
                    )
                    customDialogView(1, "已废弃出库,请及时进行废弃回收")
                    viewBinding.relOne.visibility = View.GONE
                    viewBinding.lint3.visibility = View.GONE
                    viewBinding.linTow.visibility = View.GONE
                    viewBinding.lintComplete.visibility = View.VISIBLE
                    viewBinding.surplusTow.text = "废弃量：${mDataBean.surplus}${mDataBean.specUnit}"
                    mHandleScanEvent = false
                    mIsLock = false
                    stockDetailsList()
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)
                })
            addDisposable(disposable)
        }

    }

    private fun stockDetailsList() {
        showLoading("查询中...")
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["subId"] = "${ChemicalApp.subjectId!!}"
        mutableMap["status"] = "1"
        if (mCabinetId != null) {
            mutableMap["cabinetId"] = "$mCabinetId"
        }

        if (mDoorId != null) {
            mutableMap["doorId"] = "$mDoorId"
        }

        var toString = viewBinding.edCont.text.toString()
        RcLog.info("======ceshi======$toString")
        if (toString.isNotEmpty()) {
            mutableMap["searchValue"] = "$toString"
        }
        mutableMap["page"] = "$page"
        mutableMap["pageSize"] = "$pageSize"
        val disposable =
            ApiRepository.stockDetailsList(mutableMap)
                .subscribe({ data ->
                    dismissLoading()
                    if (mAdapter.data != null) {
                        mAdapter.data.clear()
                        mAdapter.notifyDataSetChanged()
                        initPagesView(data.pages)
                    }
                    mDataPage = 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 inAdapter() {
        viewBinding.rvView?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvView?.adapter = mAdapter

        //点击左侧进行 废弃
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.data.forEach { it.isType = false }
            mAdapter.data[position].isType = true
            mAdapter.notifyDataSetChanged()
//            mDataBean = mAdapter.data[position]
            try {
                codeDateIn(mAdapter.data[position].tagCode)
            } catch (e: Exception) {
                showToast("参数异常")
            }
        }
    }

    private fun upList(cabinetName: String, doorName: String, layers: String) {
        viewBinding.relOne.visibility = View.GONE
        viewBinding.linTow.visibility = View.GONE
        viewBinding.lintComplete.visibility = View.GONE
        viewBinding.cabinet.text =
            "${cabinetName}-${doorName}-${layers}层"
    }

    private fun upListTwo(cabinetName: String, doorName: String, layers: String) {
        viewBinding.relOne.visibility = View.GONE
        viewBinding.lint3.visibility = View.VISIBLE
        viewBinding.linTow.visibility = View.GONE
        viewBinding.lintComplete.visibility = View.GONE
        viewBinding.cabinet.text =
            "${cabinetName}-${doorName}-${layers}层"
    }

    private fun upView() {
        viewBinding.relOne.visibility = View.GONE
        viewBinding.lint3.visibility = View.GONE
        viewBinding.linTow.visibility = View.VISIBLE
        viewBinding.lintComplete.visibility = View.GONE
        viewBinding.chemicalName.text = "${mDataBean.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.surplus.text = "${mDataBean.surplus}${mDataBean.specUnit}"
        if (mDataBean.expireTime != null) {
            viewBinding.expireTime.text = "${mDataBean.expireTime}"
        }
        viewBinding.storage.text =
            "${mDataBean.cabinetName}-${mDataBean.doorName}-${mDataBean.layers}层"
        if (mDataBean.expireStatus == 1) {
            viewBinding.tvNoName.visibility = View.VISIBLE
        }

    }

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


    //通过化学品code码确定当前是否需要双人认证业务
    private fun codeDateIn(tagCode: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.discardDetail(tagCode)
            .subscribe({ data ->
                dismissLoading()
                mDataBean = data
                if (mDataBean.verify) {
                    //需要双人认证
                    if (ChemicalApp.confs!!.verifyType.length == 1) {
                        val map = mutableMapOf<String, Any>()
                        map["chemicalLevel"] = mDataBean.chemicalLevel  //管控类型
//                        map["doorId"] = "$mDoorId"  //柜子id
                        map["doorId"] = "${data.doorId}"  //柜子id
                        map["mTag"] = 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 {
                    mTyps = 2
                    showLoading("查询中...")
                    val disposable =
                        ApiRepository.getCabinetLock(mDataBean!!.doorId)
                            .subscribe({ data ->
                                dismissLoading()
                                mCabinetLockVoList = data
                                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) {
                                        viewBinding.butOpen.visibility = View.VISIBLE
                                        openLock(mLockStr)
                                    } else {
                                        viewBinding.butOpen.visibility = View.GONE
                                        //没有锁 直接显示 需要扫描化学品信息
                                        upListTwo(
                                            mDataBean!!.cabinetName,
                                            mDataBean!!.doorName,
                                            mDataBean!!.layers
                                        )
                                    }
                                } else {
                                    //没有锁 直接显示 需要扫描化学品信息
                                    upListTwo(
                                        mDataBean!!.cabinetName,
                                        mDataBean!!.doorName,
                                        mDataBean!!.layers
                                    )
                                }
                            }, { throwable ->
                                dismissLoading()
                                showNetError(throwable)
                            })
                    addDisposable(disposable)
                }

            }, { throwable ->
                dismissLoading()
                throwableView(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") }
    }

    private val mPortScanHelper by lazy {
        PortScanHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (!mHandleScanEvent) {
                    if (content.isNotBlank()) {
                        RcLog.info("==========当前usb返回参数$content  $type")
                        mHandleScanEvent = true
                        //所有通过查询二维码的参数 需要先判断  http开头的  然后进行截取
                        if (content.startsWith("http")) {
                            try {
                                val currentDateTimeString =
                                    BigDecimalUtils.extractParameterValue(content, "code")
                                RcLog.info("=======ce  $currentDateTimeString")
//                                if (mDataBean.rfidCode == null) {
//                                    mDataBean.rfidCode = "-1"
//                                }
                                handleScanEvent(currentDateTimeString!!)
//                                if (mDataBean.tagCode == currentDateTimeString || currentDateTimeString == mDataBean.rfidCode!!) {
//                                    handleScanEvent(currentDateTimeString!!)
//                                } else {
//                                    showToast("请检查化学品标签是否一致")
//                                    mHandleScanEvent = false
//                                }

                            } catch (e: Exception) {
                                showToast("扫码失败，请重新扫码")
                                mHandleScanEvent = false
                            }
                        } else {
//                            if (mDataBean.rfidCode == null) {
//                                mDataBean.rfidCode = "-1"
//                            }
//                            if (mDataBean.tagCode == content || content == mDataBean.rfidCode!!) {
//                                handleScanEvent(content)
//                            } else {
//                                showToast("请检查化学品标签是否一致")
//                                mHandleScanEvent = false
//                            }
                            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()
        try {
            if (Constants.AUTHENTICATION) {
                mTyps = 2
                showLoading("查询中...")
                val disposable =
                    ApiRepository.getCabinetLock(mDataBean!!.doorId)
                        .subscribe({ data ->
                            dismissLoading()
                            mCabinetLockVoList = data
                            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) {
                                    viewBinding.butOpen.visibility = View.VISIBLE
                                    openLock(mLockStr)
                                } else {
                                    viewBinding.butOpen.visibility = View.GONE
                                    //没有锁 直接显示 需要扫描化学品信息
                                    upListTwo(
                                        mDataBean!!.cabinetName,
                                        mDataBean!!.doorName,
                                        mDataBean!!.layers
                                    )
                                }
                            } else {
                                //没有锁 直接显示 需要扫描化学品信息
                                upListTwo(
                                    mDataBean!!.cabinetName,
                                    mDataBean!!.doorName,
                                    mDataBean!!.layers
                                )
                            }
                        }, { throwable ->
                            dismissLoading()
                            showNetError(throwable)
                        })
                addDisposable(disposable)
            }
        } catch (e: Exception) {
            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()
        mPortScanHelper.onPause()

        try {
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
        } catch (e: Exception) {

        }
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
        // 停止定时更新
        unregisterReceiver(mUsbReceiver)
        EventBus.getDefault().unregister(this) //关闭广播
    }

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

    }


    //=========================刷卡end==================
    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun cdTime(cd: Int) {
        TODO("Not yet implemented")
    }

    //=================开锁流程================
    private fun openLock(mLockStr: ArrayList<String>) {
        val map = mutableMapOf<String, Any>()
        map["subId"] = ChemicalApp.subjectId!!
        map["subName"] = ChemicalApp.subjectName!!
        map["cabinetId"] = "${mDataBean.cabinetId}"
        map["cabinetName"] = "${mDataBean.cabinetName}"
        map["doorId"] = "${mDataBean.doorId}"
        map["doorName"] = "${mDataBean.doorName}"
        map["lockNumList"] = mLockStr
        map["operationType"] = 5
        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("查询中...")
                    // 开始执行任务，每 1 秒执行一次
                    startCountdownLock()
                    handlerUtil.startTask(task, 1000)
                }
            }, { throwable ->
                dismissLoading()
                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 {
        //判断所有的锁开锁成功
        val containsFalse = mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
        if (containsFalse) {
            getLocks()
        } else {
            dismissLoading()
            mIsLock = true
//            discardDialogShow()
            //没有锁 直接显示 需要扫描化学品信息
            MediaPlayerHelper.playRawMp3(this, R.raw.gui_men_kai_qing_fei_qi)
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
//            mStockModelList.add(mDataBean)
            if (mTyps == 1) {
                upList(
                    mDataBean!!.cabinetName,
                    mDataBean!!.doorName,
                    mDataBean!!.layers
                )
            } else {
                upListTwo(
                    mDataBean!!.cabinetName,
                    mDataBean!!.doorName,
                    mDataBean!!.layers
                )
            }
        }
    }



    //查询开锁信息
    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)
    }

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

    //自动返回了
    override fun cdFinish() {
        super.cdFinish()
        if (Constants.VIEW_TYPE) {
            Constants.VIEW_TYPE = false
        }
        if (mIsLock) {
            outTimeWarnData()
        } else {
            finish()
        }
    }

}