package com.rehome.bhdxj.base;

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 android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.rehome.bhdxj.R;
import com.rehome.bhdxj.utils.ControllerActivity;
import com.zhy.autolayout.AutoLayoutActivity;
import java.nio.charset.StandardCharsets;
import androidx.annotation.LayoutRes;
import androidx.appcompat.widget.Toolbar;

/**
 * Created by Administrator on 2016/8/3.
 */
public abstract class BaseActivity extends AutoLayoutActivity {
    public Toolbar mToolbar;
    public TextView title;
    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;
    public abstract int getContentViewID();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(getContentViewID());
        context = this;
        ControllerActivity.getAppManager().addActivity(this);
        mToolbar = findViewById(R.id.toolbar);
        title = findViewById(R.id.title);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        initView();
        initData();
        initNFC();
    }
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
    }
    protected abstract void initView();
    public void initData() {
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ControllerActivity.getAppManager().finishActivity(this);
        context = null;
    }
    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();
    }
    public void setTitle(String title) {
        this.title.setText(title);
    }
    public void setBack() {
        mToolbar.setNavigationIcon(R.mipmap.back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    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;
        }
    }
    private String ByteArrayToHexString(byte[] inarray) { //converts byte arrays to string
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        String out = "";
        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null) {
            nfcAdapter.disableForegroundDispatch(this);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null && pendingIntent != null && mFilters != null && mTechLists != null) {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
                    mTechLists);
        }
    }
    @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 = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
            if (id != null) {
                handleNfc(id);
            }
        }
    }
    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;
    }
    public void handleNfc(String result) {
    }
}
