package com.hh.arome.common.scan.idcard.manymodels;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.provider.Settings;

import androidx.fragment.app.FragmentActivity;

import com.common.lib_base.utils.ui.ToastUtils;
import com.eidlink.idocr.sdk.bean.EidlinkResult;
import com.eidlink.idocr.sdk.bean.IdentityBean;
import com.eidlink.idocr.sdk.listener.NfcListener;
import com.eidlink.idocr.sdk.listener.OnGetResultListener;
import com.hh.arome.bean.LogcatAddRequestBean;
import com.hh.arome.common.scan.idcard.abstractidcard.IIDCardScan;
import com.hh.arome.common.scan.idcard.bean.IDCardInfoBean;
import com.hh.arome.common.scan.idcard.callback.IDCardInitResultCallback;
import com.hh.arome.common.scan.idcard.callback.IDCardScanResultCallback;
import com.hh.arome.common.scan.idcard.manymodels.k8.MyNfcManager;
import com.hh.arome.common.scan.idcard.manymodels.k8.ReadCardManager;
import com.hh.arome.utlis.log.AppLogUtils;
import com.hh.arome.utlis.log.LogType;

import static com.alipay.arome.aromecli.AromeInit.getApplicationContext;
import static com.hh.arome.common.Constants.LogcatValue.LINE;
import static com.hh.arome.common.Constants.LogcatValue.LOG_NODE_IDCARD;
import static com.hh.arome.common.Constants.LogcatValue.NET_ERROR;
import static com.hh.arome.common.Constants.LogcatValue.NODE;
import static com.hh.arome.common.Constants.LogcatValue.WARP;

/**
 * 服务未开通，请联系客服:
 *      去航汇-在线身份证对接群，找王义琳，提供TESTID20210809203718，开通测试权限和明文
 */
public class NfcIDCardScan implements IIDCardScan {


    //用volatile关键字确保 instance 在多线程下的可见性
    private static volatile NfcIDCardScan instance = null;

    //将构造方法私有化，禁止外部通过构造方法创建实例
    private NfcIDCardScan() {
    }

    //提供一个公共的访问方法，用于获取该类的唯一实例
    public static NfcIDCardScan getInstance(Context context) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (NfcIDCardScan.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new NfcIDCardScan(context);
                }
            }
        }
        return instance;
    }


    Context mContext;
    Activity mActivity;

    public NfcIDCardScan(Context context) {
        if (context instanceof FragmentActivity) {
            this.mActivity = (Activity) context;
        }
        this.mContext = context;

    }


    private void k8Init() {

        ReadCardManager.initEid(getApplicationContext());
        ReadCardManager.eid.setGetDataFromSdk(true);

        if (ReadCardManager.eid == null) {
            idCardInitResultCallback.onIDCardInitError("-1", "在线身份证---初始化失败---eid对象为空，请初始化sdk成功后再使用sdk功能---");
        }else{
            // 初始化成功
            idCardInitResultCallback.onIDCardInitSuccess();
        }



    }

