package com.hhlib_dx_multi_readcard;


import static com.hh.lib_dx_base_multi.bean.InitStatusEnum.*;

import android.graphics.Bitmap;
import android.os.CountDownTimer;
import android.util.Base64;
import android.util.Log;

import com.donsee.bean.IDCardInfo;
import com.donsee.devices.CardReader;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_dx_base_multi.DxCardReader;
import com.hh.lib_dx_base_multi.DxInitListener;
import com.hh.lib_dx_base_multi.bean.InitStatusEnum;
import com.hh.lib_dx_base_multi.listener.IDCardListener;
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;


/**
 * Description: $东信多合一
 *
 * @author xwh
 * time 2024/9/11
 **/
public class DxMultiIDCardScan extends BaseIDCardScan {

    private static volatile DxMultiIDCardScan instance = null;
    
    private volatile ReadIDCardListener  pollReadIDCardListener; //循环读取回调监听
    private volatile ReadIDCardListener onceReadIDCardInfoListener;//单次读取;

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


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

    @Override
    public void initIDCard(IDCardInfoLogListener listener) {
        switch (DxCardReader.getInstance().getStatusEnum()){
            case SUCCESS:
                if(listener!=null){
                    listener.initSuccess();
                }
                return;
            case  FAIL:
                if(listener!=null){
                    listener.initFailed(new IDCardError(-1,"身份证初始化失败"));
                }
                return;
            case DEFAULT:
                break;
        }
        init(listener);


    }

    /**
     *
     * @author xwh
     * Time 2024/10/10
     * Description: 初始化监听
     *
    **/
    private void init(IDCardInfoLogListener listener){
        DxCardReader.getInstance().init(BaseApplication.getContext(),DxMultiIDCardScan.class.getName(), new DxInitListener() {
            @Override
            public void onLogInfo(String msg) {

            }

            @Override
            public void initSuccess() {
                if(listener!=null){
                    listener.initSuccess();
                }

            }

            @Override
            public void initFailed(String code, String msg) {
                if(listener!=null){
                    listener.initFailed(new IDCardError(-1,"身份证初始化失败"));
                }
            }
        });
    }
    @Override
    public void startPollRead(ReadIDCardListener listener) {
        pollReadIDCardListener=listener;
        startRead();
    }

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

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

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

    @Override
    public void getIDCardUid(ReadIDCardListener listener) {

    }


    /**
     *
     * desc:启动轮询社保卡
     * @author xia weihao
     * @date 2024/6/26
     *
     */
    public void startRead() {
        DxCardReader.getInstance().setIdCardListener(new IDCardListener() {
            @Override
            public void result(long result, IDCardInfo idCardInfo) {
                if (result == 0) {
                    handleIDCardData(DxCardReader.getInstance().getCardReader(), idCardInfo);
                }else {
                    if(pollReadIDCardListener!=null){
                        pollReadIDCardListener.onError(new IDCardError(result,"读身份证失败"));
                    }
                }
            }
        });
    }

    /**
     *
     * desc:停止轮询读取社保卡
     * @author xia weihao
     * @date 2024/6/26
     *
     */
    public void stopRead() {
        DxCardReader.getInstance().setIdCardListener(null);
    }

    /**
     *
     * @author xwh
     * Time 2024/9/13
     * Description: 处理身份证阅读信息
     *
    **/
    private void handleIDCardData(  CardReader cardReader,final IDCardInfo idcard ) {

        IDCardBean idCardInfoBean = new IDCardBean();
        idCardInfoBean.setName(idcard.getName());
        idCardInfoBean.setIdNum(idcard.getIdNO());
        idCardInfoBean.setSex(idcard.getSex());
        idCardInfoBean.setAddress(idcard.getAddress());
        idCardInfoBean.setBirthDate(idcard.getBirthDate());
        idCardInfoBean.setNation(idcard.getNation());
        idCardInfoBean.setSigningOrganization(idcard.getOrgans());
        idCardInfoBean.setBeginTime(idcard.getIssueDate());
        idCardInfoBean.setEndTime(idcard.getExpireDate());

        String bmpPhotos = "";
        Bitmap image= null;
        try {

            image = cardReader.getBMPByWlt(idcard.getPhoto());
            if (image == null) {
                AppLogUtils.i("东信多合一身份证照片解码null ");
            } else {
                bmpPhotos = bitmapToString(image);
//                AppLogUtils.i("新中新身份证照片解码有值bmpPhotos--" +bmpPhotos);
                AppLogUtils.i("东信多合一身份证照片解码有值bmpPhotos--");
                idCardInfoBean.setPhotoBase64(bmpPhotos);
            }
        } catch (Exception e) {
            e.printStackTrace();
            AppLogUtils.i("东信多合一身份证照片解码异常 " + e);
        } finally {
            if (image != null && !image.isRecycled()) {
                image.recycle();
                image = null;
            }
        }
        if(onceReadIDCardInfoListener!=null){
            onceReadIDCardInfoListener.onSuccess(idCardInfoBean);
            stopCountDownTimer();
            onceReadIDCardInfoListener=null;
        }
        if(pollReadIDCardListener!=null){
            pollReadIDCardListener.onSuccess(idCardInfoBean);
        }


    }

    /**
     *
     * @author xwh
     * Time 2024/9/13
     * Description: 将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;
        }

    }

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

    @Override
    public void onRelease() {
        stopCountDownTimer();
        stopPollRead();
        stopRead();
        instance = null;
    }
}
