package com.hh.lib_idcard;

import android.content.Context;
import android.text.TextUtils;

import com.alipay.arome.aromecli.AromeServiceInvoker;
import com.google.gson.JsonObject;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_ampe.bean.BaseAmpeRequestBean;
import com.hh.lib_ampe.utils.AromeInvoker;
import com.hh.lib_ampe.utils.MyTypeToken;
import com.hh.lib_base.ConfigData;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.device.DeviceConfigResultBean;
import com.hh.lib_base.bean.event.ConfigStatusTextEvent;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_base.utils.StringUtils;
import com.hh.lib_idcard.bean.AmpeRequestIDCardBean;
import com.hh.lib_idcard.bean.AmpeResultIDCardBean;
import com.hh.lib_idcard_base.BaseIDCardScan;
import com.hh.lib_idcard_base.bean.IDCardBean;
import com.hh.lib_idcard_base.bean.IDCardError;
import com.hh.lib_idcard_base.listener.ReadIDCardListener;
import com.hh.lib_idcard_base.listener.SimpleIDCardInfoLogListener;
import com.hh.lib_idcard_base.event.NFCIDcardEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;

/**
 *
 * @author xwh
 * time 2024/9/3
 * Description: 身份证调用器
 **/
public class IDCardInvoler {

    private volatile static IDCardInvoler idCardInvoler;
    private BaseIDCardScan idCardScan;
    HashMap<String, BaseAmpeRequestBean> ampeActionMap = new HashMap<>();
    private String lastErrMsg="";// 上一次轮询错误日志信息

    /**
     *
     * @author xwh
     * Time 2024/9/10
     * Description: 身份证功能交互入口
     *
    **/
    public void onCalled(Context context, BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        if (dataBean == null) {
            return;
        }
        if(isUnEnabledHardware(dataBean,bridgeCallback)){
            return;
        }
        switch (dataBean.getAction()) {
            case Constants.Ampe.ACTION_IDCARD:
                getAmpeActionMap().put(dataBean.getAction(),dataBean);
                if(idCardScan==null){
                    initCard(ConfigData.getDeviceConfigResultBean());
                }
                if(idCardScan!=null){
                    idCardScan.onceReadIDCardInfo(new ReadIDCardListener() {
                        @Override
                        public void onSuccess(IDCardBean idCard) {
                            receiveIDCardResult(dataBean,idCard);
                        }

                        @Override
                        public void onError(IDCardError idCardError) {
                            String msg="";
                            if(idCardError!=null){
                                msg=idCardError.getCode()+"   "+idCardError.getMessage();
                            }
                            receiveIDCardResultFailed(dataBean, msg );
                        }
                    });
                }

                break;
            case Constants.Ampe.ACTION_IDCARD_CLOSE:
                closeIDCardReading(dataBean);
                break;
        }
    }


