package com.qimai.android.widget

import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.Utils
import com.qmai.zqtoolkit.LEDHub
import com.qmai.zqtoolkit.ScaleHub
import com.qmai.zqtoolkit.ScaleInfo
import com.qmai.zqtoolkit.config.SHOP_ASSITANT_2B
import com.qmai.zqtoolkit.config.SHOP_ASSITANT_2C
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.*

class ZqToolActivity : AppCompatActivity() {
    private var TAG = "EBSDK"
    private var adpBaud: ArrayAdapter<String>? = null
    private var spinBaud: Spinner? = null
    private var nSelSpinBaud = 2
    private var adpPort: ArrayAdapter<String>? = null
    private var spinPort: Spinner? = null
    private var nSelSpinPort = 1

    private var etTare: EditText? = null
    private var tvWeight: TextView? = null
    private var tvLivingWeight: TextView? = null
    private var tv_scale_info: TextView? = null
    private var tvTare: TextView? = null
    private var tvState: TextView? = null
    private var butConnect: Button? = null
    private var butSetZero: Button? = null
    private var butNetWeight: Button? = null
    private var butClearTare: Button? = null
    private var butSetTare: Button? = null
    private var butAutoRead: Button? = null
    private var ButAutoStopRead: Button? = null
    private var ButSend: Button? = null
    private var etdata: EditText? = null
    private var ButConnectLED: Button? = null
    private var rb_zq: RadioButton? = null
    private var rb_sunmi: RadioButton? = null
    private var rb_dj: RadioButton? = null

    private lateinit var sp: SharedPreferences;

    private var m_bConnected = false
    private var m_bThreadAutoReadExit = true
//    private val  ScaleHub.instance by lazy {
//        ViewModelProvider(this).get(ScaleHub::class.java)
//    }


