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

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.common.lib_base.utils.ui.ToastUtils;
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.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.common.scan.idcard.manymodels.er301.ReadCardManagerER301;
import com.hh.arome.utlis.log.AppLogUtils;

import java.io.ByteArrayOutputStream;

/**
 * 金联汇通
 * 适用于ER301在线身份证设备
 */
public class JlhtER301IDCardScan implements IIDCardScan {


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

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

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


    Context mContext;
    Activity mActivity;

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

    private void init() {
        //
        ReadCardManagerER301.initEid(1, 1);


    }

    private boolean deviceIsConnect = false;//当前usb设备是否连接

    /**
     * 初始化USB设备
     */
    private void initUsbDevice() {
        ReadCardManagerER301.eid.initlUSbDevice(mContext, 8898, 12289, new InitCallback() {
            @Override
            public void onSuccess() {
                deviceIsConnect = true;
                idCardInitResultCallback.onIDCardInitSuccess();

            }

            @Override
            public void onFailed() {
                deviceIsConnect = false;
                idCardInitResultCallback.onIDCardInitError("-1","初始化USB失败");

            }
        });


    }

    IDCardInitResultCallback idCardInitResultCallback;

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

    IDCardScanResultCallback idCardScanResultCallback;

    @Override
    public void startIDCardScan(IDCardScanResultCallback idCardScanResultCallback) {

        this.idCardScanResultCallback = idCardScanResultCallback;

        initStartCard();
    }

    private void initStartCard() {
        if (deviceIsConnect) { //当前usb是否连接
            readCard();
        } else {
            AppLogUtils.e("未找到设备,初始化USB");
            initUsbDevice();
        }
    }

    private long startTime;

    private void readCard() {
        ReadCardManagerER301.eid.readCard(new OnGetResultListener() {
            @Override
            public void onSuccess(EidlinkResult result) {

                AppLogUtils.e("\n读卡成功耗时：" + (System.currentTimeMillis() - startTime) + "ms");
                IdInfoBean idInfoBean = result.getIdInfoBean();
                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初始化失败";
                    initUsbDevice();
                    return;
                }

                if(TextUtils.isEmpty(msg)){
                    msg = "读卡失败,请重试";
                }

                idCardScanResultCallback.onIDCardError(code+"",msg);
                // 开始读取
                readCard();

            }

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

            @Override
            public void findCard() {
                super.findCard();
                startTime = System.currentTimeMillis();
            }

        });


    }



    private void handleIDCardData(final IdInfoBean idcard) {

        IDCardInfoBean idCardInfoBean = new IDCardInfoBean();
        idCardInfoBean.setIdcardName(idcard.getName());
        idCardInfoBean.setIdcardNumber(idcard.getIdnum());
        idCardInfoBean.setSex(idcard.getSex());
        idCardInfoBean.setAddress(idcard.getAddress());
        idCardInfoBean.setBirth(idcard.getBirthDate());
        idCardInfoBean.setNation(idcard.getNation());
        idCardInfoBean.setSigningOrganization(idcard.getSigningOrganization());
        idCardInfoBean.setBeginTime(idcard.getBeginTime());
        idCardInfoBean.setEndTime(idcard.getEndTime());

        String bmpPhotos = "";
        try {
            byte[] picData = Base64.decode(idcard.getPicture(), Base64.DEFAULT);
            // 头像图片
            Bitmap 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);
        }

        idCardScanResultCallback.onIDCardScanSuccess(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 "";
            }
        }


    @Override
    public void resumeIDCardScan() {

    }

    @Override
    public void pauseIDCardScan() {

    }

    @Override
    public void stopIDCardScan() {

    }

    @Override
    public void destoryIDCardScan() {

    }
}
