package com.example.chemical.weidith

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.IntentFilter
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.*
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.receiver.OnSerialScanListener
import com.example.chemical.receiver.PortScanHelper
import com.example.chemical.receiver.UsbReceiver
import com.example.chemical.ui.adapter.UsageLabelDialogAdapter
import com.example.chemical.utils.BigDecimalUtils
import com.rc.core.log.RcLog
import com.rc.httpcore.bean.ChemistryBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


//领用-请扫描化学品标签
class UsageLabelDialog(
    private val ac: Activity,
    private var isLcok: Boolean,
    private var cabinet: String,
    private val lint: IIneSwipeLin
) : Dialog(ac) {

    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数
    private val mAdapter by lazy { UsageLabelDialogAdapter(ac) }
    private var mCounter = 0
    private var butClos: Button? = null
    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }


    override fun onStop() {
        super.onStop()
        mPortScanHelper.onPause()
        ac.unregisterReceiver(mUsbReceiver)
        EventBus.getDefault().unregister(this)
    }

    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.usage_label_dialog)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setGravity(Gravity.CENTER)
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        // 设置点击外部空白处不关闭对话框
        setCanceledOnTouchOutside(false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (isLcok) {
            findViewById<Button>(R.id.butOpen).visibility = View.VISIBLE
        } else {
            findViewById<Button>(R.id.butOpen).visibility = View.GONE
        }

        findViewById<TextView>(R.id.cabinet).text = "$cabinet"
        findViewById<Button>(R.id.butClos).setOnClickListener {
            closHandle()
            dismiss()
        }

        findViewById<Button>(R.id.cloe).setOnClickListener {
            closHandle()
            lint.onCloses()
            dismiss()
        }

        //领用信息
        findViewById<Button>(R.id.useEn).setOnClickListener {
            if (mAdapter.data != null && mAdapter.data.size > 0) {
                val hasDuplicateCodes = hasDuplicateCodes(mAdapter.data)
                RcLog.info("========hasDuplicateCodes  $hasDuplicateCodes")
                if (!hasDuplicateCodes) {
                    closHandle()
                    lint.onUseClick(mAdapter.data)
                    dismiss()
                } else {
                    RcLog.info("===========2")
                    Toast.makeText(ac as Context, "不能重复领用", Toast.LENGTH_SHORT).show()
                }

            }
        }

        findViewById<Button>(R.id.butOpen).setOnClickListener {
            closHandle()
            dismiss()
            lint.openLock()
        }
        val findViewById = findViewById<RecyclerView>(R.id.reView)
        findViewById.layoutManager = LinearLayoutManager(ac)
        findViewById.adapter = mAdapter
        mPortScanHelper.onResume()
        registerUsbBroadcast()


        mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
        mCountDownHandler.sendEmptyMessage(Constants.WHAT_COUNT_DOWN_TWO)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            // 在这里处理子View的点击事件
            when (view.id) {
                R.id.imgDelete -> {
//                    mAdapter.data.removeAt(position)
//                    mAdapter.notifyItemRemoved(position)
                    lint.onPositions(position, mAdapter)
                }
            }
        }
    }

    private fun hasDuplicateCodes(list: List<ChemistryBean>): Boolean {
        val distinctCodes = list.map { it.code }.distinct()
        return distinctCodes.size != list.size
    }

    interface IIneSwipeLin {
        fun onCardInContent(cont: String)//刷卡返回
        fun onUseClick(data: MutableList<ChemistryBean>)//点击领用
        fun onCloses() //关闭清空数据
        fun openLock()//再次开门
        fun onPositions(position: Int, mData: UsageLabelDialogAdapter)//下标删除
        fun onTimerReply()//重置最外层弹框信息
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            // 在Dialog弹出时处理返回键事件
            // 处理完事件后返回true表示事件已经被消费，不再传递
            return true
        }
        mPortScanHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }


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

    }

    private val mPortScanHelper by lazy {
        PortScanHelper(ac, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                lint.onTimerReply()
                mCounter = 0
                if (!mHandleScanEvent) {
                    if (content.isNotBlank()) {
                        RcLog.info("========a==当前usb返回参数$content")
                        mHandleScanEvent = true
//                        handleScanEvent(content)
                        //所有通过查询二维码的参数 需要先判断  http开头的  然后进行截取
                        if (content.startsWith("http")) {
                            try {
                                val currentDateTimeString =
                                    BigDecimalUtils.extractParameterValue(content, "code")
                                RcLog.info("=======ce  $currentDateTimeString")
                                lint.onCardInContent(currentDateTimeString!!)
                            } catch (e: Exception) {
                                mHandleScanEvent = false
                                RcLog.info("刷卡异常了")
                                showToast("未获取到二维码信息，请重新扫描", 3000)
                            }
                        } else {
                            lint.onCardInContent(content)
                        }
                    }

                }
            }

        })
    }

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

    //刷卡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()
            ac.registerReceiver(mUsbReceiver, filter)
        }
    }

    fun setMessage(message: String, dataList: List<ChemistryBean>) {
        RcLog.info("====================数据过来了")
        mHandleScanEvent = false
        findViewById<ImageView>(R.id.img).visibility = View.GONE
        findViewById<Button>(R.id.butClos).visibility = View.GONE
        findViewById<LinearLayout>(R.id.linTow).visibility = View.VISIBLE
        findViewById<RecyclerView>(R.id.reView).visibility = View.VISIBLE     // 在这里可以设置接收到的消息参数
        mAdapter.setNewInstance(dataList.toMutableList())

    }

    fun notifyData(mChemistryBean: MutableList<ChemistryBean>) {
        mHandleScanEvent = false
        mAdapter.data = mChemistryBean
        mAdapter.notifyDataSetChanged()
    }

    fun notifyData() {
        mHandleScanEvent = false
    }

    private fun closHandle() {
        mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
        mCountDownHandler.removeCallbacksAndMessages(null)
    }

    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            if (Constants.WHAT_COUNT_DOWN_TWO == msg.what) {

                val countDown = Constants.OFFTIME_TIME - mCounter

                Log.d("======返回时间", "$countDown")
                if (countDown <= 0) {
                    dismiss()
                } else {
                    sendEmptyMessageDelayed(Constants.WHAT_COUNT_DOWN_TWO, 1000)
                }
                mCounter++
            }
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        // 在触摸事件发生时被调用
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                // 用户按下屏幕时的处理逻辑
                onUserInteraction()
            }
            MotionEvent.ACTION_MOVE -> {
                // 用户在屏幕上移动手指时的处理逻辑
            }
            MotionEvent.ACTION_UP -> {
                // 用户抬起手指时的处理逻辑
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun onUserInteraction() {
        // 在用户与对话框交互时的逻辑处理
        RcLog.info("=========弹框触发了")
        lint.onTimerReply()
        mCounter = 0
    }
}