package com.rehome.bhdxj.base;

/**
 * Create By HuangWenFei
 * 创建日期：2023-02-06 14:58
 * 描述：
 */


import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.viewbinding.ViewBinding;
import android.view.View;
import android.widget.Toast;
import com.rehome.bhdxj.R;
import com.rehome.bhdxj.utils.ControllerActivity;
import com.rehome.bhdxj.utils.OAToolbar;
import com.zhy.autolayout.AutoLayoutActivity;
import java.nio.charset.StandardCharsets;

/**
 * Create By HuangWenFei
 * 创建日期：2023-01-11 14:25
 * 描述：基类使用ViewBinding，ButterKnife已被作者废弃，不再维护
 */
public abstract class BaseViewBindingActivity<T extends ViewBinding> extends AutoLayoutActivity {


    protected T binding;
    OAToolbar mToolbar;
    public Context context;
    private NfcAdapter nfcAdapter;
    private String readResult = "";
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private boolean isFirst = true;
    private IntentFilter ndef;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = getViewBinding();
        mToolbar = getToolbar();
        setContentView(binding.getRoot());
        context = this;
        ControllerActivity.getAppManager().addActivity(this);

        initView();
        initData();
    }

    //初始化View
    protected abstract void initView();
    //初始化数据
    protected abstract void initData();
    protected abstract T getViewBinding();
    protected abstract OAToolbar getToolbar();


    public void startActivity(Class<? extends Activity> cls) {
        Intent intent = new Intent(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null) {
            nfcAdapter.disableForegroundDispatch(this);
        }
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ControllerActivity.getAppManager().finishActivity(this);
        context = null;
    }

    /**
     * 显示toast
     *
     * @param text
     */
    public void showToast(String text) {
        if (text != null && !text.trim().equals("")) {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        }
    }

    public void showToast(int id) {
        Toast.makeText(this, id, Toast.LENGTH_SHORT).show();
    }


    /**
     * 检测工作,判断设备的NFC支持情况
     *
     * @return
     */
    private Boolean ifNFCUse() {
        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;
    }

    /**
     * 初始化过程
     */
    public void initNFC() {

        //NFC适配器，所有的关于NFC的操作从该适配器进行
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (!ifNFCUse()) {
            return;
        }
        //将被调用的Intent，用于重复被Intent触发后将要执行的跳转


        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        }


        //设定要过滤的标签动作，这里只接收ACTION_NDEF_DISCOVERED类型
        ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器
        mTechLists = new String[][]{new String[]{NfcA.class.getName()},
                new String[]{NfcF.class.getName()},
                new String[]{NfcB.class.getName()},
                new String[]{NfcV.class.getName()},
                new String[]{MifareClassic.class.getName()},
                new String[]{MifareUltralight.class.getName()},
                new String[]{IsoDep.class.getName()}};// 允许扫描的标签类型

        if (isFirst) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent()
                    .getAction())) {
                ndef = new IntentFilter();
                if (readFromTag(getIntent())) {
                    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 static String bytesToHex(byte[] src){
        StringBuffer sb = new StringBuffer();
        if (src == null || src.length <= 0) {
            return null;
        }
        String sTemp;
        for (int i = 0; i < src.length; i++) {
            sTemp = Integer.toHexString(0xFF & src[i]);
            if (sTemp.length() < 2){
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /*
     * 有必要要了解onNewIntent回调函数的调用时机,请自行上网查询
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {

            String id = bytesToHex(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));

            if (id != null) {
                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 boolean readFromTag(Intent intent) {

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

            Parcelable[] rawArray = intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawArray != null) {
                NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
                NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];
                if (mNdefRecord != null) {
                    readResult = new String(mNdefRecord.getPayload(), StandardCharsets.UTF_8);
                    return true;
                }
                //return false;
            }
            return false;
        }
        return false;
    }

    //处理NFC
    public void handleNfc(String result) {
        //showToast(result);
    }
    public void initToolbar(String title, String rightText, View.OnClickListener listenerLeftClick,View.OnClickListener listenerRightClick) {
        mToolbar.setTvTitleText(title);
        mToolbar.setTvRightText(rightText);
        mToolbar.setIvLeftIcon(R.mipmap.ac_back_icon);
        mToolbar.setIvLeftOnClickListener(listenerLeftClick);
        mToolbar.setTvRightOnClickListener(listenerRightClick);
    }
}