    private var mContext: Context? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_zqtool)
        //
        mContext = this

        //
        //
        etdata = findViewById<View>(R.id.etdata) as EditText
        ButSend = findViewById<View>(R.id.ButSend) as Button
        etTare = findViewById<View>(R.id.etTare) as EditText
        tvWeight = findViewById<View>(R.id.tvWeight) as TextView
        tvLivingWeight = findViewById<View>(R.id.tvLivingWeight) as TextView
        tv_scale_info = findViewById<View>(R.id.tv_scale_info) as TextView
        tvTare = findViewById<View>(R.id.tvTare) as TextView
        tvState = findViewById<View>(R.id.tvState) as TextView
        butConnect = findViewById<View>(R.id.ButConnect) as Button
        butConnect!!.setOnClickListener(MyClickListener)
        butSetZero = findViewById<View>(R.id.ButSetZero) as Button
        butSetZero!!.setOnClickListener(MyClickListener)
        butNetWeight = findViewById<View>(R.id.ButNetweight) as Button
        butNetWeight!!.setOnClickListener(MyClickListener)
        butClearTare = findViewById<View>(R.id.ButClearTare) as Button
        butClearTare!!.setOnClickListener(MyClickListener)
        butSetTare = findViewById<View>(R.id.ButSetTare) as Button
        butSetTare!!.setOnClickListener(MyClickListener)
        butAutoRead = findViewById<View>(R.id.ButAutoRead) as Button
        butAutoRead!!.setOnClickListener(MyClickListener)
        ButAutoStopRead = findViewById<View>(R.id.ButAutoStopRead) as Button
        ButConnectLED = findViewById<View>(R.id.ButConnectLED) as Button
        ButAutoStopRead!!.setOnClickListener(MyClickListener)
        ButConnectLED!!.setOnClickListener(MyClickListener)
        ButSend!!.setOnClickListener(MyClickListener)
        //

        rb_zq = findViewById<View>(R.id.rb_zq) as RadioButton
        rb_sunmi = findViewById<View>(R.id.rb_sunmi) as RadioButton
        rb_dj = findViewById<View>(R.id.rb_dj) as RadioButton

        rb_zq!!.setOnClickListener(MyClickListener)
        rb_sunmi!!.setOnClickListener(MyClickListener)
        rb_dj!!.setOnClickListener(MyClickListener)
        sp = getSharedPreferences("com.example.zqebsdksample_preferences", MODE_PRIVATE)
        //
        val ListPort: MutableList<String> = ArrayList()
        ListPort.add("ttyS0")
        ListPort.add("ttyS1")
        ListPort.add("ttyS2")
        ListPort.add("ttyS3")
        ListPort.add("ttyS4")
        ListPort.add("ttyUSB0")
        ListPort.add("ttyUSB1")
        ListPort.add("ttyUSB2")
        ListPort.add("s3c2410_serial3")
        adpPort = ArrayAdapter(this, android.R.layout.simple_spinner_item, ListPort)
        adpPort!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinPort = findViewById<View>(R.id.SpinPort) as Spinner
        spinPort!!.adapter = adpPort
        nSelSpinPort = sp.getInt("SelSpinPort", 2)
        spinPort!!.setSelection(nSelSpinPort)
        spinPort!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(arg0: AdapterView<*>?, arg1: View, arg2: Int, arg3: Long) {
                nSelSpinPort = arg2
                val editor = sp.edit()
                editor.putInt("SelSpinPort", nSelSpinPort)
                editor.commit()
            }

            override fun onNothingSelected(arg0: AdapterView<*>?) {}
        }
        //
        val ListBaud: MutableList<String> = ArrayList()
        ListBaud.add("2400")
        ListBaud.add("4800")
        ListBaud.add("9600")
        ListBaud.add("19200")
        ListBaud.add("38400")
        ListBaud.add("57600")
        ListBaud.add("115200")
        adpBaud = ArrayAdapter(this, android.R.layout.simple_spinner_item, ListBaud)
        adpBaud!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinBaud = findViewById<View>(R.id.SpinBaud) as Spinner
        spinBaud!!.adapter = adpBaud
        nSelSpinBaud = sp.getInt("SelSpinBaud", 2)
        spinBaud!!.setSelection(nSelSpinBaud)
        spinBaud!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(arg0: AdapterView<*>?, arg1: View, arg2: Int, arg3: Long) {
                nSelSpinBaud = arg2
                val editor = sp.edit()
                editor.putInt("SelSpinBaud", nSelSpinBaud)
                editor.commit()
            }

            override fun onNothingSelected(arg0: AdapterView<*>?) {}
        }
        var usbManager = Utils.getApp().getSystemService(Context.USB_SERVICE) as UsbManager?
        usbManager?.deviceList?.forEach {
            Log.v("cccc", GsonUtils.toJson(it.value))
//            if (it.value.productId == ACLAS_PRODUCTID && it.value.vendorId == ACLAS_VENDORID) {
//                return it.value.productName?:""
//            }
        }

        lifecycleScope.launch {
            ScaleHub.connectState.collect {
                Log.v("ZqToolActivity", it.toString())
                if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                    m_bConnected = it.isConnect
                    if (m_bConnected) {
                        butConnect?.text = "断开"
                    } else {
                        butConnect?.text = "连接"
                    }
                    Log.d(TAG, it.toString())
                }
            }
        }
        lifecycleScope.launch {
            ScaleHub.livingWeight.collect {
                if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                    Log.d(TAG, it.toString())
                    tvTare?.text = it.tare
                    if (it.isStable) {
                        tvWeight?.text = it.weight
                        tvState?.text = "稳定"
                        tvState?.setBackgroundColor(Color.GREEN)
                        tvLivingWeight?.text =
                            "实时重量" + it.weight + " 单位" + it.unit + "time:" + System.currentTimeMillis()
                    } else {
                        tvState?.setBackgroundColor(Color.RED)
                        tvState?.text = "不稳定"
                        tvLivingWeight?.text =
                            "实时重量" + it.weight + " 单位" + it.unit + "time:" + System.currentTimeMillis()
                    }
                }
            }

        }
        lifecycleScope.launch {
            ScaleHub.scaleLog.collect {
                Log.v("aaa",it)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        ScaleHub.stopReadData()
        m_bThreadAutoReadExit = true
        if (m_bConnected) {
            m_bConnected = false
            ScaleHub.disconnect()
            butConnect!!.text = "连接"
        }
    }

    private val MyClickListener =
        View.OnClickListener { v ->
            var nRet: Int
            when (v.id) {
                R.id.ButConnect -> {
                    if (!m_bConnected) {
                        ScaleHub.connect(this, ScaleInfo(appType = SHOP_ASSITANT_2C, connectType = 0))
//                        Thread {
//                            if (zqeb.EB_Connect(
//                                    String.format(
//                                        "%s:%s",
//                                        spinPort!!.selectedItem.toString(),
//                                        spinBaud!!.selectedItem.toString()
//                                    ),
//                                    v.context
//                                ) == PrinterConst.ErrorCode.SUCCESS
//                            ) {
//                                m_bConnected = true
//                                butConnect!!.text = "断开"
//                            }
//                        }.start()
                    } else {
                        m_bThreadAutoReadExit = true
                        ScaleHub.disconnect()
                        m_bConnected = false
                        butConnect!!.text = "连接"
                    }
                }
                R.id.ButSetZero -> {
                    if (m_bConnected) {
                        ScaleHub.setZero()
                    }
                }
                R.id.ButConnectLED -> {
                }
                R.id.ButNetweight -> {
                    if (m_bConnected) {
                        ScaleHub.setNetWeight()
                    }
                }
                R.id.ButClearTare -> {
                    if (m_bConnected) {
                        ScaleHub.clearTare()
                    }
                }
                R.id.ButSetTare -> {
                    if (m_bConnected) {
                        // zqeb.EB_SetTare(java.lang.Double.valueOf(etTare!!.text.toString()))
                    }
                }
                R.id.ButAutoRead -> {
                    if (m_bConnected) {
                        ScaleHub.readData()
                    }
                }
                R.id.rb_zq -> {
                   // ScaleHub.initScale(QmScaleBrand.ZQEB)
                }
                R.id.rb_sunmi -> {
                    //ScaleHub.initScale(QmScaleBrand.SUNMI)
                }
                R.id.rb_dj -> {
                    //ScaleHub.initScale(QmScaleBrand.ACLAS)
                }
                R.id.ButSend -> {
                    if (m_bConnected) {
//                        val text: String = etdata?.text.toString().trim()
//                        if (TextUtils.isEmpty(text) || text.length % 2 != 0) {
//                            ToastUtils.showShort("无效数据")
//                            return@OnClickListener
//                        }


                        try {
                            // ScaleHub.sendLEDTotalPrice(etdata?.text.toString())
                            LEDHub.sendLEDLight(zero = false, stable = false, tare = true)
                        } catch (e: Exception) {
                        }
                    }
                }
                R.id.ButAutoStopRead -> {
                    //  if (m_bConnected) {
                    ScaleHub.stopReadData()
                    //}
//                    val strText = butAutoRead!!.text.toString()
//                    if (strText == "开始读数") {
//                        butAutoRead!!.text = "停止读数"
//                        m_bThreadAutoReadExit = false
//                        mHandlerAutoRead = Handler()
//                        Thread { //
//                            m_bThreadAutoReadRunning = true
//                            while (!m_bThreadAutoReadExit) {
//                                if (m_bConnected) {
//                                    ReadData()
//                                }
//                                try {
//                                    Thread.sleep(80)
//                                } catch (e: InterruptedException) {
//                                    // TODO Auto-generated catch block
//                                    e.printStackTrace()
//                                }
//                            }
//                            m_bThreadAutoReadRunning = false
//                            mHandlerAutoRead!!.post { butAutoRead!!.text = "开始读数" }
//                        }.start()
//                    } else {
//                        m_bThreadAutoReadExit = true
//                    }
                }
            }
        }


    /**
     * 把十六进制表示的字节数组字符串，转换成十六进制字节数组
     *
     * @param
     * @return byte[]
     */
    fun hexStr2bytes(hex: String): ByteArray {
        val len = hex.length / 2
        val result = ByteArray(len)
        val achar = hex.uppercase(Locale.getDefault()).toCharArray()
        for (i in 0 until len) {
            val pos = i * 2
            result[i] =
                (hexChar2byte(achar[pos]) shl 4 or hexChar2byte(achar[pos + 1])).toByte()
        }
        return result
    }

    private fun hexChar2byte(c: Char): Int {
        return when (c) {
            '0' -> 0
            '1' -> 1
            '2' -> 2
            '3' -> 3
            '4' -> 4
            '5' -> 5
            '6' -> 6
            '7' -> 7
            '8' -> 8
            '9' -> 9
            'a', 'A' -> 10
            'b', 'B' -> 11
            'c', 'C' -> 12
            'd', 'D' -> 13
            'e', 'E' -> 14
            'f', 'F' -> 15
            else -> -1
        }
    }
}