package com.rehome.scbaxj.base

import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ApplicationInfo
import android.nfc.NdefMessage
import android.nfc.NfcAdapter
import android.nfc.tech.*
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.viewbinding.ViewBinding

import com.bjzc.bhzhgd.R
import com.bjzc.bhzhgd.utils.AutoToolbar
import com.bjzc.bhzhgd.utils.ControllerActivity
import com.bjzc.bhzhgd.utils.StatusBarUtil
import com.zhy.autolayout.AutoLayoutActivity
import java.nio.charset.StandardCharsets
import java.util.*

/**
 *   Create By HuangWenFei
 *   创建日期：2023-01-17 14:04
 *   描述：基类使用ViewBinding，ButterKnife已被作者废弃，不再维护
 */
abstract class BaseActivityAutoToolbarViewBinding<T : ViewBinding> : AutoLayoutActivity() {
    protected lateinit var binding: T
    protected lateinit var mToolbar: AutoToolbar
    protected lateinit var context: Context
    private var nfcAdapter: NfcAdapter? = null
    private var readResult = ""
    private var pendingIntent: PendingIntent? = null
    private lateinit var mFilters: Array<IntentFilter>
    private lateinit var mTechLists: Array<Array<String>>
    private var isFirst = true
    private var ndef: IntentFilter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = getViewBinding()
        mToolbar = getToolbar()
        setContentView(binding.root)
        context = this
        ControllerActivity.getAppManager().addActivity(this)
        initView()
        initData()
    }

    protected abstract fun getViewBinding(): T
    protected abstract fun getToolbar(): AutoToolbar

    //初始化View
    protected abstract fun initView()

    //初始化数据
    protected abstract fun initData()


    fun startActivity(cls: Class<out Activity?>?) {
        val intent = Intent(this, cls)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        startActivity(intent)
    }

    override fun onPause() {
        super.onPause()
        if (nfcAdapter != null) {
            nfcAdapter!!.disableForegroundDispatch(this)
        }
    }

    /*
     * 重写onResume回调函数的意义在于处理多次读取NFC标签时的情况
     */
    override fun onResume() {
        super.onResume()

        // 前台分发系统,这里的作用在于第二次检测NFC标签时该应用有最高的捕获优先权.
        if (nfcAdapter != null && pendingIntent != null) {
            nfcAdapter!!.enableForegroundDispatch(
                this, pendingIntent, mFilters,
                mTechLists
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ControllerActivity.getAppManager().finishActivity(this)
    }

    /**
     * 显示toast
     *
     * @param text
     */
    fun showToast(text: String?) {
        if (text != null && text.trim { it <= ' ' } != "") {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
        }
    }

    fun showToast(id: Int) {
        Toast.makeText(this, id, Toast.LENGTH_SHORT).show()
    }

    /**
     * 检测工作,判断设备的NFC支持情况
     *
     * @return
     */
    private fun ifNFCUse(): Boolean {
        if (nfcAdapter == null) {
            Toast.makeText(this, "设备不支持NFC！", Toast.LENGTH_SHORT).show()
            return false
        }
        if (!nfcAdapter!!.isEnabled) {
            Toast.makeText(this, "请在系统设置中先启用NFC功能！", Toast.LENGTH_SHORT).show()
            return false
        }
        return true
    }

    /**
     * 初始化过程
     */
    fun initNFC() {

        //NFC适配器，所有的关于NFC的操作从该适配器进行
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (!ifNFCUse()) {
            return
        }
        //将被调用的Intent，用于重复被Intent触发后将要执行的跳转
        pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
        } else {
            PendingIntent.getActivity(
                this,
                0,
                Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0
            )
        }


        //设定要过滤的标签动作，这里只接收ACTION_NDEF_DISCOVERED类型
        ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        ndef!!.addCategory("*/*")
        mFilters = arrayOf(ndef!!) // 过滤器
        mTechLists = arrayOf(
            arrayOf(NfcA::class.java.name), arrayOf(
                NfcF::class.java.name
            ), arrayOf(NfcB::class.java.name), arrayOf(
                NfcV::class.java.name
            ), arrayOf(MifareClassic::class.java.name), arrayOf(
                MifareUltralight::class.java.name
            ), arrayOf(IsoDep::class.java.name)
        ) // 允许扫描的标签类型
        if (isFirst) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent
                    .action
            ) {
                ndef = IntentFilter()
                if (readFromTag(intent)) {
                    Toast.makeText(this, readResult, Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "标签数据为空", Toast.LENGTH_SHORT).show()
                }
            }
            isFirst = false
        }
    }

    /**
     * 2进制to 16进制
     * @param src
     * @return
     */
    private fun bytesToHex(src: ByteArray?): String {
        val sb = StringBuffer()
        if (src == null || src.isEmpty()) {
            return ""
        }
        var sTemp: String
        for (i in src.indices) {
            sTemp = Integer.toHexString(0xFF and src[i].toInt())
            if (sTemp.length < 2) {
                sb.append(0)
            }
            sb.append(sTemp.uppercase(Locale.getDefault()))
        }
        return sb.toString()
    }

    /*
     * 有必要要了解onNewIntent回调函数的调用时机,请自行上网查询
     */
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action || NfcAdapter.ACTION_TECH_DISCOVERED == intent.action) {
            val id = bytesToHex(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID))
            handleNfc(id)

//            if (readFromTag(intent)) {
//                Toast.makeText(this, readResult, Toast.LENGTH_SHORT).show();
//                handleNfc(readResult);
//            } else {
//                Toast.makeText(this, "ID:" + id + "  标签数据为空", Toast.LENGTH_SHORT).show();
//            }
        }
    }

    /**
     * 读取NFC标签数据的操作
     */
    private fun readFromTag(intent: Intent): Boolean {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
            val rawArray = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
            if (rawArray != null) {
                val mNdefMsg = rawArray[0] as NdefMessage
                val mNdefRecord = mNdefMsg.records[0]
                if (mNdefRecord != null) {
                    readResult = String(mNdefRecord.payload, StandardCharsets.UTF_8)
                    return true
                }
                //return false;
            }
            return false
        }
        return false
    }

    //处理NFC
    open fun handleNfc(result: String?) {
        //showToast(result);
    }

    open fun setBack() {
        mToolbar.setNavigationIcon(R.mipmap.ac_back_icon)
        mToolbar.setNavigationOnClickListener { finish() }
    }

    protected open fun setStatusBar() {
        StatusBarUtil.setColor(this, resources.getColor(R.color.colorPrimary))
    }

    open fun showLog(logText: String?) {
        if (isApkInDebug(context)) {
            if (TextUtils.isEmpty(logText)) {
                Log.i("app", "logText is null")
            } else {
                Log.i("app", logText!!)
            }
        }
    }
    /**
     * 判断当前应用是否是debug状态
     */
    fun isApkInDebug(context: Context): Boolean {
        try {
            val info = context.applicationInfo
            return (info.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
        } catch (e: Exception) {
            return false
        }
    }
}