package com.example.chemical.ui.uses

import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.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.blu.BluetoothConnectionManager
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityUseBinding
import com.example.chemical.iml.IBankTeps
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.adapter.CabinetDoorAdapter
import com.example.chemical.ui.adapter.CabinetDoorRighAdapter
import com.example.chemical.ui.adapter.UsageLabelDialogAdapter
import com.example.chemical.ui.adapter.UseListAdapter
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.StorageDialog
import com.example.chemical.weidith.UsageLabelDialog
import com.example.chemical.weidith.WeighDialog
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.*
import com.rc.httpcore.client.ApiRepository
import kotlinx.coroutines.*
import java.lang.Runnable
import java.math.BigDecimal
import java.nio.charset.StandardCharsets

//化学品 领用
class UseActivity : BaseCountDownActivity<ActivityUseBinding>(), IBankTeps {

    private val mAdapter by lazy { UseListAdapter() }
    private val mAdapterLeft by lazy { CabinetDoorAdapter(this) }  //左边柜子
    private val mAdapterRigh by lazy { CabinetDoorRighAdapter(this) }  //右边柜子
    private var mUsePostDataBean = UsePostDataBean(mutableListOf())
    private var mChemistryBean = mutableListOf<ChemistryBean>() //领用时需要得参数
    private var mUsageLabelDialog: UsageLabelDialog? = null
    private lateinit var timeUpdater: TimeUpdater
    private var mWeighingValue: EditText? = null
    private var mCabinetId: String? = null
    private var mCabinetName: String? = null
    private var mDoorId: String? = null
    private var mDoorName: String? = null

    private var mCabinetIdTwo: String? = null
    private var mCabinetNameTwo: String? = null
    private var mDoorIdTwo: String? = null
    private var mDoorNameTwo: String? = null

    //    private var jobTow: Job? = null
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()  // 需要打开得柜锁数量
    private var mJoinType = 1   //称重方式 1 称重，2 录入
    private val handlerUtil = HandlerUtil.getInstance()
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10
    private var mWeighDialog: WeighDialog? = null
    private var mRfidCode: String? = null
    private var mData: UseBean? = null
    private var mStockModelList = mutableListOf<TimeWarBean>()
    private var mIsLock = false //是否打开过锁  只要是只能锁被打开 就需要进行异常数据上报
    private var isok = false // true  再次开门
    private var isLcok = false  //是否打开开门按钮

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

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

    }

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        Constants.VIEW_TYPE = true
        seIBanks(this)
        initTitle()
        inAdapter()
        getStockList()//查询列表信息
        getCabinet(0)//查询柜子信息
