package com.hh.nfc_readcard;

import static com.hh.lib_base.Constants.LogcatValue.WARP;

import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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.lib_base.Constants;
import com.hh.lib_base.activity.BaseActivity;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.ImageLoaderUtils;
import com.hh.lib_base.utils.ToastUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_idcard_base.bean.IDCardBean;
import com.hh.lib_idcard_base.event.NFCIDcardEvent;
import com.hh.lib_nfc_readcard.R;

import org.greenrobot.eventbus.EventBus;

public class IDCardScanNfcActivity extends BaseActivity {

    private TextView tvTime;
    private LinearLayout itemClose;
    private ImageView ivImage;

    private Handler mHandler;
    private Runnable runnableTime;
    int time = 20;

    private NfcAdapter mNfcAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_idcard_scan_nfc;
    }

    @Override
    protected void initView() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);
        tvTime =findViewById(R.id.tv_time);
        itemClose =findViewById(R.id.item_close);
        ivImage =findViewById(R.id.iv_image);
    }

    @Override
    protected void initData() {
        ImageLoaderUtils.Companion.loadRes(this,R.mipmap.ic_scan_idcard,ivImage);
        getmHandler().postDelayed(getRunnableTime(),1000);


        ReadCardManagerNfc.eid.setGetDataFromSdk(true);
        ReadCardManagerNfc.eid.setCustomSnValue(DeviceUtils.getDeviceSN());
        ReadCardManagerNfc.eid.setReqidType(0);
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                ,logLine,"在线---开始调用识别---");
    }

    @Override
    protected void initEvent() {
        itemClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter = MyNfcManager.enableReaderMode(this, mNfcListener);

    }

    @Override
    protected void onPause() {
        super.onPause();
        MyNfcManager.disableReaderMode(this, mNfcAdapter);
    }


    private NfcListener mNfcListener = new NfcListener() {
        @Override
        public void onNfcEvent(Tag tag) {
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                    ,logLine,"在线身份证---初始化成功---");
            if (ReadCardManagerNfc.eid == null) {
                String logLine2 = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                        ,logLine2,"在线身份证---初始化失败---eid对象为空，请初始化sdk成功后再使用sdk功能---");
                return;
            }
            /**
             * ReadCardManager.eid.readIDCard(tag, mResultListener);
             * 通用模式，同时支持二代证读取和eID电子证照读取
             */

            ReadCardManagerNfc.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();
                ToastUtils.showLongToast("在线身份证---初始化失败---请先打开NFC开关");
                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(intent);
                String logLine = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                        ,logLine,"在线身份证---初始化失败---请先打开NFC开关---");
            } else {
                String logLine = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                        ,logLine,"在线身份证---初始化失败---设备不支持NFC---");

            }
        }
    };

    private OnGetResultListener mResultListener = new OnGetResultListener() {

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

            String logLine = (new Throwable().getStackTrace())[0].toString();
            String logNode = "在线身份证---读卡成功---";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("result = ").append(result);
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                    ,logLine,logContentSb.toString());;

            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());


                IDCardBean dataBean=new IDCardBean();
                dataBean.setIdNum(identityBean.getIdnum());
                dataBean.setName(identityBean.getName());

                dataBean.setSigningOrganization(identityBean.getSigningOrganization());
                dataBean.setAddress(identityBean.getAddress());
                dataBean.setNation(identityBean.getNation());
                dataBean.setSex(identityBean.getSex());
                dataBean.setBeginTime(identityBean.getBeginTime());
                dataBean.setEndTime(identityBean.getEndTime());
                dataBean.setBirthDate(identityBean.getBirthDate());
                dataBean.setPhotoBase64(identityBean.getPicture());
                NFCIDcardEvent event=new NFCIDcardEvent();
                event.setSuccess(true);
                event.setIdCardBean(dataBean);
                EventBus.getDefault().post(event);
               getmHandler().postDelayed(new Runnable() {
                    public void run() {
                        // 跳转到
                        finish();
                    }
                }, 1000);


            }

        }

        @Override
        public void onFailed(int code, String msg, String biz_id) {

            String logLine = (new Throwable().getStackTrace())[0].toString();
            String logNode = "在线身份证---读卡失败---";
            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);
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,Constants.Ampe.ACTION_IDCARD
                    ,logLine,logContentSb.toString());

            NFCIDcardEvent event=new NFCIDcardEvent();
            event.setSuccess(false);
            event.setErrMsg(logContentSb.toString());
            EventBus.getDefault().post(event);
        }

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


    public Handler getmHandler() {
        if (mHandler == null) {
            synchronized (IDCardScanNfcActivity.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        return mHandler;
    }
    public Runnable getRunnableTime() {
        if (runnableTime == null) {
            synchronized (IDCardScanNfcActivity.class) {
                if (runnableTime == null) {
                    runnableTime = () -> {
                        if (time == 0) {
                            finish();
                            return;
                        }
                        if(tvTime!=null) {
                            // 设置最新时间
                            tvTime.setText(time-- + "s");
                        }
                        // 接着发送刷新任务
                        getmHandler().postDelayed(runnableTime, 1000);
                    };
                }
            }
        }
        return runnableTime;
    }
    @Override
    public void onBackPressed() {
        finish();
//        overridePendingTransition(R.anim.bottom_no, R.anim.bottom_out);
    }

    @Override
    protected void onDestroy() {
        if(ReadCardManagerNfc.eid!=null){
            ReadCardManagerNfc.eid.release();
        }
        super.onDestroy();
    }
}