package com.hh.lib_er301_readcard;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;

import com.eidlink.serial_idocr.bean.EidlinkInitParams;
import com.eidlink.serial_idocr.bean.EidlinkResult;
import com.eidlink.serial_idocr.bean.IdInfoBean;
import com.eidlink.serial_idocr.listener.InitCallback;
import com.eidlink.serial_idocr.listener.OnGetResultListener;
import com.eidlink.serial_idocr.sdk.EidLinkSE;
import com.eidlink.serial_idocr.sdk.EidLinkSEFactory;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.bean.InitStatusEnum;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_idcard_base.BaseIDCardScan;
import com.hh.lib_idcard_base.IDCardConfig;
import com.hh.lib_idcard_base.bean.IDCardBean;
import com.hh.lib_idcard_base.bean.IDCardError;
import com.hh.lib_idcard_base.listener.IDCardInfoLogListener;
import com.hh.lib_idcard_base.listener.ReadIDCardListener;

import java.io.ByteArrayOutputStream;

/**
 *
 * @author xwh
 * time 2024/9/5
 * Description: ER301身份证阅读器
 **/
public class Er301IDCardScan extends BaseIDCardScan {

    private static volatile Er301IDCardScan instance = null;

    private volatile   EidLinkSE eid;

    public volatile IDCardInfoLogListener onILogListener; //初始化
    private volatile ReadIDCardListener  pollReadIDCardListener; //循环读取回调监听
    private volatile ReadIDCardListener onceReadIDCardInfoListener;//单次读取;

    private Handler mHandler;
    private long readIDCardTotalTime = 15 * 1000;
    private volatile CountDownTimer readIDCardCountDownTimer; //单次读卡超时倒计时

    private static final int MESSAGE_RETRY_READER = 0x90; //重连

    private InitStatusEnum statusEnum = InitStatusEnum.DEFAULT;//设备是否初始化

    public Er301IDCardScan(IDCardConfig config) {
        super(config);
    }

    @Override
    public void initIDCard(IDCardInfoLogListener listener) {
        onILogListener=listener;
        initEid(1, 1);
        initUsbDevice();
    }
    public  void initEid(int modelType, int findFlag) {

        /**
         * @param declevel    是否读照片 0 读照片 1读文本
         * @param model       模式  0 串口 1usb
         * @param find_flag   寻卡类型 0 一次 1 循环
         * @param read_model  读卡模式 0 触发式读卡（贴一下读一下），1 重复读卡（测试环境中使用）
         * @param pic_type   0 原始数据，1 明文数据 (读头掉电重启生效)
         * @param usb_receive usb的收发模式，0 64字节循环接收，1 单次接收
         * @brief 初始化参数
         */
        if (eid != null) {
            eid.release();
            eid = null;
        }
        EidlinkInitParams eidlinkInitParams = new EidlinkInitParams(0, modelType, findFlag, 1, 1, 1);
        eid = EidLinkSEFactory.getEidLinkSE(eidlinkInitParams);
        try {
            eid.setIP("es.eidlink.com");
            eid.setPort(9699);
        } catch (Exception e) {
            AppLogUtils.e("e:"+e.toString());
        }

    }



