package com.hh.xzx_readcard;

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

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 com.hh.xzx_readcard.bean.InitState;
import com.hh.xzx_readcard.idcard.ForeignerIDCard;
import com.hh.xzx_readcard.idcard.IDCards;

import java.io.ByteArrayOutputStream;

/**
 * @author xwh
 * time 2024/9/2
 * Description: 新中新身份证阅读器
 **/
public class XzxIDCardScan extends BaseIDCardScan {

    private static volatile XzxIDCardScan instance = null;

    public volatile IDCardInfoLogListener onILogListener; //初始化
    private volatile ReadIDCardListener  pollReadIDCardListener; //循环读取回调监听
    private volatile ReadIDCardListener onceReadIDCardInfoListener;//单次读取;
    //新中新身份证阅读器
    private IDCardReaderThread idCardReaderThread;
    private Handler mHandler;
    private long readIDCardTotalTime = 15 * 1000;
    private volatile CountDownTimer readIDCardCountDownTimer; //单次读卡超时倒计时

    private volatile InitState initSucessState= InitState.DEFAULT; //初始化状态
    private static final int MESSAGE_RETRY_READER = 0x90; //重连


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


    @Override
    public void initIDCard( IDCardInfoLogListener listener) {
        onILogListener = listener;
        readIDCardTotalTime = getConfig().getReadIDCardTotalTime();
        DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_USB);
        idCardReaderThread = new IDCardReaderThread();
        idCardReaderThread.setHandler(getmHandler());
        idCardReaderThread.open(null);
        getmHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    idCardReaderThread.read();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1000);

    }

    @Override
    public void startPollRead(ReadIDCardListener listener) {
        pollReadIDCardListener=listener;
        if (idCardReaderThread != null && !idCardReaderThread.isReading()) {
            try {
                idCardReaderThread.read();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @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) {

    }

    @Override
    public void onRelease() {
        closeRead();
        stopPollRead();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        DeviceConnectManager.getInstance().onRelease();
        initSucessState=InitState.DEFAULT;
        idCardReaderThread = null;
        instance = null;

    }



    public Handler getmHandler() {
        if (mHandler == null) {
            synchronized (XzxIDCardScan.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            String devName = DeviceConnectManager.getInstance().getDevName();
                            switch (msg.what) {
                                case DeviceConnectManager.MESSAGE_CONNECTED:
                                    //   Log.e("____________123", devName + "新中新身份证阅读器连接成功");
                                    if (onILogListener != null) {
                                        onILogListener.initSuccess();
                                    }
                                    initSucessState=InitState.SUCESS;
                                    break;
                                case DeviceConnectManager.MESSAGE_CONNECTING_DEVICE:
                                    //   Log.e("____________123", devName + "新中新身份证阅读器正在连接");
                                    break;
                                case DeviceConnectManager.MESSAGE_CONNECTFAILED:
                                    if(initSucessState!=InitState.FAILED){ //TODO 重连时，已经提示过失败了不再重复提示
                                        initSucessState=InitState.FAILED;
                                        if (onILogListener != null) {
                                            onILogListener.initFailed(new IDCardError(-1,""));
                                        }
                                    }
                                    getmHandler().removeMessages(MESSAGE_RETRY_READER);
                                    //初始化有延迟一秒轮询读取身份证，所以改为6秒
                                    getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER,6000);
                                    // Log.e("____________123", devName + "新中新身份证阅读器连接失败,尝试重连");
                                    if (onILogListener != null) {
                                        onILogListener.onLogInfo(devName + "新中新身份证阅读器连接失败,尝试重连");
                                    }

                                    break;
                                case DeviceConnectManager.MESSAGE_DISCONNECTED:
                                    // Log.e("____________123", devName + "新中新身份证阅读器连接断开");
                                    if (onILogListener != null) {
                                        onILogListener.onLogInfo("新中新身份证阅读器连接断开");
                                    }
                                    closeRead();
                                    break;
                                case DeviceConnectManager.MESSAGE_RECONNECT_DEVICE:
                                    //  Log.e("____________123", devName + "新中新身份证阅读器重新连接");
                                    if (onILogListener != null) {
                                        onILogListener.onLogInfo("身份证-" + "新中新身份证阅读器停止读卡....");
                                    }
                                    break;
                                case DeviceConnectManager.MESSAGE_STOP_READCARD:
                                    break;
                                case IDCardReaderThread.MESSAGE_START_READ:
                                    //  Log.e("____________123", "新中新身份证阅读器开始读卡");
                                    if (onILogListener != null) {
                                        onILogListener.onLogInfo("身份证-" + "新中新身份证阅读器开始读卡....");
                                    }
                                    break;
                                case IDCardReaderThread.MESSAGE_DISPLAY_IDCARD:
                                    // Log.e("____________123", "新中新身份证读卡信息  " + new Gson().toJson((IDCards) msg.obj));
                                    SendIdCard((IDCards) msg.obj);
                                    break;
                                case IDCardReaderThread.MESSAGE_STOP_READ:
                                    // Log.e("____________123", "新中新身份证阅读器停止读卡");
                                    if (null != onILogListener) {
                                        onILogListener.onLogInfo("身份证-" + "新中新身份证阅读器停止读卡....");
                                    }
                                    break;
                                case MESSAGE_RETRY_READER:
                                    closeRead();
                                    initIDCard(onILogListener);
                                    break;
                                default:
                                    break;
                            }
                            super.handleMessage(msg);
                        }
                    };
                }
            }
        }
        return mHandler;
    }

    /**
     *
     * @author xwh
     * Time 2024/9/3
     * Description: 新中新身份证信息返回
     *
     **/
    private void SendIdCard(IDCards idcard) {
        stopCountDownTimer();
        if (pollReadIDCardListener == null && onceReadIDCardInfoListener == null) {
            return;
        }
        if(idcard == null){
           // AppLogUtils.e("______________123"+"   未扫描到身份证信息");
            if(pollReadIDCardListener!=null) {
                pollReadIDCardListener.onError(new IDCardError(-1, "未扫描到身份证信息"));
            }
            return;
        }

        AppLogUtils.i("idcard:"+idcard.toString());

        String type = "";
        String name = "";
        String Cardid = "";
        String bmpPhotos = "";
        //普通居民身份证 或 港澳台居住证
        if (idcard.getCardType() == IDCards.CARDTYPE_NORMAL || idcard.getCardType() == IDCards.CARDTYPE_HMT) {
            name = idcard.getName() + "";
            Cardid = idcard.getIDCardNo();
        } else {//外国人居住证
            ForeignerIDCard card = idcard.getForeignerIDCard();
            name = card.getEngName() + "\n" + card.getCHNName();
            Cardid = card.getIDCardNo();
        }

        AppLogUtils.i(true, "mHandler_新中新身份证阅读器","新中新身份证读卡人员" + name
                + "新中新身份证读卡时间 " + idcard.getReadTime());
        IDCardBean idCardInfoBean = new IDCardBean();
        idCardInfoBean.setName(idcard.getName());
        idCardInfoBean.setIdNum(idcard.getIDCardNo());
        idCardInfoBean.setSex(idcard.getSex());
        idCardInfoBean.setAddress(idcard.getAddress());
        idCardInfoBean.setBirthDate(idcard.getBirthday());
        idCardInfoBean.setNation(idcard.getNation());
        idCardInfoBean.setSigningOrganization(idcard.getGrantDept());
        idCardInfoBean.setBeginTime(idcard.getUserLifeBegin());
        idCardInfoBean.setEndTime(idcard.getUserLifeEnd());

        try {
            Bitmap bmp = idcard.getPhoto();
            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);
        }
        if(pollReadIDCardListener!=null) {
            pollReadIDCardListener.onSuccess(idCardInfoBean);
        }
        if(onceReadIDCardInfoListener!=null){
            onceReadIDCardInfoListener.onSuccess(idCardInfoBean);
            stopCountDownTimer();
            onceReadIDCardInfoListener=null;
        }


    }

    /**
     *
     * @author xwh
     * Time 2024/9/3
     * 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: 关闭身份证阅读器
     *
     **/
    public void closeRead() {
        stopCountDownTimer();
        stopOnceReadIDCardInfo();
        if (idCardReaderThread != null) {
            idCardReaderThread.close();
        }
    }

    /**
     *
     * @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 XzxIDCardScan getInstance(IDCardConfig config) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (XzxIDCardScan.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new XzxIDCardScan(config);
                }
            }
        }
        return instance;
    }
}
