package xn.hxp.weidith

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
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.blankj.utilcode.util.ActivityUtils
import xn.hxp.R
import xn.hxp.comm.Constants
import xn.hxp.receiver.OnSerialScanListener
import xn.hxp.receiver.PortScanHelper
import xn.hxp.receiver.UhfRfidKeyEventHelper
import xn.hxp.receiver.UhfRfidManager
import xn.hxp.receiver.UsbReceiver
import xn.hxp.ui.PrintBean
import xn.hxp.ui.adapter.CustomSpinnerAdapter
import xn.hxp.ui.adapter.LabelDialogAdapter
import com.blankj.utilcode.util.LogUtils
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.StockDetailsModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import xn.hxp.utils.AudioPlayer
import java.time.Instant
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

//新增-入库-列表 弹框
class LabelDialog(
    private val ac: Activity,
    private val number: String,
    private val layers: Int,
    private var density: String,
    private var chemicalName: String,
    private var ILin: IRfidClick
) : Dialog(ac) {
    private var listData: MutableList<StockDetailsModel>? = mutableListOf()
    private val mAdapter by lazy { LabelDialogAdapter() }
    private val mStoreyList = mutableListOf<String>()  //层数
    private var mLayers = 1  //默认层数已选择的层数
    private var recyclerView: RecyclerView? = null
    private var butClos: Button? = null

    ///刷卡===============获取RFID 电子标签=====
    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数

    // 外置超高频RFID读卡器解析器
    private val mUhfRfidHelper = UhfRfidKeyEventHelper { content ->
        mCounter = 0
        if (!mHandleScanEvent && content.isNotBlank()) {
            mHandleScanEvent = true
            var isDuplicate = false
            mAdapter.data.forEachIndexed { index, stockDetailsModel ->
                if (stockDetailsModel.rfidCode != null && stockDetailsModel.rfidCode == content) {
                    showToast("RFID不能重复")
                    mHandleScanEvent = false
                    isDuplicate = true
                    return@forEachIndexed
                }
            }
            if (!isDuplicate) {
                upViewRfid(content)
            }
        }
    }

    @SuppressLint("NewApi")
    private val formatter: DateTimeFormatter =
        DateTimeFormatter.ofPattern("yyMMddHHmmssSSS")

    @SuppressLint("NewApi")
    fun getCurrentDateTimeString(): String {
        return LocalDateTime.now().format(formatter)
    }

    private fun getLast8DigitsOfTimestamp(): String {
        val timestamp = System.currentTimeMillis().toString() // 获取当前时间戳并转换为字符串
        return if (timestamp.length >= 8) {
            timestamp.takeLast(8) // 获取字符串的最后8位
        } else {
            timestamp // 如果时间戳长度小于8位，返回完整的时间戳字符串
        }
    }

    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.label_dialogs)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setGravity(Gravity.CENTER)
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        // 设置点击外部空白处不关闭对话框
        setCanceledOnTouchOutside(false)
    }


    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerUsbBroadcast()
        findViewById<TextView>(R.id.chemicalName).text = "$chemicalName"
        findViewById<TextView>(R.id.density).text = "净重：${density}"
        recyclerView = findViewById<RecyclerView>(R.id.rvView)
        //初始化柜子层数
        for (i in 1..layers) {
            mStoreyList.add("$i")
        }

        val sPinner = findViewById<Spinner>(R.id.sPinner)
        val customAdapter = CustomSpinnerAdapter(ac, mStoreyList)
        sPinner.adapter = customAdapter

        sPinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                // 当用户选择某一项时被调用
                mLayers = mStoreyList[position].toInt()
                LogUtils.i("=======当前1选择 $mLayers")
            }

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

        val toInt = number.toInt() + 1  //根据输入的数量  生成数据
        for (i in 1 until toInt) {
            // 在这里编写循环体的逻辑
            val currentDateTimeString = getCurrentDateTimeString()
            LogUtils.i("====CAS码生成 $number  $currentDateTimeString")
            val takeLast = currentDateTimeString.takeLast(7)
            var wxCode = "${HttpConfig.API_BASE_QC_URL}?code=${takeLast}&type=9"
            var bean = StockDetailsModel(null, null, takeLast, i, wxCode)
            listData!!.add(bean)
            Thread.sleep(10)
        }
        val layoutManager = LinearLayoutManager(ac, LinearLayoutManager.VERTICAL, false)
        recyclerView!!.layoutManager = layoutManager
        recyclerView!!.adapter = mAdapter
        mAdapter.setNewInstance(listData)

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            // 在这里处理子View的点击事件
            when (view.id) {
                R.id.imgDelete -> {
                    var count = 1
                    mAdapter.data.removeAt(position)
                    mAdapter.data.forEach {
                        it.no = count
                        count++
                    }
//                    mAdapter.notifyItemRemoved(position)
                    mAdapter.notifyDataSetChanged()
                }

            }
        }

        findViewById<Button>(R.id.butClos).setOnClickListener {
            closHandle()
            dismiss()
            ILin.onItemClick(null, 1)
        }

        findViewById<Button>(R.id.determine).setOnClickListener {
            closHandle()
            if (mAdapter.data.size > 0) {
                var isOk = false
                mAdapter.data.forEach { it ->
                    if (it.rfidCode != null) {
                        isOk = true
                    }
                }

//                val allNotNull = mAdapter.data.all { it.rfidCode != null }
//                if (allNotNull) {
//                    println("所有数据的字段 a 都不为 null")
//                } else {
//                    println("至少有一条数据的字段 a 为 null")
//                    showToast("RFID不能为空")
//                    return@setOnClickListener
//                }
//                dismiss()
//                ILin.onItemClick(mAdapter.data, mLayers)

                LogUtils.i("=======当前2选择 $mLayers")
                if (isOk) {
                    val allNotNull = mAdapter.data.all { it.rfidCode != null }
                    if (allNotNull) {
                        println("所有数据的字段 a 都不为 null")
                    } else {
                        println("至少有一条数据的字段 a 为 null")
                        showToast("RFID不能为空")
                        return@setOnClickListener
                    }
                    dismiss()
                    LogUtils.i("=======当前4选择 $mLayers")
                    ILin.onItemClick(mAdapter.data, mLayers)
                } else {
                    //直接需要判断是否打印标签
                    dismiss()
                    LogUtils.i("=======当前5选择 $mLayers")
                    ILin.opTageCode(mAdapter.data, mLayers)
                }
            } else {
                dismiss()
                ILin.onItemClick(null, 1)
            }
        }
        AudioPlayer.getInstance().play(R.raw.scan_label)
