package com.hh.lib_tb_readcard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.bean.InitStatusEnum;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.utils.StringUtils;
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.telpo.tps550.api.idcard.IdCard;
import com.telpo.tps550.api.idcard.IdentityMsg;
import com.telpo.tps550.api.idcard.T2OReader;
import com.zkteco.android.IDReader.IDPhotoHelper;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;

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

    private static volatile TbIDCardScan instance = null;
    private static volatile T2OReader t2oReader = null;

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

    private Handler mHandler;
    private static final int MESSAGE_RETRY_READER = 0x90; //重连身份证阅读器
    private static final int MESSAGE_RETRY_READCARE = 0x91; //重新读取身份证

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

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

    @Override
    public void initIDCard(IDCardInfoLogListener listener) {
        onILogListener = listener;
        initReader();
    }

    InitStatusEnum statusEnum = InitStatusEnum.DEFAULT;

    /**
     * @author xwh
     * Time 2024/9/5
     * Description: 初始化启动身份证阅读器
     **/
    private void initReader() {
        ThreadPoolManager.getInstance().executeCpuTask(new Runnable() {
            @Override
            public void run() {
                AppLogUtils.e("initIDCard---openReader");
                openReader();
            }
        });

    }

    /**
     * @author xwh
     * Time 2024/9/5
     * Description: 启动身份证阅读器
     **/
    private void openReader() {
        AppLogUtils.e("openReader---isInitSuccess:" + statusEnum);
        if (statusEnum == InitStatusEnum.SUCCESS) {
            return;
        }
        if (getT2oReader().isUSBReader(BaseApplication.getContext())) {
            boolean ret = getT2oReader().openReader(BaseApplication.getContext());
            if (ret) {
                AppLogUtils.e("--open usb reader success");
                getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        statusEnum = InitStatusEnum.SUCCESS;
                        if (onILogListener != null) {
                            onILogListener.initSuccess();
                        }
                        startScan();
                    }
                });
                AppLogUtils.e("--ret---isInitSuccess:" + statusEnum);
            } else {
                AppLogUtils.e("--open usb reader fail");
                if (statusEnum != InitStatusEnum.FAIL) {
                    statusEnum = InitStatusEnum.FAIL;
                    if (onILogListener != null) {
                        getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                onILogListener.initFailed(new IDCardError(-1, "--open usb reader fail"));
                            }
                        });

                    }
                }
                getmHandler().removeMessages(MESSAGE_RETRY_READER);
                getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READER, 5000);

            }
        } else {
            boolean ret = getT2oReader().openReader();
            if (ret) {
                AppLogUtils.e("--open serial reader success");
                getmHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        statusEnum = InitStatusEnum.SUCCESS;
                        if (onILogListener != null) {
                            onILogListener.initSuccess();
                        }
                        startScan();
                    }
                });
            } else {
                AppLogUtils.e("--open serial reader fail");
                if (statusEnum != InitStatusEnum.FAIL) {
                    statusEnum = InitStatusEnum.FAIL;
                    if (onILogListener != null) {
                        getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                onILogListener.initFailed(new IDCardError(-1, "--open serial reader fail"));
                            }
                        });

                    }
                }
                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 startScan(){
        ThreadPoolManager.getInstance().executeCpuTask(new Runnable() {
            @Override
            public void run() {
                readScan();
            }
        });
    }

    private void readScan() {
        try {
            IdentityMsg msgBean =   getT2oReader().checkIDCard();
            if (msgBean == null) {
                getT2oReader().findIDCard();
                getT2oReader().selectIDCard();
                msgBean = IdCard.decodeIdCardBaseInfo( getT2oReader().readIDCard(false));
            }
            if (msgBean == null) {
                getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READCARE, 500);
                return;
            }
            IDCardBean idCardInfoBean = new IDCardBean();
            idCardInfoBean.setName(msgBean.getName());
            idCardInfoBean.setIdNum(msgBean.getNo());
            idCardInfoBean.setSex(msgBean.getSex());
            idCardInfoBean.setAddress(msgBean.getAddress());
            idCardInfoBean.setBirthDate(msgBean.getBorn());
            idCardInfoBean.setNation(msgBean.getNation());
            idCardInfoBean.setSigningOrganization(msgBean.getApartment());

            String period = msgBean.getPeriod();
            AppLogUtils.e("Period:" + msgBean.getPeriod());
            if (StringUtils.isNotNull(period) && period.length() >= 23) {
                String begin = period.substring(0, 10);
                String end = period.substring(13, 23);

                AppLogUtils.e("begin:" + begin);
                AppLogUtils.e("end:" + end);

                idCardInfoBean.setBeginTime(begin);
                idCardInfoBean.setEndTime(end);
            }


            // 获取photoBase64str
         //   byte[] head_photo = msgBean.getHead_photo();
            String photoBase64str = "";
            Bitmap bitmap = null;
            IdentityMsg identityMsg = getT2oReader().checkIDCard();
            if (identityMsg != null) {

                bitmap = getT2oReader().decodeIDImage(identityMsg.getHead_photo());
                if (bitmap != null) {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    photoBase64str = encodeToString(byteArray);
                }
            }
            idCardInfoBean.setPhotoBase64(photoBase64str);
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }

            getmHandler().post(new Runnable() {
                @Override
                public void run() {
                    if(onceReadIDCardInfoListener!=null){
                        onceReadIDCardInfoListener.onSuccess(idCardInfoBean);
                        stopCountDownTimer();
                        onceReadIDCardInfoListener=null;
                    }
                    if(pollReadIDCardListener!=null){
                        pollReadIDCardListener.onSuccess(idCardInfoBean);
                    }


                }
            });

            // 恢复刷证
            getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READCARE, 1500);


        } catch (Exception e) {
            AppLogUtils.e(e.toString());
            getmHandler().removeMessages(MESSAGE_RETRY_READCARE);
            getmHandler().sendEmptyMessageDelayed(MESSAGE_RETRY_READCARE, 1500);
            getmHandler().post(new Runnable() {
                @Override
                public void run() {
                    if(pollReadIDCardListener!=null){
                        pollReadIDCardListener.onError(new IDCardError(-1,"读身份证异常："+e.toString()));
                    }
                }
            });

        }
    }

    /**
     *
     * @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 Handler getmHandler() {
        if (mHandler == null) {
            synchronized (TbIDCardScan.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case MESSAGE_RETRY_READER:
                                    initReader();
                                    break;
                                case MESSAGE_RETRY_READCARE:
                                    startScan();
                                    break;
                                default:
                                    break;
                            }
                            super.handleMessage(msg);
                        }
                    };
                }
            }
        }
        return mHandler;
    }

    public static TbIDCardScan getInstance(IDCardConfig config) {
        //如果instance为空，就进行实例化
        if (instance == null) {
            //保证多线程下只有一个线程进行实例化
            synchronized (TbIDCardScan.class) {
                //第二次判断，避免多线程下创建多个实例
                if (instance == null) {
                    instance = new TbIDCardScan(config);
                }
            }
        }
        return instance;
    }

    public static T2OReader getT2oReader() {
        if (t2oReader == null) {
            synchronized (TbIDCardScan.class) {
                if (t2oReader == null) {
                    t2oReader = new T2OReader();
                }
            }
        }
        return t2oReader;
    }




    //接收屏幕事件
    public class ScreenActionReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                //下电身份证阅读器
                t2oReader.closeReader();
            }

            if (action.equals(Intent.ACTION_SCREEN_ON)) {

                //上电身份证阅读器
                t2oReader.openReader(BaseApplication.getContext());
                if (waitForIDCardReaderReady()) {
                    //身份证模块连接成功
                } else {
                    //身份证模块连接失败
                }
            }
        }
    }

    /**
     * 上电后调用此方法等待身份证阅读器连接
     *
     * @return true，连接上  false 连接失败
     */
    private boolean waitForIDCardReaderReady() {
        AppLogUtils.e("waitForIDCardReaderReady");
        for (int count = 0; count < 50; count++) {
            if (isIDCardReaderConnected()) {
                return true;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    private boolean isIDCardReaderConnected() {
        AppLogUtils.e("isIDCardReaderConnected");
        UsbManager usbManager = (UsbManager) BaseApplication.getContext().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = usbManager.getDeviceList();
        for (String key : usbList.keySet()) {
            UsbDevice usbDevice = usbList.get(key);
            if (usbDevice != null && usbDevice.getProductId() == 0xc35a && usbDevice.getVendorId() == 0x0400) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onRelease() {
        statusEnum = InitStatusEnum.DEFAULT;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        //下电身份证阅读器
        if (t2oReader != null) {
            t2oReader.closeReader();
            t2oReader=null;
        }


        //取消注册监听
//        mContext.unregisterReceiver(mScreenActionReceiver);
        ThreadPoolManager.getInstance().shutdownExecutor();
        instance = null;
    }

    public static String encodeToString(byte[] data) {
        return android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);
    }
}