//    private NfcListener mNfcListener;

    NfcListener mNfcListener = new NfcListener() {
        @Override
        public void onNfcEvent(Tag tag) {

            AppLogUtils.e("mNfcListener");
            AppLogUtils.e("mNfcListener--"+ReadCardManager.eid);

            if (ReadCardManager.eid == null) {

                idCardInitResultCallback.onIDCardInitError("-1", "Nfc在线身份证---初始化失败---eid对象为空，请初始化sdk成功后再使用sdk功能---");

                return;
            }else{
                // 初始化成功
                idCardInitResultCallback.onIDCardInitSuccess();
            }
            /**
             * ReadCardManager.eid.readIDCard(tag, mResultListener);
             * 通用模式，同时支持二代证读取和eID电子证照读取
             */

            ReadCardManager.eid.readIDCard(tag, mResultListener);

            /**
             * ReadCardManager.eid.readIDCard(IDOCRCardType.IDCARD,tag, mResultListener);
             * 设置只支持二代证读取
             */
//        ReadCardManager.eid.readIDCard(IDOCRCardType.IDCARD,tag, mResultListener);

            /**
             * ReadCardManager.eid.readIDCard(IDOCRCardType.ECCARD,tag, mResultListener);
             * 设置只支持eID电子证照读取
             */
//        ReadCardManager.eid.readIDCard(IDOCRCardType.ECCARD,tag, mResultListener);




        }

        @Override
        public void onNfcError(boolean has) {
            AppLogUtils.e("NFC——onNfcError");
            if (has) {
//                showAlertDialog();

                String err = "Nfc在线身份证---初始化失败---请先打开NFC开关";

                ToastUtils.showLongToast(err);

                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                mActivity.startActivity(intent);

                idCardInitResultCallback.onIDCardInitError("-1", err);

                // 打印编译器输出日志
                AppLogUtils.e(err);


            } else {

                String err = "Nfc在线身份证---初始化失败---设备不支持NFC";

                ToastUtils.showLongToast(err);

                idCardInitResultCallback.onIDCardInitError("-1", err);


                // 打印编译器输出日志
                AppLogUtils.e(err);

            }
        }
    };


    // 扫结果回调
    IDCardScanResultCallback idCardScanResultCallback;

    // 初始化结果回调
    IDCardInitResultCallback idCardInitResultCallback;

    @Override
    public void initIDCard(IDCardInitResultCallback idCardInitResultCallback) {
        this.idCardInitResultCallback = idCardInitResultCallback;

        k8Init();
    }

    @Override
    public void startIDCardScan(IDCardScanResultCallback idCardScanResultCallback) {
        this.idCardScanResultCallback = idCardScanResultCallback;
    }

    @Override
    public void resumeIDCardScan() {
        mNfcAdapter = MyNfcManager.enableReaderMode(mActivity, mNfcListener);
    }

    @Override
    public void pauseIDCardScan() {
//        MyNfcManager.disableReaderMode(mActivity, mNfcAdapter);
    }

    @Override
    public void stopIDCardScan() {
//        MyNfcManager.disableReaderMode(mActivity, mNfcAdapter);
    }

    @Override
    public void destoryIDCardScan() {
        ReadCardManager.eid.release();
    }

    private NfcAdapter mNfcAdapter;


    private OnGetResultListener mResultListener = new OnGetResultListener() {

        @Override
        public void onSuccess(EidlinkResult result) {
//            endtime = System.currentTimeMillis() - starttime;
//            tv_msg.setText("读卡成功  " + result.toString() + "\n耗时: " + endtime + "ms");


            // 打印编译器输出日志
            AppLogUtils.e("Nfc在线身份证---读卡成功---");


            if (result != null && result.getIdentity() != null) {
                IdentityBean identityBean = result.getIdentity();
                String name = identityBean.getName();
                AppLogUtils.e("读卡成功--name--" + name);
                AppLogUtils.e("读卡成功--Idnum--" + identityBean.getIdnum());
                AppLogUtils.e("读卡成功--identityBean--" + identityBean.toString());

//                ToastUtils.showLongToast("读卡成功:" + name + "   " + identityBean.getIdnum());

                IDCardInfoBean idCardInfoBean = new IDCardInfoBean();
                idCardInfoBean.setIdcardName(identityBean.getName());
                idCardInfoBean.setIdcardNumber(identityBean.getIdnum());
                idCardInfoBean.setSex(identityBean.getSex());
                idCardInfoBean.setAddress(identityBean.getAddress());
                idCardInfoBean.setBirth(identityBean.getBirthDate());
                idCardInfoBean.setNation(identityBean.getNation());

                if(idCardScanResultCallback!=null){
                    idCardScanResultCallback.onIDCardScanSuccess(idCardInfoBean);
                }


            }


            // 转换图片
//            try {
//                if (result.getIdentity() != null && !TextUtils.isEmpty(result.getIdentity().getPicture())) {
//                    byte[] decode = Base64.decode(result.getIdentity().getPicture(), Base64.DEFAULT);
//                    Bitmap bt = BitmapFactory.decodeByteArray(decode, 0, decode.length);
//                    if (bt != null) {
//                        iv_image.setVisibility(View.VISIBLE);
//                        iv_image.setImageBitmap(bt);
//                    }
//                }
//            } catch (Exception e) {
//
//            }
        }

        @Override
        public void onFailed(int code, String msg, String biz_id) {
            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "Nfc在线身份证---读卡失败---";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("code = ").append(code).append(WARP)
                    .append("msg = ").append(msg).append(WARP)
                    .append("biz_id = ").append(biz_id);

            // 开始保存本地日志
            AppLogUtils.saveLog(LogType.Error, new StringBuilder()
                    .append(LINE)
                    .append(logLine).append(WARP)
                    .append(NODE)
                    .append(logContentSb)
                    .toString()
            );

            // 开始网络在线日志
            LogcatAddRequestBean logBean = new LogcatAddRequestBean();
            logBean.setLogType(NET_ERROR);
            // 对应web端"日志标签"
            logBean.setLogTag(logLine + WARP + LOG_NODE_IDCARD);
            logBean.setLogContent(logContentSb.toString());
//            requestLogcatAdd(logBean);
            // 日志开始----------------end

            // 打印编译器输出日志
            AppLogUtils.e(logContentSb);

            if(idCardScanResultCallback!=null){
                idCardScanResultCallback.onIDCardError(code + "", logContentSb.toString());
            }

        }

        @Override
        public void onStart() {
            super.onStart();
            AppLogUtils.e("开始读卡");
        }
    };




}