    /**
     * 初始化USB设备
     */
    private void initUsbDevice() {
        if(eid == null){
            if (onILogListener != null) {
                onILogListener.initFailed(new IDCardError(-1, "initUsbDevice  eid == null"));
            }
            return;
        }
        eid.initlUSbDevice(BaseApplication.getContext(), 8898, 12289, new InitCallback() {
            @Override
            public void onSuccess() {
                statusEnum=InitStatusEnum.SUCCESS;
                if(onILogListener!=null){
                    onILogListener.initSuccess();
                }
                readCard();
            }

            @Override
            public void onFailed() {
                if (statusEnum != InitStatusEnum.FAIL) { //一直初始化失败，只展示第一次
                    statusEnum = InitStatusEnum.FAIL;
                    if (onILogListener != null) {
                        onILogListener.initFailed(new IDCardError(-1, "初始化USB失败"));
                    }
                }
                getmHandler().removeMessages(MESSAGE_RETRY_READER);
                getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER,5000);
            }
        });
    }


    @Override
    public void startPollRead(ReadIDCardListener listener) {
        pollReadIDCardListener=listener;
    }

    @Override
    public void stopPollRead() {
        pollReadIDCardListener=null;
    }

    @Override
    public void onceReadIDCardInfo(ReadIDCardListener listener) {
        startCountDownTimer();
        onceReadIDCardInfoListener=listener;

    }

    @Override
    public void stopOnceReadIDCardInfo() {
        stopCountDownTimer();
        onceReadIDCardInfoListener=null;
    }

    @Override
    public void getIDCardUid(ReadIDCardListener listener) {

    }

    private void readCard() {
        if(eid == null){
            if (onILogListener != null) {
                onILogListener.initFailed(new IDCardError(-1, "readCard  eid == null"));
            }
            return;
        }
        eid.readCard(new OnGetResultListener() {
            @Override
            public void onSuccess(EidlinkResult result) {
                IdInfoBean idInfoBean = result.getIdInfoBean();
                if(idInfoBean==null){
                    return;
                }
                handleIDCardData(idInfoBean);
            }

            @Override
            public void onFailed(int code, String msg) {
                AppLogUtils.e("\n读卡失败---code:"+code+"  msg:"+msg);

                if(code == 401){
                    msg = "该域名无法解析身份证，请检查网络错误";
                }else if(code == 405){
                    msg = "USB初始化失败";
                    getmHandler().removeMessages(MESSAGE_RETRY_READER);
                    getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER,5000);
                    return;
                }

                if(TextUtils.isEmpty(msg)){
                    msg = "读卡失败,请重试";
                }
                if (pollReadIDCardListener != null) {
                    pollReadIDCardListener.onError(new IDCardError(code,msg));
                }
                // 开始读取
                readCard();

            }

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

            @Override
            public void findCard() {
                super.findCard();
            }

        });


    }



    private void handleIDCardData(final IdInfoBean idcard) {
        IDCardBean idCardInfoBean = new IDCardBean();
        idCardInfoBean.setName(idcard.getName());
        idCardInfoBean.setIdNum(idcard.getIdnum());
        idCardInfoBean.setSex(idcard.getSex());
        idCardInfoBean.setAddress(idcard.getAddress());
        idCardInfoBean.setBirthDate(idcard.getBirthDate());
        idCardInfoBean.setNation(idcard.getNation());
        idCardInfoBean.setSigningOrganization(idcard.getSigningOrganization());
        idCardInfoBean.setBeginTime(idcard.getBeginTime());
        idCardInfoBean.setEndTime(idcard.getEndTime());

        String bmpPhotos = "";
        Bitmap bmp = null;
        try {
            byte[] picData = Base64.decode(idcard.getPicture(), Base64.DEFAULT);
            // 头像图片
            bmp = BitmapFactory.decodeByteArray(picData, 0, picData.length);
            if (bmp == null) {
                AppLogUtils.i("新中新身份证照片解码null ");
            } else {
                bmpPhotos = bitmapToString(bmp);
//                AppLogUtils.i("新中新身份证照片解码有值bmpPhotos--" +bmpPhotos);
                AppLogUtils.i("新中新身份证照片解码有值bmpPhotos--");
                idCardInfoBean.setPhotoBase64(bmpPhotos);
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppLogUtils.i("新中新身份证照片解码异常 " + e);
        } finally {
            if (bmp != null && !bmp.isRecycled()) {
                bmp.recycle();
                bmp = null;
            }
        }
        if (onceReadIDCardInfoListener != null) {
            onceReadIDCardInfoListener.onSuccess(idCardInfoBean);
            stopCountDownTimer();
            onceReadIDCardInfoListener = null;
        }

        if (pollReadIDCardListener != null) {
            pollReadIDCardListener.onSuccess(idCardInfoBean);
        }


        readCard();


    }


    //将Bitmap转换成字符串
    public static String bitmapToString(Bitmap bitmap) {
        try {
            String string = null;
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
            byte[] bytes = bStream.toByteArray();
            string = Base64.encodeToString(bytes, Base64.DEFAULT);
            return string;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     *
     * @author xwh
     * Time 2024/9/3
     * Description: 启动倒计时：单次刷身份证
     *
     **/
    private void startCountDownTimer(){
        stopCountDownTimer();
        readIDCardCountDownTimer = new CountDownTimer(readIDCardTotalTime, 1000) {
            public void onTick(long millisUntilFinished) {
                // 每次间隔，这里更新UI，显示剩余时间
                AppLogUtils.e("身份证，倒计时--" + millisUntilFinished / 1000);
            }

            public void onFinish() {
                // 倒计时结束时的操作
                if (onceReadIDCardInfoListener!=null) {
                    // 未结束
                    onceReadIDCardInfoListener.onError(new IDCardError(-2,"超时"));
                    onceReadIDCardInfoListener=null;
                }
            }
        };
        // 开始倒计时
        readIDCardCountDownTimer.start();
    }

    /**
     *
     * @author xwh
     * Time 2024/9/3
     * Description: 停止倒计时
     *
     **/
    private void stopCountDownTimer(){
        if (readIDCardCountDownTimer != null) {
            readIDCardCountDownTimer.cancel();
            readIDCardCountDownTimer=null;
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/9/3
     * Description: 关闭身份证阅读器
     *
     **/
    public void closeRead() {
        stopCountDownTimer();
        stopOnceReadIDCardInfo();
    }

    @Override
    public void onRelease() {

        if( eid!=null){
            eid.release();
            eid = null;
        }
        closeRead();
        stopPollRead();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        statusEnum = InitStatusEnum.DEFAULT;
    }



    public Handler getmHandler() {
        if (mHandler == null) {
            synchronized (Er301IDCardScan.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case MESSAGE_RETRY_READER:
                                    initUsbDevice();
                                    break;
                                default:
                                    break;
                            }
                            super.handleMessage(msg);
                        }
                    };
                }
            }
        }
        return mHandler;
    }
    //提供一个公共的访问方法，用于获取该类的唯一实例
    public static Er301IDCardScan getInstance(IDCardConfig config) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (Er301IDCardScan.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new Er301IDCardScan(config);
                }
            }
        }
        return instance;
    }
}
