package com.example.chemical.ui.inquiry

import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
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.chad.library.adapter.base.util.getItemView
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.databinding.ActivityInquiryBinding
import com.example.chemical.receiver.OnSerialScanListener
import com.example.chemical.receiver.PortScanHelper
import com.example.chemical.receiver.UsbReceiver
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.adapter.CabinetDoorAdapter
import com.example.chemical.ui.adapter.CabinetDoorRighAdapter
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.ui.fragments.QueryOneFragment
import com.example.chemical.ui.fragments.QueryTwoFragment
import com.example.chemical.ui.login.FacialCardActivity
import com.example.chemical.ui.login.FacialLoginActivity
import com.example.chemical.ui.login.ScanLoginActivity
import com.example.chemical.ui.login.SwipeActivity
import com.example.chemical.utils.*
import com.example.chemical.weidith.*
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.*
import com.rc.httpcore.client.ApiRepository
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

//化学品-查询   已登录-未登录   未登录-扫码弹框提示当前某一个信息   已登陆 显示所有列表
class InquiryActivity : BaseCountDownActivity<ActivityInquiryBinding>() {

    private lateinit var timeUpdater: TimeUpdater
    private var logIn = 0  //未登录
    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数
    private val mAdapterLeft by lazy { CabinetDoorAdapter(this) }  //左边柜子
    private val mAdapterRigh by lazy { CabinetDoorRighAdapter(this) }  //右边柜子
    private lateinit var viewPager: SwipeViewPager
    private lateinit var pagerAdapter: TabFragmentPagerAdapter
    private var mLeftPosition = 0 //左边柜子信息
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()  // 需要打开得柜锁数量
    private val handlerUtil = HandlerUtil.getInstance()
    private var mCabinetId: String? = null
    private var mCabinetName: String? = null
    private var mDoorId: String? = null
    private var mDoorName: String? = null
    private lateinit var faceList: List<String>//人员区间值
    private var mLoginType: String? = null //登录方式

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        logIn = intent.getIntExtra("logIn", 0)
        val stringExtra = intent.getStringExtra("cabinetId")
        val stringExtra1 = intent.getStringExtra("doorId")
        if (!stringExtra.equals("a")) {
            mCabinetId = stringExtra
            mDoorId = stringExtra1
        }
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        //注册广播
        EventBus.getDefault().register(this)
        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
//                HttpClient.token = null
                ChemicalApp.subjectId = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }

        if (logIn == 1) {
//            mHandleScanEvent = true
            //已登录
            viewBinding.loggedIn.visibility = View.VISIBLE
            viewBinding.tvName.text = "${ChemicalApp.userData!!.userName}"
            viewBinding.relOne.visibility = View.GONE
            getCabinet(ChemicalApp.subjectId!!)
            RcLog.info("=====$mCabinetId")
            RcLog.info("=====$mDoorId")
            fragmentInView()
            inAdapter()
            viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        } else {
            mLoginType = ChemicalApp.confs!!.loginType
            //未登录
            viewBinding.loggedIn.visibility = View.GONE
            viewBinding.tvName.visibility = View.GONE
        }

        viewBinding.logIn.setOnClickListener {
            getUserIds()

        }
        initTitle()
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }
        //校园级管理员-柜门管理员-柜锁管理员-安全负责人-实验室负责人
        viewBinding.butOpen.setOnClickListener {
            if (ChemicalApp.administrators || ChemicalApp.responsibles) {

                if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                    mLockStr.clear()
                    mCabinetLockVoList!!.forEach { it ->
                        when (it.unlockingMethod) {
                            2 -> { //智能锁
                                mLockStr.add("${it.lockNum}")
                            }
                        }
                    }
                    if (mLockStr != null && mLockStr.size > 0) {
                        openLock(mLockStr)
                    } else {
                        //无锁
                        customDialogView(1, "柜门已开")
                    }
                } else {
                    //无锁
                    customDialogView(1, "柜门已开")
                }
            } else {
                showToast("无权限信息")
            }
        }
    }

    private fun initTitle() {
        if (ChemicalApp.userData != null) {
            viewBinding.logIn.visibility = View.GONE
            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 fragmentInView() {
        val tabArray = mutableListOf(
            QueryOneFragment.newInstance(),
            QueryTwoFragment.newInstance(),
        )
        pagerAdapter = TabFragmentPagerAdapter(supportFragmentManager, tabArray)
        viewPager = viewBinding.swipePagerView
        viewPager.adapter = pagerAdapter
    }

    private fun inAdapter() {
        viewBinding.recyclerViewListLeft?.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerViewListLeft?.adapter = mAdapterLeft
        viewBinding.recyclerViewListRight?.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerViewListRight?.adapter = mAdapterRigh

        mAdapterLeft.setOnItemClickListener { adapter, view, position ->
            mLeftPosition = position
            mAdapterLeft.data.forEach { it.isType = false }
            mAdapterLeft.data[position].isType = true
            mAdapterRigh.data.forEach { it.isType = false }  //柜门初始化
            mAdapterLeft.notifyDataSetChanged()

            if (mAdapterLeft.data[mLeftPosition].cabinetDoorVoList != null) {
                mCabinetId = mAdapterLeft.data[mLeftPosition].cabinetId
                mCabinetName = mAdapterLeft.data[mLeftPosition].cabinetName
                mAdapterRigh.setNewInstance(mAdapterLeft.data[mLeftPosition].cabinetDoorVoList.toMutableList())
            }
        }


        mAdapterRigh.setOnItemClickListener { adapter, view, position ->
            mDoorId = mAdapterRigh.data[position].doorUniqueId
            mDoorName = mAdapterRigh.data[position].doorName
            mCabinetLockVoList = mAdapterRigh.data[position].cabinetLockVoList
            mAdapterRigh.data.forEach { it.isType = false }
            mAdapterRigh.data[position].isType = true
            mAdapterRigh.notifyDataSetChanged()
            //第一个页面
            goQueryTwoFragment()
            if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                var isLock = false
                mCabinetLockVoList!!.forEach { it ->
                    if (it.unlockingMethod == 2) {
                        isLock = true
                        return@forEach
                    }
                }

                if (isLock) {
                    viewBinding.butOpen.visibility = View.VISIBLE
                } else {
                    viewBinding.butOpen.visibility = View.GONE
                }

            }
        }


    }


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

    //查询存储位置  默认第一个
    private fun getCabinet(subId: String) {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(subId)
            .subscribe({ data ->
                dismissLoading()

                mAdapterLeft.setNewInstance(data.toMutableList())
                mAdapterRigh.setNewInstance(data[0].cabinetDoorVoList.toMutableList())
                if (mCabinetId != null) {
                    mAdapterLeft.data.forEachIndexed { index, ruleBean ->
                        if (mCabinetId.equals(ruleBean.cabinetId)) {
                            mAdapterLeft.data[index].isType = true
                            mAdapterLeft.data[index].cabinetDoorVoList.forEachIndexed { index, ruleBean ->
                                if (mDoorId.equals(ruleBean.doorUniqueId)) {
                                    mAdapterRigh.data[index].isType = true
                                    return@forEachIndexed
                                }
                            }
                            return@forEachIndexed
                        }
                    }
                } else {
                    //初始化第一把锁
                    mCabinetId = mAdapterLeft.data[0].cabinetId
                    mCabinetName = mAdapterLeft.data[0].cabinetName
                    mAdapterLeft.data[0].isType = true
                    mDoorId = mAdapterRigh.data[0].doorUniqueId
                    mDoorName = mAdapterRigh.data[0].doorName
                    mAdapterRigh.data[0].isType = true
                    mCabinetLockVoList = mAdapterLeft.data[0].cabinetDoorVoList[0].cabinetLockVoList

                    if (mCabinetLockVoList != null && mCabinetLockVoList!!.size > 0) {
                        var isLock = false
                        mCabinetLockVoList!!.forEach { it ->
                            if (it.unlockingMethod == 2) {
                                isLock = true
                                return@forEach
                            }
                        }

                        if (isLock) {
                            viewBinding.butOpen.visibility = View.VISIBLE
                        } else {
                            viewBinding.butOpen.visibility = View.GONE
                        }

                    }


                }

                //第一个页面
                goQueryTwoFragment()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

    fun goQueryTwoFragment(stockId: String, hxpStockWaitListBean: HxpStockWaitListBean) {
        val secondFragment = pagerAdapter.getItem(1) as QueryTwoFragment
        secondFragment.setData(stockId, hxpStockWaitListBean, mCabinetId, mDoorId)
        viewPager.currentItem = 1
    }

    private fun goQueryTwoFragment() {
        val secondFragment = pagerAdapter.getItem(0) as QueryOneFragment
        secondFragment.upDatas(mCabinetId, mDoorId)
        viewPager.currentItem = 0
    }

    //=========================刷卡start================
    //刷卡信息  调用当前化学品信息 进行归还
    private fun handleScanEvent(cont: String) {
        if (logIn == 1) {
            //已登录
            showLoading("查询中...")
            val disposable = ApiRepository.getStockDetailsByCode(cont)
                .subscribe({ data ->
                    dismissLoading()
                    upViewTwo(data)
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)
                    mHandleScanEvent = false
                })
            addDisposable(disposable)
        } else {
            //未登录
            showLoading("查询中...")
            val disposable = ApiRepository.indexDetailbyRfid(cont)
                .subscribe({ data ->
                    dismissLoading()
                    upView(data)
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)
                    mHandleScanEvent = false
                })
            addDisposable(disposable)
        }
    }

    //未登录
    private fun upView(data: UseNoBean) {
        val proDialog = PromptDialog(this, data)
        if (!this.isFinishing && !this.isDestroyed) {
            proDialog.show()
        }
        mHandleScanEvent = false
    }

    //已登录
    private fun upViewTwo(data: UseNoTwoBean) {
        val scanCodeDialog = ScanCodeDialog(this, data)
        if (!this.isFinishing && !this.isDestroyed) {
            scanCodeDialog.show()
        }
        mHandleScanEvent = false
    }

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

                }
            }

        })
    }

    //刷卡usb链接
    private fun registerUsbBroadcast() {
        if (null == mUsbReceiver) {
            val filter = IntentFilter().apply {
                addAction(UsbReceiver.ACTION_USB_PERMISSION)
                addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
                addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
                addAction(UsbReceiver.ACTION_USB_STATE) // usb连接状态广播
            }
            mUsbReceiver = UsbReceiver()
            registerReceiver(mUsbReceiver, filter)
        }
    }

    override fun onResume() {
        super.onResume()
        mPortScanHelper.onResume()
        registerUsbBroadcast()
    }

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

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

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

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

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

    }

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

    //==========================开锁信息===================

    //=================开锁流程================

    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["lockNumList"] = mLockStr
        map["operationType"] = 6
        if (ChemicalApp.subRoom != null) {
            map["subRoom"] = ChemicalApp.subRoom!!
        }
        map["type"] = true
        try {// 从 SharedPreferences 中取出集合
            val retrievedList = SharedPreferencesHelper.getList(this)
            if (retrievedList != null && retrievedList.size > 0) {
                RcLog.info("从本地取出得双人信息${retrievedList[0].name}")
                map["oneUserId"] = "${retrievedList[0].userId}"
                map["oneUserName"] = "${retrievedList[0].name}"
                map["twoUserId"] = "${retrievedList[1].userId}"
                map["twoUserName"] = "${retrievedList[1].name}"
                // 清空 SharedPreferences 中的集合
//                SharedPreferencesHelper.clearList(this)
            }
        } catch (e: Exception) {

        }
        showLoading("加载中...")
        val disposable = ApiRepository.lockOperate(map)
            .subscribe({ data ->
                dismissLoading()
                val containsFalse =
                    mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
                if (containsFalse) {
                    showLoading("查询中...")
                    startCountdownLock()
                    // 开始执行任务，每 1 秒执行一次
                    handlerUtil.startTask(task, 1000)
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

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

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

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

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

    private val task = Runnable {
        //判断所有的锁开锁成功
        val containsFalse = mCabinetLockVoList!!.any { it.isOk == false && it.unlockingMethod == 2 }
        if (containsFalse) {
            getLocks()
        } else {
            dismissLoading()
            //开锁成功
            customDialogView(1, "柜门已开")
            MediaPlayerHelper.playRawMp3(this, R.raw.guimenkai)
            handlerUtil.stopAllTasks()
            countdownTimer?.cancel()
        }
    }


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

    //查询开锁状态
    private fun getLocksDate(index: Int, fruit: String) {
        val disposable = ApiRepository.getLocks(ChemicalApp.subjectId!!, fruit)
            .subscribe({ data ->
                if (data) {
                    mCabinetLockVoList!![index].isOk = true
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

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

    private fun getUserIds() {
        if (ChemicalApp.subjectId != null) {
            showLoading("查询中...")
            val disposable = ApiRepository.getUserIds(ChemicalApp.subjectId!!)
                .subscribe({ data ->
                    dismissLoading()
                    faceList = data
                    getLogin()
                }, { throwable ->
                    dismissLoading()
//                throwableView(throwable)
                })
            addDisposable(disposable)
        }
    }

    //登录方式
    private fun getLogin() {
        if (mLoginType == null) {
            customDialogView(2, "登录方式配置有误")
        } else {
            finish()
            if (mLoginType!!.contains("4")) {
                //需要刷卡+人脸
                UiManager.switcher(this, FacialCardActivity::class.java)
            } else {
                val map = mutableMapOf<String, String>()
                //1人脸 2刷卡 3扫码   4人脸+刷卡
                if (mLoginType!!.length == 1) {
                    when (mLoginType) {
                        "1" -> {
                            //人脸
                            map["faceList"] = faceList.toString()
                            map["mtypes"] = "1"
                            UiManager.switcher(this, map, FacialLoginActivity::class.java)
                        }
                        "2" -> {
                            //刷卡
                            map["mtypes"] = "1"
                            UiManager.switcher(this, map, SwipeActivity::class.java)
                        }
                        else -> {
                            //扫码
                            map["mtypes"] = "1"
                            UiManager.switcher(this, map, ScanLoginActivity::class.java)
                        }
                    }

                } else {
                    val array = mLoginType!!.split(",").toTypedArray()
                    when (array.size) {
                        2 -> {
                            //1-2(人脸+刷卡)  1-3(人脸+扫码)  2-3(刷卡+扫码)
                            if (mLoginType == "1,2" || mLoginType == "2,1") {
                                //人脸+刷卡
                                map["faceList"] = faceList.toString()
                                map["mtypes"] = "4"  //隐藏扫码
                                UiManager.switcher(this, map, FacialLoginActivity::class.java)
                            } else if (mLoginType == "1,3" || mLoginType == "3,1") {
                                //人脸+扫码
                                map["faceList"] = faceList.toString()
                                map["mtypes"] = "5"  //隐藏刷卡
                                UiManager.switcher(this, map, FacialLoginActivity::class.java)
                            } else if (mLoginType == "2,3" || mLoginType == "3,2") {
                                //刷卡+扫码
                                map["mtypes"] = "6"  //隐藏人脸
                                UiManager.switcher(this, map, SwipeActivity::class.java)
                            } else {
                                showToast("登录方式$mLoginType")
                            }

                        }
                        else -> {
                            //3条
                            try {
                                map["mtypes"] = "0"
                                map["faceList"] = faceList.toString()
                                UiManager.switcher(this, map, FacialLoginActivity::class.java)
                            } catch (e: Exception) {
                                map["mtypes"] = "0"
                                UiManager.switcher(this, map, SwipeActivity::class.java)
                            }
                        }
                    }
                }

            }
        }

    }
}