    /**
     *
     * @author xwh
     * Time 2024/9/26
     * Description: 是否未开启该模块
     * @return true:是该模块的消息并且未启用该模块
     **/
    private boolean isUnEnabledHardware(BaseAmpeRequestBean dataBean, AromeServiceInvoker.BridgeCallback bridgeCallback) {
        DeviceConfigResultBean configResultBean = ConfigData.getDeviceConfigResultBean();
        boolean isUseIDCard = true;
        if (configResultBean != null) {
            isUseIDCard =configResultBean.isUseIdcard();
        }
        String action = dataBean.getAction();
        if (!isUseIDCard &&
                action != null &&
                (Constants.Ampe.ACTION_IDCARD.equals(action) ||
                        Constants.Ampe.ACTION_IDCARD_CLOSE.equals(action) )) {
            AromeInvoker.getAromeInvoker().hardwareNotEnabled(dataBean, bridgeCallback);
            return true;
        }

        return false;
    }
    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: NFC在线身份证返回
     *
    **/
    public void NFCCardInfo(NFCIDcardEvent event) {
        if (event == null) {
            return;
        }
        if (event.isSuccess() && event.getIdCardBean() == null) {
            return;
        }
        BaseAmpeRequestBean requestBean = ampeActionMap.get(Constants.Ampe.ACTION_IDCARD);
        if (requestBean == null) {
            return;
        }
        if (event.isSuccess()) {
            receiveIDCardResult(requestBean, event.getIdCardBean());
        }else {
            receiveIDCardResultFailed(requestBean,event.getErrMsg());
        }
    }




    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 身份证初始化
     *
    **/
    public void initCard( DeviceConfigResultBean deviceConfigBean){
        if(deviceConfigBean==null){
            return;
        }

        int idCardReaderBrand = deviceConfigBean.getIdCardReaderBrand();
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,"",logLine,"开始初始化,  "+idCardReaderBrand);
        idCardScan=IDCardScanFactory.createIDCardScan(idCardReaderBrand);
        if(idCardScan==null){
            String logLine2 = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,"",logLine2,"idCardScan=null");
            return;
        }
        idCardScan.initIDCard(new SimpleIDCardInfoLogListener() {
            @Override
            public void initSuccess() {
                String initStr="身份证---初始化成功---" + "  连接品牌：" +
                        (deviceConfigBean==null?"": idCardReaderBrand);
                EventBus.getDefault().post(new ConfigStatusTextEvent(initStr));
                String logLine2 = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,"",logLine2,initStr);

            }

            @Override
            public void initFailed(IDCardError msg) {
                String initStr="身份证---初始化失败---" + "  连接品牌：" +
                        (deviceConfigBean==null?"": idCardReaderBrand);
                EventBus.getDefault().post(new ConfigStatusTextEvent("身份证---初始化失败---" + "  连接品牌：" +
                        (deviceConfigBean==null?"": idCardReaderBrand)));
                String logLine2 = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(Constants.LogcatValue.LOG_NODE_IDCARD,"",logLine2,initStr);
            }
        });
        idCardScan.startPollRead(new ReadIDCardListener() {
            @Override
            public void onSuccess(IDCardBean idCard) {
                handleIdCardResultListener(ConfigData.getDeviceConfigResultBean(),idCard);
            }

            @Override
            public void onError(IDCardError idCardError) {
                if (idCardError == null) {
                    return;
                }
                if (TextUtils.isEmpty(lastErrMsg)) {
                    lastErrMsg = "";
                }
                if (TextUtils.isEmpty(idCardError.getMessage())) {
                    idCardError.setMessage("");
                }
                if (lastErrMsg.equals(idCardError.getMessage())) {
                    return;
                }
                lastErrMsg = idCardError.getMessage();
                String logLine = (new Throwable().getStackTrace())[0].toString();
                UploadLogUtils.sendLogs(false,Constants.LogcatValue.LOG_NODE_IDCARD, "", logLine, lastErrMsg);
            }
        });
    }

    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 身份证单次刷证返回成功结果
     *
    **/
    public void receiveIDCardResult(BaseAmpeRequestBean requestBean, IDCardBean idCard) {
        if(requestBean==null||idCard==null){
            receiveIDCardResultFailed(requestBean, (requestBean == null ? "requestBean == null" : " ")
                    + (idCard == null ? "idCard == null" : " "));
            //失败
            return;
        }
        BaseAmpeRequestBean<AmpeRequestIDCardBean> newRequestBean=MyTypeToken
                .toBaseAmpeRequestBean(requestBean,AmpeRequestIDCardBean.class);
        if(newRequestBean==null){
            receiveIDCardResultFailed(requestBean, "newRequestBean == null" );
            return;
        }
        BaseAmpeAppletResultBean<AmpeResultIDCardBean> resultBean=new BaseAmpeAppletResultBean<>();
        AmpeResultIDCardBean dataBean= new  AmpeResultIDCardBean();

        String[] paramsArray = null;
        if (newRequestBean.getParams() != null) {
            paramsArray = newRequestBean.getParams().getParamsArray();
        }

        resultBean.setAction(Constants.Ampe.ACTION_IDCARD);
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        resultBean.setSuccess(true);
        resultBean.setMessage("成功");

        String name = idCard.getName().replace(" ", "");
        String address = idCard.getAddress();

        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                String param = paramsArray[i];
                if (param.equals("base")) {
                    dataBean.setIdNum(idCard.getIdNum());
                    dataBean.setName(name);
                } else if (param.equals("photo")) {
//                    dataBean.setPhotoBase64(identityBean.getPhotoBase64());
                    if (StringUtils.isNotNull(idCard.getPhotoBase64())) {
                        String photoBase64 = idCard.getPhotoBase64().replaceAll("\n", "");
                        dataBean.setPhotoBase64(photoBase64);
                    }

                } else if (param.equals("other")) {
                    dataBean.setSigningOrganization(idCard.getSigningOrganization());
                    dataBean.setAddress(address);
                    dataBean.setNation(idCard.getNation());
                    dataBean.setSex(idCard.getSex());
                    dataBean.setBeginTime(idCard.getBeginTime());
                    dataBean.setEndTime(idCard.getEndTime());
                    dataBean.setBirthDate(idCard.getBirthDate());
                }
            }
            resultBean.setData(dataBean);

        } else {
            dataBean.setIdNum(idCard.getIdNum());
            dataBean.setName(name);
            dataBean.setSigningOrganization(idCard.getSigningOrganization());
            dataBean.setAddress(address);
            dataBean.setNation(idCard.getNation());
            dataBean.setSex(idCard.getSex());
            dataBean.setBeginTime(idCard.getBeginTime());
            dataBean.setEndTime(idCard.getEndTime());
            dataBean.setBirthDate(idCard.getBirthDate());
            dataBean.setPhotoBase64(idCard.getPhotoBase64());
            resultBean.setData(dataBean);
        }

        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();

            if (newRequestBean.getBridgeCallback() != null) {
                newRequestBean.getBridgeCallback().callback(jsonObject.toString());
            } else {
                AppLogUtils.e("bridgeCallback--null");
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            StringBuilder logContentSb = new StringBuilder();
            logContentSb.append("jsonObject = ").append(jsonObject);
            UploadLogUtils.sendLogs("身份证---回传处理结果给小程序",
                    Constants.Ampe.ACTION_IDCARD,logLine,logContentSb.toString());
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 身份证单次刷证返回失败结果
     *
     **/
    public void receiveIDCardResultFailed(BaseAmpeRequestBean requestBean, String msg){
        if(requestBean==null){
            return;
        }
        String errMsg="失败";
        if(!TextUtils.isEmpty(msg)){
            errMsg=msg;
        }
        BaseAmpeAppletResultBean resultBean=new BaseAmpeAppletResultBean<>();
        resultBean.setAction(Constants.Ampe.ACTION_IDCARD);
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        resultBean.setSuccess(false);
        resultBean.setMessage(errMsg);
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();

            if (requestBean.getBridgeCallback() != null) {
                requestBean.getBridgeCallback().callback(jsonObject.toString());
            } else {
                AppLogUtils.e("bridgeCallback--null");
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs("身份证---回传处理结果给小程序",
                    Constants.Ampe.ACTION_IDCARD,logLine,msg);
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    /**
     *
     * @author xwh
     * Time 2024/9/5
     * Description: 关闭当前单次读取身份证
     *
    **/
    private void closeIDCardReading(BaseAmpeRequestBean requestBean){
        if (requestBean == null ) {
            return;
        }
        if(idCardScan!=null) {
            idCardScan.stopOnceReadIDCardInfo();
        }
        BaseAmpeAppletResultBean resultBean=new BaseAmpeAppletResultBean<>();
        resultBean.setAction(requestBean.getAction());
        resultBean.setEvent(requestBean.getEvent());
        resultBean.setTaskId(requestBean.getTaskId());
        resultBean.setSuccess(true);
        resultBean.setMessage("成功");
        // 回传处理结果给小程序
        try {
            JsonObject jsonObject = GsonUtils.getGson().toJsonTree(resultBean).getAsJsonObject();

            if (requestBean.getBridgeCallback() != null) {
                requestBean.getBridgeCallback().callback(jsonObject.toString());
            } else {
                AppLogUtils.e("bridgeCallback--null");
            }
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs("身份证---回传处理结果给小程序",
                    Constants.Ampe.ACTION_IDCARD,logLine,"成功");
        } catch (Throwable t) {
            AppLogUtils.e("onCalled--t" + t);
        }
    }

    private void handleIdCardResultListener(DeviceConfigResultBean deviceConfigBean,IDCardBean idCardInfoBean) {
        if (deviceConfigBean == null || idCardInfoBean == null) {
            return;
        }
        JSONObject object = new JSONObject();
        try {
            // 勿动key，对外的文档key
            object.put("name", idCardInfoBean.getName());
            object.put("idNum", idCardInfoBean.getIdNum());
            object.put("address", idCardInfoBean.getAddress());
            object.put("nation", idCardInfoBean.getNation());
            object.put("sex", idCardInfoBean.getSex());
            object.put("birthDate", idCardInfoBean.getBirthDate());
            if (StringUtils.isNotNull(idCardInfoBean.getPhotoBase64())) {
                String photoBase64 = idCardInfoBean.getPhotoBase64().replaceAll("\n", "");
                object.put("photoBase64", photoBase64);
            }
//                    object.put("photoBase64", idCardInfoBean.getPhotoBase64());
            object.put("beginTime", idCardInfoBean.getBeginTime());
            object.put("endTime", idCardInfoBean.getEndTime());
            object.put("signingOrganization", idCardInfoBean.getSigningOrganization());
        } catch (Throwable t) {

        }
        if (AromeInvoker.getAromeInvoker() != null) {
            AromeInvoker.getAromeInvoker().
                    sendMessageToApplet(Constants.Ampe.EVENT_IDCard_LISTENER, object.toString());
        }
    }



    public void onRelease() {
        if (idCardScan != null) {
            idCardScan.onRelease();
            idCardScan = null;
        }
        getAmpeActionMap().clear();
        ampeActionMap = null;
        idCardInvoler = null;
    }

    public HashMap<String, BaseAmpeRequestBean> getAmpeActionMap() {
        if(ampeActionMap==null){
            synchronized (IDCardInvoler.class){
                if(ampeActionMap==null){
                    ampeActionMap=new HashMap<>();
                }
            }
        }
        return ampeActionMap;
    }

    public static IDCardInvoler getInstance() {
        if (idCardInvoler == null) {
            synchronized (IDCardInvoler.class) {
                if (idCardInvoler == null) {
                    idCardInvoler = new IDCardInvoler();

                }
            }
        }
        return idCardInvoler;
    }
}