//        customDialogView(0, "请扫描标签")
        butClos = findViewById<Button>(R.id.butClos)

        mCountDownHandler.removeMessages(Constants.WHAT_COUNT_DOWN_TWO)
        mCountDownHandler.sendEmptyMessage(Constants.WHAT_COUNT_DOWN_TWO)
    }

    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

                if (countDown <= 0) {
                    dismiss()
                } else {
                    sendEmptyMessageDelayed(Constants.WHAT_COUNT_DOWN_TWO, 1000)
                }
                mCounter++
            }
        }
    }

    interface IRfidClick {
        fun onItemClick(modelList: MutableList<StockDetailsModel>?, layer: Int)
        fun onPrint(tagCode: String, wxCode: String, rfidCode: String, position: Int) //回显需要打印的数据
        fun opTageCode(data: MutableList<StockDetailsModel>, layer: Int)//打印所有编码
    }


    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            return true
        }
        // 外置超高频RFID读卡器输入
        if (UhfRfidManager.isEnabled(ac) && UhfRfidManager.isUhfRfidEvent(ac, event)) {
            if (UhfRfidManager.isPageWhitelisted(ac, UhfRfidManager.PAGE_STORAGE_RFID)) {
                mUhfRfidHelper.analysisKeyEvent(event)
            }
            return true
        }
        mPortScanHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

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

    }

    private var mCounter = 0
    private val mPortScanHelper by lazy {
        PortScanHelper(ac, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, rfid: String) {
                mCounter = 0
                if (!mHandleScanEvent) {
                    if (rfid.isNotBlank()) {
                        LogUtils.i("========aa==当前rfid返回参数$rfid")
                        mHandleScanEvent = true
                        var isOk = false
                        mAdapter.data.forEachIndexed { index, stockDetailsModel ->
                            if (stockDetailsModel.rfidCode != null && stockDetailsModel.rfidCode.equals(
                                    rfid
                                )
                            ) {
                                showToast("RFID不能重复")
                                mHandleScanEvent = false
                                isOk = true
                                return@forEachIndexed
                            }
                        }
                        if (isOk == false) {
                            upViewRfid(rfid)
                        }
                    }

                }
            }

        })
    }

    //刷卡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)
        }
    }

    //更新Rfid
    fun upViewRfid(rfid: String) {
        val cleanRfid = rfid.replace("\r", "").replace("\n", "").trim()
        if (cleanRfid.isEmpty()) {
            mHandleScanEvent = false
            return
        }
        var tagCode: String = ""
        var wxCode: String = ""
        var rfidCode: String = ""
        var position = -1
        for (index in mAdapter.data.indices) {
            if (mAdapter.data[index].rfidCode == null) {
                mAdapter.data[index].rfidCode = cleanRfid
                tagCode = mAdapter.data[index].tagCode!!
                wxCode = mAdapter.data[index].wxCode!!
                rfidCode = mAdapter.data[index].rfidCode!!
                position = index
                LogUtils.i("====下标 ${index + 1}  ${mAdapter.data.size}")
                mHandleScanEvent = false
                if (index + 1 == mAdapter.data.size) {
                    //没有内容需要打印
                    mHandleScanEvent = true
                }
                break
            }
        }
        mAdapter.notifyDataSetChanged()
        val isOk = mAdapter.data.lastOrNull()
        if (!mHandleScanEvent || (mHandleScanEvent && isOk!!.rfidCode != null)) {
            LogUtils.i("打印回调========")
            //回调打印
            ILin.onPrint(tagCode, wxCode, rfidCode, position)
        }


    }

    // 在自定义对话框类中定义一个方法来显示 Toast 消息
    fun showToast(message: String) {
        Toast.makeText(ActivityUtils.getTopActivity(), message, Toast.LENGTH_SHORT).show()
    }

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

    fun getRfidTag(position: Int) {
        //不能打印
        mHandleScanEvent = false
        mAdapter.data[position].rfidCode = null
//        mAdapter.setData(position, mAdapter.data[position])
        mAdapter.notifyDataSetChanged()
    }

    fun printingCom() {
        dismiss()
        ILin.onItemClick(mAdapter.data, mLayers)
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        // 在触摸事件发生时被调用
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                // 用户按下屏幕时的处理逻辑
                onUserInteraction()
            }

            MotionEvent.ACTION_MOVE -> {
                // 用户在屏幕上移动手指时的处理逻辑
            }

            MotionEvent.ACTION_UP -> {
                // 用户抬起手指时的处理逻辑
            }
        }
        return super.dispatchTouchEvent(ev)
    }

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