package aicare.net.cn.sdk.ailinksdkdemoandroid.modules.caseTreasure

import aicare.net.cn.sdk.ailinksdkdemoandroid.R
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import cn.net.aicare.modulelibrary.module.bleCaseTreasure.BleCaseTreasureDevice
import com.pingwang.bluetoothlib.listener.OnCallbackBle
import com.pingwang.bluetoothlib.utils.BleStrUtils
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.KBleBaseNewActivity
import aicare.net.cn.sdk.ailinksdkdemoandroid.databinding.ActivityBleCaseTreasureBinding
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L
import java.text.SimpleDateFormat
import java.util.Locale


/**
 * 病例宝界面
 * @author xing
 * @date 2025/06/03
 * @constructor 创建[BleCaseTreasureActivity]
 */
class BleCaseTreasureActivity : KBleBaseNewActivity<ActivityBleCaseTreasureBinding>(), BleCaseTreasureDevice.OnBleCaseTreasureListener,
    View.OnClickListener, OnCallbackBle {
    private val REFRESH_DATA = 3
    private val LOOPSEND_KEY = 4
    private val mList: ArrayList<String> = arrayListOf()
    private var listAdapter: ArrayAdapter<*>? = null
    private var mMac = ""
    private var mBleCaseTreasureDevice: BleCaseTreasureDevice? = null
    private var spList = arrayOf("ASCII")
    private var mSelectPosition = 0
    private var mSendIntervalMs = 1000L
    private var mSendCountAll = 0
    private var mSendCount = 0
    private var mSendData = ""

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                REFRESH_DATA -> listAdapter?.notifyDataSetChanged()
                LOOPSEND_KEY -> {
                    if (mSendCount >= mSendCountAll) {
                        addLog("已循环发送完成:$mSendCount")
                        removeMessages(LOOPSEND_KEY)
                        return
                    }
                    val charsetName = spList[mSelectPosition]
                    mBleCaseTreasureDevice?.sendString(charsetName, "$mSendCount:$mSendData")
                    mSendCount++
                    binding.tvSendCount.text = "$mSendCount"
                    sendEmptyMessageDelayed(LOOPSEND_KEY, mSendIntervalMs)
                }
            }
        }
    }

    override fun getLayoutView(): ActivityBleCaseTreasureBinding {
        return ActivityBleCaseTreasureBinding.inflate(layoutInflater)
    }

    override fun initListener() {
        binding.btnConnect.setOnClickListener(this)
        binding.btnDisconnect.setOnClickListener(this)
        binding.btnClear.setOnClickListener(this)
        binding.btnGetVersion.setOnClickListener(this)
        binding.btnGetDeviceStatus.setOnClickListener(this)
        binding.btnSendData.setOnClickListener(this)
        binding.btnSendSpeed.setOnClickListener(this)
        binding.btnLoopSend.setOnClickListener(this)
        binding.btnStopSend.setOnClickListener(this)
        binding.btnResetCount.setOnClickListener(this)
        binding.spEncoding.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                mSelectPosition = position
                addLog("选择的项:${spList[position]}")

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                L.i("没有选择")
            }
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnConnect -> {
                mBleManager.connectDevice(mMac)
            }

            R.id.btnDisconnect -> {
                mBleManager.disconnect(mMac)
            }

            R.id.btnClear -> {
                mList.clear()
                mHandler.sendEmptyMessage(REFRESH_DATA)
            }

            R.id.btnGetVersion -> {
                mBleCaseTreasureDevice?.getVersion()

            }

            R.id.btnGetDeviceStatus -> {
                mBleCaseTreasureDevice?.getDeviceStatus()
            }

            R.id.btnSendData -> {
                val data = binding.etData.text.toString()
                if (data.isEmpty()) {
                    addLog("发送的内容不能为空")
                    return
                }
                val charsetName = spList[mSelectPosition]
                mBleCaseTreasureDevice?.sendString(charsetName, data)
            }

            R.id.btnSendSpeed -> {
                val data = binding.etSpeedUs.text.toString()
                mBleCaseTreasureDevice?.setSpeed(data.toInt())
            }

            R.id.btnLoopSend -> {
                mSendCountAll = binding.etCount.text.toString().toInt()
                mSendIntervalMs = binding.etIntervalMs.text.toString().toLong()
                mSendData = binding.etData.text.toString()
                if (mSendData.isEmpty()) {
                    addLog("发送的内容不能为空")
                    return
                }
                if (mSendIntervalMs<1000){
                    addLog("发送间隔不能小于1000")
                    Toast.makeText(this,"发送间隔不能小于1000", Toast.LENGTH_LONG).show()
                    return
                }
                mHandler.removeMessages(LOOPSEND_KEY)
                mHandler.sendEmptyMessage(LOOPSEND_KEY)
            }

            R.id.btnStopSend -> {
                mHandler.removeMessages(LOOPSEND_KEY)
            }
            R.id.btnResetCount -> {
                mSendCount = 0
                binding.tvSendCount.text = "$mSendCount"
                mHandler.removeMessages(LOOPSEND_KEY)
            }

            else -> {}
        }
    }

    override fun initData() {
        //设置常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        mMac = intent.getStringExtra("mac") ?: ""
        if (mMac.isEmpty()) {
            finish()
            return
        }
        binding.tvMac.text = mMac
        listAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, mList)
        binding.listview.adapter = listAdapter
        spList = resources.getStringArray(R.array.spinner_encoding_format)
        val adapter = ArrayAdapter.createFromResource(this, R.array.spinner_encoding_format, android.R.layout.simple_spinner_item)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spEncoding.adapter = adapter
        binding.spEncoding.setSelection(mSelectPosition)
        onServiceSuccess()
    }

    override fun onServiceSuccess() {
        if (mMac.isEmpty() || mBleManager == null) {
            return
        }
        val bleDevice = mBleManager.getBleDevice(mMac)
        bleDevice?.let {
            addLog("连接成功:${mMac}")
            mBleManager.setOnCallbackBle(this)
            mBleCaseTreasureDevice = BleCaseTreasureDevice(bleDevice)
            mBleCaseTreasureDevice?.addListener(this@BleCaseTreasureActivity)
        }

    }

    override fun onServiceErr() {

    }

    override fun unbindServices() {

    }

    override fun bleOpen() {
        addLog("蓝牙已打开")
    }

    override fun bleClose() {
        addLog("蓝牙已关闭")
    }

    override fun onServicesDiscovered(mac: String?) {
        onServiceSuccess()
    }

    override fun onDisConnected(mac: String?, code: Int) {
        addLog("断开连接:$mac  错误码:$code")
        mHandler.removeMessages(LOOPSEND_KEY)
    }

    override fun onVersion(version: String?) {
        addLog("版本号:$version")
    }

    override fun onDeviceStatus(status: Int, dataId: Int, sendId: Int) {
        addLog("设备状态:$status,病例ID:$dataId,已传帧ID:$sendId")
    }

    override fun onSendDataSchedule(cur: Int, size: Int) {
        addLog("已发送帧数:$cur,总帧数:${size}, 发送完成")
    }

    override fun onSendFail() {
        addLog("发送失败")
    }

    override fun onSendDataId(dataId: Int) {
        addLog("发送的数据ID:$dataId")
    }

    override fun onSendHex(hex: ByteArray?) {
        L.i("发送的数据:${BleStrUtils.byte2HexStr(hex)}")
//        addLog("发送的数据:${BleStrUtils.byte2HexStr(hex)}")
    }

    override fun onSetSpeed(status: Int) {
        addLog("设置打字速度:${if (status == 0) "成功" else "失败"}")
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeMessages(LOOPSEND_KEY)
    }

    //-----------log---------------


    private var mOldLog = ""
    private var sdf: SimpleDateFormat? = null

    /**
     * 添加日志
     *
     * @param log 日志
     */
    private fun addLog(log: String) {
        if (mOldLog.equals(log, ignoreCase = true)) {
            return
        }
        if (sdf == null) {
            sdf = SimpleDateFormat("HH:mm:ss:SSS", Locale.US)
        }
        mOldLog = log
        mList.add(
            0, """
     ${sdf!!.format(System.currentTimeMillis())}：
     $log
     """.trimIndent()
        )
        mHandler.sendEmptyMessage(REFRESH_DATA)
    }
}