package com.hh.arome.common.scan.idcard.manymodels;

import android.app.Activity;
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.Handler;

import androidx.fragment.app.FragmentActivity;

import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.utils.StringUtils;
import com.hh.arome.common.scan.idcard.abstractidcard.IIDCardScan;
import com.hh.arome.common.scan.idcard.bean.IDCardInfoBean;
import com.hh.arome.common.scan.idcard.callback.IDCardInitResultCallback;
import com.hh.arome.common.scan.idcard.callback.IDCardScanResultCallback;
import com.hh.arome.utlis.log.AppLogUtils;
import com.telpo.tps550.api.idcard.IdCard;
import com.telpo.tps550.api.idcard.IdentityMsg;
import com.telpo.tps550.api.idcard.T2OReader;

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

public class TbIDCardScan implements IIDCardScan {


    //用volatile关键字确保 instance 在多线程下的可见性
    private static volatile TbIDCardScan instance = null;

    //将构造方法私有化，禁止外部通过构造方法创建实例
    private TbIDCardScan() {
    }

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


    Context mContext;
    Activity mActivity;


    // 扫身份证回调结果
    IDCardScanResultCallback idCardScanResultCallback;

    public TbIDCardScan(Context context) {
        if (context instanceof FragmentActivity) {
            this.mActivity = (Activity) context;
        }
        this.mContext = context;
    }


    T2OReader t2oReader = new T2OReader();
    private ScreenActionReceiver mScreenActionReceiver;
    boolean isOpen;

    // 初始化回调
    IDCardInitResultCallback idCardInitResultCallback;

    @Override
    public void initIDCard(IDCardInitResultCallback idCardInitResultCallback) {
        this.idCardInitResultCallback = idCardInitResultCallback;


        ThreadPoolManager.getInstance().removeIOTask(new Runnable() {
            @Override
            public void run() {
                AppLogUtils.e("initIDCard---openReader");
                openReader();
            }
        });




        //        t2oReader.openReader(mActivity);
//        if(waitForIDCardReaderReady()){
//            //身份证模块连接成功
//            AppLogUtils.e("D2-身份证模块连接成功");
//            isOpen = true;
//        }else{
//            //身份证模块连接失败
//            AppLogUtils.e("D2-身份证模块连接失败");
//            isOpen = false;
//
////            waitForIDCardReaderReady();
//        }

    }

    boolean isInitSuccess;

    int retryCount = 0;

    private void openReader() {

        AppLogUtils.e("openReader---isInitSuccess:"+isInitSuccess);
        if(isInitSuccess){
            return;
        }

        if(retryCount >= 10){
            return;
        }


        if (t2oReader.isUSBReader(mContext)) {
            boolean ret = t2oReader.openReader(mContext);
            if (ret) {
                AppLogUtils.e("--open usb reader success");
                idCardInitResultCallback.onIDCardInitSuccess();
                isInitSuccess = true;
                AppLogUtils.e("--ret---isInitSuccess:"+isInitSuccess);
            } else {
                AppLogUtils.e("--open usb reader fail");
                if(!isInitSuccess){
                    idCardInitResultCallback.onIDCardInitError("-1", "--open usb reader fail");
                }
                retryCount++;
            }
        } else {
            boolean ret = t2oReader.openReader();
            if (ret) {
                AppLogUtils.e("--open serial reader success");
                isInitSuccess = true;
                idCardInitResultCallback.onIDCardInitSuccess();
            } else {
                AppLogUtils.e("--open serial reader fail");
                if(!isInitSuccess){
                    idCardInitResultCallback.onIDCardInitError("-1", "--open serial reader fail");
                }
                retryCount++;
            }
        }

        if(!isInitSuccess){
            openReader();
        }


    }


    @Override
    public void startIDCardScan(IDCardScanResultCallback idCardScanResultCallback) {

        this.idCardScanResultCallback = idCardScanResultCallback;

        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
            @Override
            public void run() {
                startScan(idCardScanResultCallback);
            }
        });




    }

    private void startScan(IDCardScanResultCallback idCardScanResultCallback) {
        try {

            t2oReader.findIDCard();
            t2oReader.selectIDCard();

            IdentityMsg msgBean = t2oReader.checkIDCard();
            if (msgBean == null) {
//                idCardScanResultCallback.onIDCardError("-1","IdentityMsg为空");
//                return;

                t2oReader.findIDCard();
                t2oReader.selectIDCard();
                msgBean = IdCard.decodeIdCardBaseInfo(t2oReader.readIDCard(false));

                if (msgBean == null) {
//                    idCardScanResultCallback.onIDCardError("-1", "IdentityMsg为空");
//                    return;
//                    openReader();
                }

            }

//            AppLogUtils.e(msgBean.getApartment());
//            AppLogUtils.e(msgBean.getCard_type());
//            AppLogUtils.e(msgBean.getCardSignal());
//            AppLogUtils.e(msgBean.getPassNum());
//            AppLogUtils.e(msgBean.getNo());
//            AppLogUtils.e(msgBean.getPeriod());
//            AppLogUtils.e(msgBean.getReserve());

            if(msgBean == null){
                startIDCardScan(idCardScanResultCallback);
                return;
            }

            IDCardInfoBean idCardInfoBean = new IDCardInfoBean();
            idCardInfoBean.setIdcardName(msgBean.getName());
            idCardInfoBean.setIdcardNumber(msgBean.getNo());
            idCardInfoBean.setSex(msgBean.getSex());
            idCardInfoBean.setAddress(msgBean.getAddress());
            idCardInfoBean.setBirth(msgBean.getBorn());
            idCardInfoBean.setNation(msgBean.getNation());
            idCardInfoBean.setSigningOrganization(msgBean.getApartment());

            String period = msgBean.getPeriod();
            AppLogUtils.e("Period:"+msgBean.getPeriod());
            if(StringUtils.isNotNull(period)){
                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 = t2oReader.decodeIDImage(head_photo);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                photoBase64str = Base64.getEncoder().encodeToString(byteArray);
            }
            idCardInfoBean.setPhotoBase64(photoBase64str);


//            mHandler.post(new Runnable() {
//                @Override
//                public void run() {
                    idCardScanResultCallback.onIDCardScanSuccess(idCardInfoBean);
//                }
//            });


            // 恢复刷证
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startIDCardScan(idCardScanResultCallback);
                }
            },2000);





        } catch (Exception e) {

            idCardScanResultCallback.onIDCardError("-1", "读身份证异常");
            e.printStackTrace();
        }
    }


    Handler mHandler = new Handler();



    @Override
    public void resumeIDCardScan() {
        openReader();
//        isOpen = true;
    }

    @Override
    public void pauseIDCardScan() {
        //下电身份证阅读器
//        t2oReader.closeReader();
//        isOpen = false;
    }

    @Override
    public void stopIDCardScan() {
        //下电身份证阅读器
//        t2oReader.closeReader();
//        isOpen = false;
    }

    @Override
    public void destoryIDCardScan() {
        retryCount = 0;
        isInitSuccess = false;
        //下电身份证阅读器
        if(t2oReader!=null){
            t2oReader.closeReader();
        }
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }

        //取消注册监听
//        mContext.unregisterReceiver(mScreenActionReceiver);

        instance = null;
    }


    //接收屏幕事件
    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(mActivity);
                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) mContext.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;
    }


}
