package com.bjzc.zjyxdxj.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.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.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


import com.bjzc.zjyxdxj.R;
import com.bjzc.zjyxdxj.utils.AppManager;
import com.bjzc.zjyxdxj.utils.OAToolbar;
import com.zhy.autolayout.AutoLayoutActivity;

import java.nio.charset.StandardCharsets;
import androidx.annotation.Nullable;


/**
 * Created by ruihong on 2017/12/23.
 */

public abstract class BaseActivity3 extends AutoLayoutActivity {

    protected OAToolbar toolbar;
    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(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        toolbar = findViewById(R.id.toolbar);
        AppManager.getAppManager().addActivity(this);
        context = this;
        initView();
        initData();
    }
    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 startActivity(Class<? extends Activity> cls) {
        startActivity(new Intent(this, cls));
    }
    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), PendingIntent.FLAG_UPDATE_CURRENT);
        }
        //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();

        // 前台分发系统,这里的作用在于第二次检测NFC标签时该应用有最高的捕获优先权.
        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);
            }

//            if (readFromTag(intent)) {
//                Toast.makeText(this, readResult, Toast.LENGTH_SHORT).show();
//                handleNfc(readResult);
//            } else {
//                Toast.makeText(this, "ID:" + id + "  标签数据为空", Toast.LENGTH_SHORT).show();
//            }
        }
    }
    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);
        //Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }
    public abstract int getLayoutId();
    public abstract void initView();
    public abstract void initData();
    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }
    public void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
    public void initToolbar(String title) {
        toolbar.setTvTitleText(title);
    }

    public void initToolbar(String title, String rightText, View.OnClickListener listener) {
        toolbar.setTvTitleText(title);
        toolbar.setTvRightText(rightText);
        toolbar.setTvRightOnClickListener(listener);
        setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    public void initToolbar(String title, String rightText, View.OnClickListener listenerLeftBtnClick, View.OnClickListener listener) {
        toolbar.setTvTitleText(title);
        toolbar.setTvRightText(rightText);
        toolbar.setTvRightOnClickListener(listener);
        setLeftOnClickListener(listenerLeftBtnClick);
    }
    public void initToolbar(String title, int rightTextId, View.OnClickListener listener) {
        toolbar.setTvTitleText(title);
        toolbar.setTvRightText(rightTextId);
        toolbar.setTvRightOnClickListener(listener);
        setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    public void setLeftOnClickListener(View.OnClickListener listener) {
        toolbar.setIvLeftOnClickListener(listener);
        toolbar.setIvLeftIcon(R.mipmap.ac_back_icon);
    }
    public String getText(EditText editText) {
        return editText.getText().toString();
    }

    public void showLog(String logText) {
        if (isApkInDebug(context)) {
            if(TextUtils.isEmpty(logText)){
                Log.i("app", "logText is null");
            }else{
                Log.i("app", logText);
            }
        }
    }

    /**
     * 判断当前应用是否是debug状态
     */

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

}
