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.LayoutInflater
import android.view.View
import android.widget.AdapterView
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.caysn.autoreplyprint.AutoReplyPrint
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityChemicalLabelingBinding
import com.example.chemical.ui.PrintBean
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.adapter.ChemicalLabelingAdapter
import com.example.chemical.ui.adapter.CustomSpinnerTwoAdapter
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.LockVoListBean
import com.rc.httpcore.bean.ReturnDetailsBean
import com.rc.httpcore.client.ApiRepository
import com.sun.jna.Pointer

//标签列表
class ChemicalLabelingActivity : BaseCountDownActivity<ActivityChemicalLabelingBinding>() {

    private val mAdapter by lazy { ChemicalLabelingAdapter(this) }
    private lateinit var timeUpdater: TimeUpdater
    private lateinit var mData: ReturnDetailsBean
    private var mCabinetId: String? = null
    private var mDoorId: String? = null
    private val sPrinDate: MutableList<String> = mutableListOf()
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()  // 需要打开得柜锁数量
    private val handlerUtil = HandlerUtil.getInstance()
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10
    private var mPosition = 0
    private var mAdIndex = -1
    var h = Pointer.NULL


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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        val sPinner = viewBinding.sPinner
        viewBinding.rvInventory.layoutManager = LinearLayoutManager(this)
        viewBinding.rvInventory.adapter = mAdapter
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
                HttpClient.token = null
                ChemicalApp.subjectId = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }

        viewBinding.tvReturn.setOnClickListener {
            finish()
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.data.forEach { it.isType = false }
            mAdapter.data[position].isType = true
            mAdapter.notifyDataSetChanged()
            getIdDate("${mAdapter.data[position].id}")
            mAdIndex = position
        }

        viewBinding.cabinetName.setOnClickListener {
            getCabinet()
        }

        viewBinding.reSou.setOnClickListener {
            page = 1
            labelingData()
        }
        viewBinding.edCont.setOnClickListener {
            val edDialog = EdContTwoDialog(this, object : EdContTwoDialog.IClickLit {
                override fun onClickClo(str: String?) {
                    if (str != null) {
                        viewBinding.edCont.text = "$str"
                    } else {
                        page = 1
                        labelingData()
                    }
                }
            })
            edDialog.show()
        }
        viewBinding.resetting.setOnClickListener {
            page = 1
            mCabinetId = null
            mDoorId = null
            viewBinding.edCont.text = ""
            viewBinding.cabinetName.text = "化学品柜"
            sPinner.setSelection(0)
            labelingData()
        }
        viewBinding.reLabel.setOnClickListener {
            //补打标签
            val print = PrintBean()
            print.tag = mData.tagCode  //化学品编码
            print.wxCode = mData.wxCode!!  //化学品编码
            print.name = mData.chemicalName!! //化学品名称
            if (mData.casNum != null) {
                print.casNo = mData.casNum!!  //cas号
            } else {
                print.casNo = ""
            }

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

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

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

        }

        viewBinding.openLok.setOnClickListener {
            val toString = viewBinding.openLok.text.toString()
            if (toString == "打开柜门") {
                //打开柜门
                if (mData.verify) {
//                    //跳转认证
//                    //需要双人认证
//                    val map = mutableMapOf<String, Any>()
//                    //当前 管控类型
//                    map["chemicalLevel"] = mData.chemicalLevel  //管控类型
//                    map["doorId"] = "${mData.doorId}"  //柜子id
//                    map["stockId"] = "${mData.chemicalId}"  //化学品id
//                    map["mTag"] = 1
//                    UiManager.switcher(
//                        this,
//                        map,
//                        SwipeCodeTwoActivity::class.java,
//                        Constants.REQUEST_CODE
//                    )

                    //需要双人认证
                    if (ChemicalApp.confs!!.verifyType.length == 1) {
                        val map = mutableMapOf<String, Any>()
                        map["chemicalLevel"] = mData.chemicalLevel  //管控类型
//                        map["doorId"] = "$mDoorId"  //柜子id
                        map["doorId"] = "${mData.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 {
                    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 {
                        //没有锁 不需要开锁
                        MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
                    }

//                    //不需要认证
//                    if (mLockStr != null && mLockStr.size > 0) {
//                        openLock(mLockStr)
//                    } else {
//                        //没有锁 不需要开锁
//                        MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
//                    }
                }
            } 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 {
                    //没有锁 不需要开锁
                    MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
                }
            }
        }
        sPrinDate.add("级别")
        sPrinDate.add("管控")
        sPrinDate.add("非管控")
        RcLog.info("=======当前级别条数${sPrinDate.size}")

        val customAdapter = CustomSpinnerTwoAdapter(this, sPrinDate!!)
        sPinner.adapter = customAdapter
        sPinner.setSelection(0)
        sPinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                // 当用户选择某一项时被调用
                RcLog.info("=======当前选择下标 ${sPrinDate!![position]}")
                mPosition = position
                // 在这里可以使用 selectedPosition 来执行相应的操作
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有任何项被选择时被调用
                RcLog.info("=======DUOC")
            }
        }

        //获取列表信息
        labelingData()
        viewBinding.butUpper.setOnClickListener {
            //上一页
            if (mDataPage != 0) {
                if (page != 1) {
                    page--
                    labelingData()
                }
            }
        }

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

    override fun initData() {
        super.initData()
        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()
        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()
    }

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

    override fun onResume() {
        super.onResume()
        try {
            if (Constants.AUTHENTICATION) {
                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 {
                    //没有锁 不需要开锁
                    MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
                }
                Constants.AUTHENTICATION = false
            }
        } catch (e: Exception) {
            Constants.AUTHENTICATION = false
        }
    }


    //验证方式
    private fun verifyChecking() {
        val map = mutableMapOf<String, Any>()
        map["chemicalLevel"] = mData.chemicalLevel  //管控类型
        map["doorId"] = "${mData.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
        )
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == Constants.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
//            val value = data?.getBooleanExtra("isLogin", false) // 获取返回的参数
//            if (value == true) {
//                //1无锁，2是智能锁，3是钥匙柜
//                when (mData.unlockingMethod) {
//                    1 -> {
//                        //1无锁
//
//                    }
//                    2 -> {
//                        //2是智能锁
//                        openLock()
//                    }
//                    3 -> {
//                        //是钥匙柜
//
//                    }
//                }
//            } else {
//                showToast("认证失败!!")
//            }
//        }
//    }

    private fun updateRfid(
        ids: String,
        rfid: String
    ) {
        showLoading("操作中...")
        val disposable = ApiRepository.updateRfid(ids, rfid).subscribe({ data ->
            dismissLoading()
            customDialogView(1, "更换成功")
            //补打标签
            val print = PrintBean()
            print.tag = mData.tagCode  //化学品编码
            print.wxCode = mData.wxCode!!  //化学品编码
            print.name = mData.chemicalName!! //化学品名称
            if (mData.casNum != null) {
                print.casNo = mData.casNum!!  //cas号
            } else {
                print.casNo = ""
            }

//            if (mDataBean.topicGroup) {
//                print.person = mDataBean.topicGroupName //归属人
//            } else {
//                print.person = mDataBean.applyUserName //归属人
//            }
            print.person = mData.belongName
            //管控 1     非管控  2
            if (mData.chemicalLevel == 1) {
                print.level = "管控"
            } else {
                print.level = "非管控"
            }
            //
            print.types = "${mData.chemicalCategoryName}"
            labelPrint(print)
            mAdapter.data[mAdIndex].rfidCode = rfid
            mAdapter.notifyItemChanged(mAdIndex)
        }, { throwable ->
            dismissLoading()
            showNetError(throwable)

        })
        addDisposable(disposable)
    }

    /**
     * 标签打印
     * 补打印
     * 化学品信息
     */
    private fun labelPrint(printDate: PrintBean) {
        val thread = Thread {
            try {

                try {//关闭打印
                    h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x0FE6,PID:0x811E", 1)
                } catch (e: Exception) {
                    RcLog.info("初始化异常")
                }

                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()
                    RcLog.info("=====异常2222")
                }
            } catch (e: Exception) {
                closePort()
                // 监听子线程中抛出的异常
                RcLog.info("=======异常${e.message}")
            }
        }
        thread.start() // 启动子线程
    }

    //更换rfid
    private fun labelPrint(rfid: String) {
        val thread = Thread {
            try {
                var h = Pointer.NULL
                try {//关闭打印
                    h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x0FE6,PID:0x811E", 1)
                } catch (e: Exception) {
                    RcLog.info("初始化异常")
                }

                val bitmap = BitmapUtils.airBottlePrint(rfid)  //图片信息
                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.zhantiefrid)

                } else {
                    //失败
                    RcLog.info("=====异常2222")
                }
            } catch (e: Exception) {
                // 监听子线程中抛出的异常
                RcLog.info("=======异常${e.message}")
            }
        }
        thread.start() // 启动子线程
    }

    /**
     * 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 labelingData() {
        showLoading("查询中...")
        val map = mutableMapOf<String, Any>()
        map["subId"] = "${ChemicalApp.subjectId}"
        if (mPosition == 1 || mPosition == 2) {
            map["chemicalLevel"] = "$mPosition"
        }
//        map["chemicalLevel"] = ""
        if (mCabinetId != null) {
            map["cabinetId"] = mCabinetId!!
        }
        if (mDoorId != null) {
            map["doorId"] = mDoorId!!
        }
        val toString = viewBinding.edCont.text.toString()
        if (toString.isNotEmpty()) {
            map["searchValue"] = toString
        }
        map["page"] = "$page"
        map["pageSize"] = "$pageSize"

        val disposable = ApiRepository.tagDetailsList(map)
            .subscribe({ data ->
                dismissLoading()
                RcLog.info("====列表==成功")
                mDataPage = data.pages  //总页
                if (mAdapter.data != null) {
                    mAdapter.data.clear()
                    mAdapter.notifyDataSetChanged()
                    initPagesView(data.pages)
                }
                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)
                RcLog.info("====列表==失败")
            })
        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 getIdDate(id: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.getDetailsById(id)
            .subscribe({ data ->
                dismissLoading()
                upView(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun upView(data: ReturnDetailsBean) {
        viewBinding.relOne.visibility = View.GONE
        viewBinding.linTow.visibility = View.VISIBLE
        viewBinding.chemicalName.text = "${data.chemicalName}"
        viewBinding.tagCode.text = "编码${data.tagCode}"
        viewBinding.chemicalLevelName.text = "${data.chemicalLevelName}"
        viewBinding.chemicalCategoryName.text = "${data.chemicalCategoryName}"
        viewBinding.spec.text = "${data.specNum}${data.specUnit}/${data.packUnit}"
        viewBinding.belongName.text = "${data.belongName}"
        viewBinding.surplus.text = "${data.surplus}${data.specUnit}"
        viewBinding.expireTime.text = ""//清除之前得数据
        if (data.expireTime != null) {
            viewBinding.expireTime.text = "${data.expireTime}"
        }
        viewBinding.cabinet.text = "${data.cabinetName}-${data.doorName}-${data.layers}层"
        mData = data
        if (mData.rfidCode == null) {
            viewBinding.replaceLabel.text = "绑定RFID"
        } else {
            viewBinding.replaceLabel.text = "更换RFID"
        }
        mCabinetLockVoList = mData.cabinetLockVoList //柜锁信息
        if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
            var isLock = false
            mCabinetLockVoList!!.forEach { it ->
                if (it.unlockingMethod == 2) {
                    isLock = true
                    return@forEach
                }
            }
            if (isLock) {
                viewBinding.openLok.visibility = View.VISIBLE
            }
        }
    }


    private fun openLock(mLockStr: ArrayList<String>) {
        val map = mutableMapOf<String, Any>()
        map["subId"] = mData.subId
        map["subName"] = mData.subName
        map["cabinetId"] = "${mData.cabinetId}"
        map["cabinetName"] = "${mData.cabinetName}"
        map["doorId"] = "${mData.doorId}"
        map["doorName"] = "${mData.doorName}"
        map["lockNumList"] = mLockStr
        map["operationType"] = 7
        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("查询中...")
                    // 开始执行任务，每 3 秒执行一次
                    startCountdownLock()
                    handlerUtil.startTask(task, 1000)
                } else {
                    dismissLoading()
                    //柜门已开去除化学品
                    customDialogView(1, "柜门已开，请取出化学品")
                    MediaPlayerHelper.playRawMp3(this, R.raw.bgm_qu_chu_hua_xue_p)
                    handlerUtil.stopAllTasks()
                    countdownTimer?.cancel()
                    viewBinding.openLok.text = "再次开门"
                }
            }, { throwable ->
                dismissLoading()
                RcLog.info("=========开始调用解析失败")
                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()
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
        } catch (e: Exception) {
        }

        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {

        }
    }


    //查询柜子  存储位置  默认第一个
    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 = "$cabinetName"
                            }

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

            })
        addDisposable(disposable)
    }

    private val task = Runnable {
        //判断所有的锁开锁成功
        val containsFalse = mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
        RcLog.info("=======查询调用开锁状态====$containsFalse")
        if (containsFalse) {
            getLocks()
        } else {
            dismissLoading()
            //柜门已开去除化学品
            customDialogView(1, "柜门已开，请取出化学品")
            MediaPlayerHelper.playRawMp3(this, R.raw.bgm_qu_chu_hua_xue_p)
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
            viewBinding.openLok.text = "再次开门"
        }
    }

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

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

    //查询开锁状态
    private fun getLocksDate(index: Int, fruit: String) {
        val disposable = ApiRepository.getLocks(ChemicalApp.subjectId!!, fruit)
            .subscribe({ data ->
                RcLog.info("=======开锁查询成功")
                if (data) {
                    mCabinetLockVoList!![index].isOk = true
                    RcLog.info("=======设置成功")
                }
            }, { throwable ->
                RcLog.info("=======开锁查询成功 解析失败")
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

}