//        viewBinding.edCont.isEnabled = false
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvReturn.setOnClickListener {
            if (mIsLock) {
                outTimeWarnData()
            } else {
                finish()
            }
        }
        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
                HttpClient.token = null
                ChemicalApp.subjectId = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }

        //化学品柜 查询
        viewBinding.relCabinet.setOnClickListener {
            getCabinet(1)
        }

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

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

        viewBinding.butNext.setOnClickListener {
            //下一页
            if (mDataPage != 0) {
                if (mDataPage != page) {
                    page++
                    getStockList()
                }
            }
        }
        MediaPlayerHelper.playRawMp3(this, R.raw.lingyongguimen)
        customDialogView(0, "请选择要打开的柜门")
    }


    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 inAdapter() {
        viewBinding.rvUse?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvUse?.adapter = mAdapter

        //左边柜子信息
        viewBinding.recyclerLeft?.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerLeft?.adapter = mAdapterLeft

        mAdapterLeft.setOnItemClickListener { adapter, view, position ->
            mAdapterLeft.data.forEach { it.isType = false }
            mAdapterLeft.data[position].isType = true
            mAdapterRigh.data.forEach { it.isType = false }  //柜门初始化
            mAdapterLeft.notifyDataSetChanged()
            if (mAdapterLeft.data[position].cabinetDoorVoList != null) {
                mCabinetId = mAdapterLeft.data[position].cabinetId
                mCabinetName = mAdapterLeft.data[position].cabinetName
                mAdapterRigh.setNewInstance(mAdapterLeft.data[position].cabinetDoorVoList.toMutableList())
            }
        }

        //点击柜门  进行领用业务
        mAdapterRigh.setOnItemClickListener { adapter, view, position ->
            mChemistryBean.clear()//每次选择柜子 清空历史数据
            mAdapterRigh.data.forEach { it.isType = false }
            mAdapterRigh.data[position].isType = true
            mAdapterRigh.notifyDataSetChanged()
            if (mAdapterRigh.data[position].cabinetLockVoList != null && mAdapterRigh.data[position].cabinetLockVoList!!.size > 0) {
                mCabinetLockVoList = mAdapterRigh.data[position].cabinetLockVoList
                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                    mLockStr.clear()
                    mCabinetLockVoList!!.forEach { it ->
                        when (it.unlockingMethod) {
                            2 -> { //智能锁
                                isLcok = true
                                mLockStr.add("${it.lockNum}")
                            }
                        }
                    }
                } else {
                    isLcok = false
                    mLockStr.clear()
                }
            } else {
                isLcok = false
                mLockStr.clear()
            }
            mDoorId = mAdapterRigh.data[position].doorUniqueId
            mDoorName = mAdapterRigh.data[position].doorName

            if (mAdapterRigh.data[position].verify) {
                var chemicalLevel = 2  //非管控
                if (mAdapterRigh.data[position].isControl) {
                    //管控
                    chemicalLevel = 1
                }
                //需要双人认证   1人脸 2刷卡 3扫码  获取基础信息配置
                if (ChemicalApp.confs!!.verifyType.length == 1) {
                    val map = mutableMapOf<String, Any>()
                    map["chemicalLevel"] = chemicalLevel  //管控类型
                    map["doorId"] = "$mDoorId"  //柜子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(chemicalLevel)
                }
            } else {
                if (mLockStr != null && mLockStr.size > 0) {
                    openLock(mLockStr)
                } else {
                    //没有锁 不需要开锁
                    MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
                    RcLog.info("=====测hi是111")
                    usageLabelDialog()
                }
            }

        }

        //右边柜子信息
        viewBinding.recyclerRgi?.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerRgi?.adapter = mAdapterRigh

    }

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

        UiManager.switcher(
            this,
            map,
            TwoVerificationActivity::class.java,
            Constants.REQUEST_CODE
        )

    }

    private fun usageLabelDialog() {

        mUsageLabelDialog = UsageLabelDialog(
            this,
            isLcok,
            "${mCabinetName}-${mDoorName}",
            object : UsageLabelDialog.IIneSwipeLin {
                override fun onCardInContent(cont: String) {
                    getByRfid(cont)
                }

                //点击领用后 进行数据提交
                override fun onUseClick(data: MutableList<ChemistryBean>) {
                    if (data != null && data.size > 0) {
                        data.forEach { it.outType = mJoinType }
                        putDataUse(data)
                    } else {
                        showToast("无领用信息")
                    }
                }

                override fun onCloses() {
                    mChemistryBean.clear()
                }

                //再次开门  不需要双人认证
                override fun openLock() {
                    isok = true
                    if (mLockStr != null && mLockStr.size > 0) {
                        openLock(mLockStr)
                    } else {
                        //没有锁 不需要开锁
                        MediaPlayerHelper.playRawMp3(this@UseActivity, R.raw.quchuhuaxuepin)
                        RcLog.info("=====测hi是222")
                        usageLabelDialog()
                    }
                }

                override fun onPositions(position: Int, mData: UsageLabelDialogAdapter) {
                    RcLog.info("=====当前有几条 ${mChemistryBean.size}")
                    try {
                        mData.data.removeAt(position)
                        mChemistryBean = mData.data
                        mData.notifyDataSetChanged()
                    } catch (e: Exception) {
                    }
                }

                override fun onTimerReply() {
                    stopCountDown()
                }
            })
        mUsageLabelDialog!!.show()
        if (isok) {
            mUsageLabelDialog!!.setMessage("11", mChemistryBean)
        }

    }

    //领用
    private fun putDataUse(upData: MutableList<ChemistryBean>) {
        try {// 从 SharedPreferences 中取出集合
            val retrievedList = SharedPreferencesHelper.getList(this)
            if (retrievedList != null && retrievedList.size > 0) {
                upData.forEach { it ->
                    it.outOneUser = "${retrievedList[0].userId}"
                    it.outOneUserName = "${retrievedList[0].name}"
                    it.outTwoUser = "${retrievedList[1].userId}"
                    it.outTwoUserName = "${retrievedList[1].name}"
                }
                // 清空 SharedPreferences 中的集合
                SharedPreferencesHelper.clearList(this)
            }
        } catch (e: Exception) {

        }

//        mUsePostDataBean.userecordModelList = mChemistryBean
        mUsePostDataBean.userecordModelList = upData
        showLoading("查询中...")
        val disposable = ApiRepository.addUseRecord(mUsePostDataBean)
            .subscribe({ data ->
                dismissLoading()
                mChemistryBean.clear()
                mIsLock = false
                customDialogView(1, "领用成功")
                mPages = 1
                getStockList()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    //通过rfid-tagCode码 查询当前需要领用得信息
    private fun getByRfid(rfidCode: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.getByRfid(rfidCode)
            .subscribe({ data ->
                dismissLoading()
                if (data.configModel != null) {
                    if (data.configModel.metage) {
                        //需要称重
                        weighData(rfidCode, data)
                    } else {
                        mJoinType = 0
                        val chemistryBean = ChemistryBean(
                            id = data.id,
                            stockId = data.id,
                            chemicalName = data.chemicalName,
                            code = rfidCode,
                            spec = "${data.specNum}${data.specUnit}/${data.packUnit}",
                            duration = "${data.duration}",
                            stockDetailsId = data.stockDetailsId,
                            surplus = data.surplus,
                            specUnit = data.specUnit,  //单位
                            chemicalDensity = data.chemicalDensity,
                            outType = mJoinType,
                            packNum = data.packNum
                        )
                        mChemistryBean.add(chemistryBean)
                        if (mChemistryBean.size > 1) {
                            mUsageLabelDialog!!.notifyData(mChemistryBean)
                        } else {
                            mUsageLabelDialog!!.setMessage("11", mChemistryBean)
                        }

                    }
                } else {
                    showToast("当前信息配置不全")
                }

            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                if (mUsageLabelDialog != null) {
                    mUsageLabelDialog!!.notifyData()
                }

            })
        addDisposable(disposable)
    }

    //称重后返回参数
    private fun weighData(rfidCode: String, data: UseBean?) {
        mRfidCode = rfidCode
        mData = data
//        val netContent = data!!.chemicalDensity * data.specNum  // 净量 = 密度*规格
//        var density = "${netContent}/${data.packUnit}"

        mWeighDialog = WeighDialog(
            this,
            "${data!!.specNum}${data.specUnit}/${data.packUnit}",
            object : WeighDialog.IViewLint {
                override fun weighingView(weighingValue: EditText) {
                    mWeighingValue = weighingValue
                    if (mWeighingValue!!.isEnabled) {
                        // EditText允许输入
                        // 在这里执行相应的操作
                        weiView()
                    } else {
                        // EditText禁止输入
                        // 在这里执行相应的操作
                        connectToDeviceWithTimeout()
                    }
                    mWeighingValue!!.setOnEditorActionListener { v, actionId, event ->
                        if (event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                            // 确认是否触发了"actionDone"
                            RcLog.info("====键盘测试==1")
                            true
                        } else {
                            RcLog.info("====键盘测试==2  ${mWeighingValue!!.text.toString()}")
                            closEnd()
                            false
                        }
                    }
                }

                override fun viewCloses() {
                    closEndTwo()
                    try {
                        lifecycleScope.cancel()
                        RcLog.info("=====协程关闭成功")
                    } catch (e: Exception) {
                        RcLog.info("=====协程关闭失败")
                    }
                    try {
                        if (mUsageLabelDialog != null) {
                            mUsageLabelDialog!!.notifyData()
                        }
                    } catch (e: Exception) {

                    }
                }

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

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

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

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

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

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

    private fun closEndTwo() {
//        mUsageLabelDialog!!.notifyData()
//        jobTow?.cancel()

        mWeighDialog!!.dismiss()
    }

    //进行下一步业务
    private fun closEnd() {
//        jobTow?.cancel()

        mWeighDialog!!.dismiss()
        val weigh =
            mWeighingValue!!.text.toString().trim()  //称重后的重量
        if (weigh.isEmpty()) {
            showToast("未称重")
            return
        }
        if (weigh.toDouble() <= 0) {
            showToast("当前重量有误")
            return
        }
        if (mData!!.specUnit == "ml") {
            //库存重量
            val multiply = mData!!.chemicalDensity.multiply(mData!!.surplus)
            RcLog.info("===a====${mData!!.chemicalDensity}")
            RcLog.info("===a====${mData!!.surplus}")
            RcLog.info("===a====${multiply}")

            val subtract = BigDecimal(weigh).subtract(mData!!.packNum)
            RcLog.info("===a====${weigh}")
            RcLog.info("===a====${subtract}")
            RcLog.info("===a====${mData!!.packNum}")

            val errorRate = BigDecimalUtils.errorRate(multiply, subtract)
            RcLog.info("===a====${errorRate}   ${ChemicalApp.confs!!.vinVex}")

            if (errorRate!!.compareTo(ChemicalApp.confs!!.vinVex) > 0) {
                mUsageLabelDialog!!.notifyData()
                mUsageLabelDialog!!.onUserInteraction()
                showToast("超出允许误差范围")
                return
            }
        } else {
            //库存重量
            val subtract = BigDecimal(weigh).subtract(mData!!.packNum)
            val errorRate = BigDecimalUtils.errorRate(mData!!.surplus, subtract)
            RcLog.info("===b====${mData!!.packNum}")
            RcLog.info("===b====${mData!!.surplus}")
            RcLog.info("===b====${subtract}")
            RcLog.info("===b====${errorRate}")
            RcLog.info("===b====${weigh}   ${ChemicalApp.confs!!.vinVex}")
            if (errorRate!!.compareTo(ChemicalApp.confs!!.vinVex) > 0) {
                mUsageLabelDialog!!.notifyData()
                mUsageLabelDialog!!.onUserInteraction()
                showToast("超出允许误差范围")
                return
            }
        }
        val chemistryBean = ChemistryBean(
            id = mData!!.id,
            stockId = mData!!.id,
            weigh = BigDecimal(weigh),
            chemicalName = mData!!.chemicalName,
            code = mRfidCode!!,
            spec = "${mData!!.specNum}${mData!!.specUnit}/${mData!!.packUnit}",
            duration = "${mData!!.duration}",
            stockDetailsId = mData!!.stockDetailsId,
            surplus = mData!!.surplus,
            specUnit = mData!!.specUnit,  //单位
            chemicalDensity = mData!!.chemicalDensity,
            packNum = mData!!.packNum
        )
        mChemistryBean.add(chemistryBean)
        if (mChemistryBean.size > 1) {
            mUsageLabelDialog!!.notifyData(mChemistryBean)
        } else {
            mUsageLabelDialog!!.setMessage("11", mChemistryBean)
        }
    }

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

    var taskStarted = false

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

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

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

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

    }

    private fun getStockList() {
        val map = mutableMapOf<String, Any>()
        map["subId"] = "${ChemicalApp.subjectId!!}"
        if (mCabinetIdTwo != null) {
            map["cabinetId"] = mCabinetIdTwo!!
        }

        if (mDoorIdTwo != null) {
            map["doorId"] = mDoorIdTwo!!
        }
        val toString = viewBinding.edCont.text.toString()
        if (toString.isNotEmpty()) {
            map["searchValue"] = toString!!
        }
        map["page"] = page
        map["pageSize"] = pageSize

        showLoading("查询中...")
        val disposable =
            ApiRepository.getStockList(map)
                .subscribe({ data ->
                    dismissLoading()
                    mDataPage = data.pages  //总页
                    RcLog.info("===page${data.pages}  curent ${data.current}")
                    if (data.records != null && data.records.size == 0) {
                        mAdapter.data.clear()
                        mAdapter.notifyDataSetChanged()
                    }
                    if (data.pages != 0) {
                        if (data.pages > 1 && data.current > 1) {
                            //当前需要更新页码
                            upPagesView(data.pages, data.current)
                            mAdapter.setList(data.records.toMutableList())
                        } else {
                            initPagesView(data.pages)
                            mAdapter.setNewInstance(data.records.toMutableList())
                        }
                    }
                }, { 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 getCabinet(tag: Int) {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(ChemicalApp.subjectId!!)
            .subscribe({ data ->
                dismissLoading()
                if (tag == 0) {
                    mAdapterLeft.setNewInstance(data.toMutableList())
//                    mCabinetId = data[0].cabinetId
//                    mCabinetName = data[0].cabinetName
//                    mDoorId = data[0].cabinetDoorVoList[0].doorUniqueId
//                    mDoorName = data[0].cabinetDoorVoList[0].doorName
//                    mAdapterRigh.setNewInstance(data[0].cabinetDoorVoList.toMutableList())
                } else {
                    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,
                                ) {
                                    mCabinetIdTwo = cabinetId
                                    mCabinetNameTwo = cabinetName
                                    mDoorIdTwo = doorId
                                    mDoorNameTwo = doorName
                                    viewBinding.cabinetName.text = "$cabinetName"
                                }

                                override fun onClose() {
                                    if (mCabinetIdTwo != null) {
                                        mCabinetIdTwo = null
                                        mDoorIdTwo = 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()
            mIsLock = true
            //柜门已开取出化学品
            MediaPlayerHelper.playRawMp3(this, R.raw.guimenkaiquchuhuaxue)
            RcLog.info("=====测hi是333")
            usageLabelDialog()
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
//            if (isok) {
//                dismissLoading()
//                mIsLock = true
//                handlerUtil.stopAllTasks()
//                countdownTimer?.cancel()
//            } else {
//                dismissLoading()
//                mIsLock = true
//                //柜门已开取出化学品
//                MediaPlayerHelper.playRawMp3(this, R.raw.guimenkaiquchuhuaxue)
//                usageLabelDialog()
//                handlerUtil.stopAllTasks()
//                countdownTimer?.cancel()
//            }
        }
    }

    private fun openLock(mLockStr: ArrayList<String>) {
        val map = mutableMapOf<String, Any>()
        map["subId"] = ChemicalApp.subjectId!!
        map["subName"] = ChemicalApp.subjectName!!
        map["cabinetId"] = "$mCabinetId"
        map["cabinetName"] = "$mCabinetName"
        map["doorId"] = "$mDoorId"
        map["doorName"] = "$mDoorName"
//        map["lockNum"] = "guisuo001"
        map["lockNumList"] = mLockStr
        map["operationType"] = 3
        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()
                    mIsLock = true
                    //柜门已开取出化学品
                    MediaPlayerHelper.playRawMp3(this, R.raw.guimenkaiquchuhuaxue)
                    RcLog.info("=====测hi是444")
                    usageLabelDialog()
                    handlerUtil.stopAllTasks()
                    countdownTimer?.cancel()

//                    if (mIsLock) {
//                        dismissLoading()
//                        mIsLock = true
//                        handlerUtil.stopAllTasks()
//                        countdownTimer?.cancel()
//                    } else {
//                        dismissLoading()
//                        mIsLock = true
//                        //柜门已开取出化学品
//                        MediaPlayerHelper.playRawMp3(this, R.raw.guimenkaiquchuhuaxue)
//                        usageLabelDialog()
//                        handlerUtil.stopAllTasks()
//                        countdownTimer?.cancel()
//                    }

                }
            }, { 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 onResume() {
        super.onResume()
        try {
            if (Constants.AUTHENTICATION) {
                if (mLockStr != null && mLockStr.size > 0) {
                    openLock(mLockStr)
                } else {
                    //没有锁 不需要开锁
                    MediaPlayerHelper.playRawMp3(this, R.raw.quchuhuaxuepin)
                    RcLog.info("=====测hi是555")
                    usageLabelDialog()
                }
                Constants.AUTHENTICATION = false
            }
        } catch (e: Exception) {
            Constants.AUTHENTICATION = false
        }
    }

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

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

    //查询开锁信息
    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 ->
                RcLog.info("=======开锁查询成功")
                if (data) {
                    mCabinetLockVoList!![index].isOk = true
                    RcLog.info("=======设置成功")
                }
            }, { throwable ->
                RcLog.info("=======开锁查询成功 解析失败")
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

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

    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 = mCabinetName
        bean.doorName = mDoorName
        bean.deptName = ChemicalApp.confs!!.deptName
        bean.stockTypeStr = "领用"
        mStockModelList.add(bean)
        map["stockModelList"] = mStockModelList  //管控类型
        showLoading("提交中...")
        val disposable =
            ApiRepository.outTimeWarn(map)
                .subscribe({ data ->
                    dismissLoading()
                    finish()
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)
                })
        addDisposable(disposable)
    }

}