package com.hh.arome.ui;

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

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.R;
import com.hh.arome.bean.LogcatAddRequestBean;
import com.hh.arome.bean.SimpleResultBean;
import com.hh.arome.bean.ampe.AmpeAppletResultBean;
import com.hh.arome.helper.MyNfcManager;
import com.hh.arome.helper.ReadCardManager;
import com.hh.arome.mvp.contract.LogcatAddContract;
import com.hh.arome.mvp.presenter.LogcatAddPresenter;
import com.hh.arome.ui.base.BaseHHActivity;
import com.hh.arome.utlis.device.DeviceUtils;
import com.hh.arome.utlis.log.AppLogUtils;
import com.hh.arome.utlis.log.LogType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.hh.arome.common.Constants.Ampe.ACTION_IDCard;
import static com.hh.arome.common.Constants.Ampe.AMPE_EVENT;
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.NET_LOGCAT;
import static com.hh.arome.common.Constants.LogcatValue.NODE;
import static com.hh.arome.common.Constants.LogcatValue.WARP;
import static com.hh.arome.common.Constants.Value.TOKEN;

public class IDCardScanActivity extends BaseHHActivity implements LogcatAddContract.View {

    LogcatAddPresenter mLogcatAddPresenter;

    private View mBoottomView;

    @Override
    public int setLayout() {
        super.setHideTopBar();
//        setTheme(R.style.TransparentTheme);

        return R.layout.activity_idcard_scan;
    }

//    @Override
//    protected void initView() {
//        super.setHideTopBar();
//    }

    @Override
    public void setStatusBar() {
//        super.setStatusBar();

    }

    TextView tv_time;
    LinearLayout item_close;


    @Override
    protected void initView() {
        super.setHideTopBar();

        //
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(params);


        tv_time = findViewById(R.id.tv_time);
        item_close = findViewById(R.id.item_close);


        // 时间
        resh.mainHandler.postDelayed(resh.runnable, 1000);// 每兩秒執行一次runnable.


    }

    @Override
    protected void initData() {

        mLogcatAddPresenter = new LogcatAddPresenter(this);

        EventBus.getDefault().register(this);
        ReadCardManager.eid.setGetDataFromSdk(true);

        // 日志开始保存----------------begin
        // 日志行数——对应web端"日志标签"
        String logLine = (new Throwable().getStackTrace())[0].toString();
        // 日志节点
        String logNode = LOG_NODE_IDCARD + "在线---开始调用识别---";
        // 日志内容
        StringBuilder logContentSb = new StringBuilder();
        logContentSb.append(logNode).append(WARP);

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

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


    }

    @Override
    protected void initListener() {
        item_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


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

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "在线身份证---初始化成功---";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP);

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

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


            if (ReadCardManager.eid == null) {

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine11 = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode11 = "在线身份证---初始化失败---eid对象为空，请初始化sdk成功后再使用sdk功能---";
                // 日志内容
                StringBuilder logContentSb11 = new StringBuilder();
                logContentSb11.append(logNode).append(WARP);

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

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

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


                return;
            }
            /**
             * 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();

                ToastUtils.showLongToast("在线身份证---初始化失败---请先打开NFC开关");

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

                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "在线身份证---初始化失败---请先打开NFC开关---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP);

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

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


            } else {
                // 日志开始----------------begin
                // 日志行数——对应web端"日志标签"
                String logLine = (new Throwable().getStackTrace())[0].toString();
                // 日志节点
                String logNode = "在线身份证---初始化失败---设备不支持NFC---";
                // 日志内容
                StringBuilder logContentSb = new StringBuilder();
                logContentSb.append(logNode).append(WARP);

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

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

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

            }
        }
    };


    private NfcAdapter mNfcAdapter;

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

    private OnGetResultListener mResultListener = new OnGetResultListener() {

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

            // 日志开始----------------begin
            // 日志行数——对应web端"日志标签"
            String logLine = (new Throwable().getStackTrace())[0].toString();
            // 日志节点
            String logNode = "在线身份证---读卡成功---";
            // 日志内容
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append(logNode).append(WARP)
                    .append("result = ").append(result);

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

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

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


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

                AmpeAppletResultBean bean = new AmpeAppletResultBean();
                bean.setAction(ACTION_IDCard);
                bean.setEvent(AMPE_EVENT);
                bean.setTaskId("");
                bean.setSuccess(true);
                bean.setMessage("成功");

                AmpeAppletResultBean.Data dataBean = new AmpeAppletResultBean.Data();
                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());

                bean.setData(dataBean);


                EventBus.getDefault().post(bean);

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        // 跳转到
                        finish();
                    }
                }, 1000);


            }


            // 转换图片
//            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 = "在线身份证---读卡失败---";
            // 日志内容
            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);

        }

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

    @Override
    protected void onDestroy() {
        ReadCardManager.eid.release();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (mBoottomView != null) {
            AppLogUtils.e("当前事件是" + this.getClass().getName() + "传递");
            mBoottomView.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mNfcAdapter = MyNfcManager.enableReaderMode(this, mNfcListener);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveIDCardResult(AmpeAppletResultBean bean) {

    }


    @Override
    public void onBackPressed() {
        mActivity.finish();
//        overridePendingTransition(R.anim.bottom_no, R.anim.bottom_out);
    }

    private void requestLogcatAdd(LogcatAddRequestBean logBean) {

        if (mLogcatAddPresenter == null) {
            mLogcatAddPresenter = new LogcatAddPresenter(this);
        }

        logBean.setToken(TOKEN);
        logBean.setSn(DeviceUtils.getDeviceSN());

        mLogcatAddPresenter.requestLogcatAdd(logBean);
    }

    @Override
    public void showLogcatAddResult(SimpleResultBean resultBean) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dismissLoading() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void showError(String url, String msg) {

    }


    RefreshPage resh = new RefreshPage();
    int time = 20;

    class RefreshPage {
        Handler mainHandler = new Handler();
        // 倒计时任务
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                if (time == 0) {
                    finish();
                    return;
                }

                // 设置最新时间
                tv_time.setText(time-- + "s");
                // 接着发送刷新任务
                mainHandler.postDelayed(this, 1000);
            }
        };
    }


}
