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

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;

import androidx.fragment.app.FragmentActivity;

import com.alipay.mobile.aromeservice.ipc.App;
import com.common.lib_base.common.async.ThreadPoolManager;
import com.common.lib_base.common.local.AppLocalConfigHandler;
import com.common.lib_base.utils.StringUtils;
import com.google.gson.Gson;
import com.hh.arome.common.IAppLocalConfig;
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.xzx.DeviceConnectManager;
//import com.hh.arome.common.scan.idcard.manymodels.xzx.IDCardReaderThread;
//import com.hh.arome.common.scan.idcard.manymodels.xzx.ReaderInterfaceFactory;
import com.hh.arome.utlis.log.AppLogUtils;
import com.synjones.DeviceConnectManager;
import com.synjones.ReaderInterfaceFactory;
import com.synjones.idcard.ForeignerIDCard;
import com.synjones.idcard.IDCards;
import com.synjones.idcardusb_reader.IDCardReaderThread;

import java.io.ByteArrayOutputStream;


public class XzxIDCardScan implements IIDCardScan {


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

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

    public XzxIDCardScan(Context context, boolean isOverTime) {
//        this.mContext = context;
        this.isOverTime = isOverTime;

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

    }

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


    Context mContext;
    Activity mActivity;

    IAppLocalConfig localConfig;

    public XzxIDCardScan(Context context) {
        if (context instanceof FragmentActivity) {
            this.mActivity = (Activity) context;
        }
        this.mContext = context;
        localConfig = AppLocalConfigHandler.create(mContext.getApplicationContext(), IAppLocalConfig.class);
        init();
    }

    // 重试次数
    int retryCount = 0;
    // 最大重试次数
    int retryMaxCount = 5;

    //新中新身份证阅读器
    IDCardReaderThread idCardReaderThread;
    final int UPDATE_READER_STATUS = 0x40;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String devName = DeviceConnectManager.getInstance().getDevName();
            switch (msg.what) {
                case DeviceConnectManager.MESSAGE_CONNECTED:
                    AppLogUtils.i(devName + "新中新身份证阅读器连接成功");
                    idCardInitResultCallback.onIDCardInitSuccess();
                    break;
                case DeviceConnectManager.MESSAGE_CONNECTING_DEVICE:
                    AppLogUtils.i(devName + "新中新身份证阅读器正在连接");
                    break;
                case DeviceConnectManager.MESSAGE_CONNECTFAILED:
                    AppLogUtils.i(devName + "新中新身份证阅读器连接失败,尝试重连");
//                    idCardInitResultCallback.onIDCardInitError("-1",devName + "新中新身份证阅读器连接失败,尝试重连");

                    retryCount++;
                    AppLogUtils.i("retryCount--"+retryCount);
                    AppLogUtils.i("retryMaxCount--"+retryMaxCount);

                    if(retryCount >= retryMaxCount){
                        AppLogUtils.i(devName + "新中新身份证阅读器连接失败回调");
                        idCardInitResultCallback.onIDCardInitError("-1",devName + "新中新身份证阅读器连接"+retryCount+"次后连接失败");
                        return;
                    }

                    AppLogUtils.i("重连--");

                    clearXzx();

                    init();

//                    closeRead();
//                    startRead(100);

                    break;
                case DeviceConnectManager.MESSAGE_DISCONNECTED:
                    AppLogUtils.i(devName + "新中新身份证阅读器连接断开");
                    closeRead();
                    break;
                case DeviceConnectManager.MESSAGE_RECONNECT_DEVICE:
                    AppLogUtils.i(devName + "新中新身份证阅读器重新连接");
                    break;
                case DeviceConnectManager.MESSAGE_STOP_READCARD:
                    break;
                case IDCardReaderThread.MESSAGE_START_READ:
                    AppLogUtils.i("新中新身份证阅读器开始读卡");
                    ThreadPoolManager.getInstance().executeIOTask(new MyTimer());
//                    new MyTimer().start();
                    break;
                case IDCardReaderThread.MESSAGE_DISPLAY_IDCARD:
                    AppLogUtils.i("新中新身份证读卡信息  " + new Gson().toJson((IDCards) msg.obj));
                    SendIdCard((IDCards) msg.obj);
//                    overtime = allTime;
                    break;
                case IDCardReaderThread.MESSAGE_STOP_READ:
                    AppLogUtils.i("新中新身份证阅读器停止读卡");
                    break;
                case UPDATE_READER_STATUS:
                    AppLogUtils.i("身份证读卡耗时等信息  " + idCardReaderThread.getReadStatus());
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void clearXzx() {
        if (idCardReaderThread!=null) {
            idCardReaderThread.stop();
            idCardReaderThread.close();
            idCardReaderThread = null;
        }
    }

    boolean isOverTime;


    /**
     * 新中新身份证阅读器
     */
    class MyTimer extends Thread {
        @Override
        public void run() {
            AppLogUtils.i("MyTimer");


//            isOverTime = localConfig.getScanIdCardOverTime();
//            AppLogUtils.i("isOverTime--"+isOverTime);
//
//            if(isOverTime){
//                isComplete = false;
//                mHandler.postDelayed(timeRunnable, 1000);// 每秒執行一次runnable.
//            }

            if(idCardReaderThread == null){
                return;
            }
            try {
                while (idCardReaderThread
                        .isReading()) {
                    mHandler.obtainMessage(UPDATE_READER_STATUS).sendToTarget();
                    try {
                        Thread.sleep(250);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                AppLogUtils.i(e.toString());
            }
        }
    }

    //新中新身份证信息返回
    private void SendIdCard(IDCards idcard) {



        if(idCardScanResultCallback == null){
            AppLogUtils.i("idCardScanResultCallback == null");
            return;
        }

        if(idcard == null){
            idCardScanResultCallback.onIDCardError("-1","未扫描到身份证信息");
//            isComplete = true;
            localConfig.setScanIdCardOverTime(false);
            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());



        IDCardInfoBean idCardInfoBean = new IDCardInfoBean();
        idCardInfoBean.setIdcardName(idcard.getName());
        idCardInfoBean.setIdcardNumber(idcard.getIDCardNo());
        idCardInfoBean.setSex(idcard.getSex());
        idCardInfoBean.setAddress(idcard.getAddress());
        idCardInfoBean.setBirth(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);
        }

        // 因为aidl解析图片出错，试试原始的wlt
//        if(StringUtils.isNull(idCardInfoBean.getPhotoBase64())){
//            // 获取photoBase64str
//            byte[] head_photo = idcard.getWlt();
//            String photoBase64str = "";
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                photoBase64str = java.util.Base64.getEncoder().encodeToString(head_photo);
//            }
//            idCardInfoBean.setPhotoBase64(photoBase64str);
//        }



        idCardScanResultCallback
                .onIDCardScanSuccess(
                idCardInfoBean);
//        isComplete = true;
        localConfig.setScanIdCardOverTime(false);



    }

    //将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 "";
        }
    }
//    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 "";
//        }
//    }


    private void init() {

        AppLogUtils.i("init");
        if(mHandler == null){
            mHandler = new Handler();
        }

        DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_USB);

//        ThreadPoolManager.getInstance().executeIOTask(new Runnable() {
//            @Override
//            public void run() {
//                AppLogUtils.i("initIDCard---idCardReaderThread");

                idCardReaderThread = new IDCardReaderThread();
                idCardReaderThread.setActivityAndHandler(mActivity, mHandler);
                idCardReaderThread.open(null);
        startRead(1000);
//            }
//        });


    }

    IDCardInitResultCallback idCardInitResultCallback;
    IDCardScanResultCallback idCardScanResultCallback;

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

//    boolean isComplete;
//    public static final int allTime = 15;
//    int overtime = allTime;
//
    // 倒计时任务
//    Runnable timeRunnable = new Runnable() {
//        @Override
//        public void run() {
//
//            if(isComplete){
//                return;
//            }
//
//            AppLogUtils.i("isComplete:"+isComplete);
//            AppLogUtils.i("overtime:"+overtime);
//            if (overtime == 0 && !isComplete) {
//                idCardScanResultCallback.onIDCardError("-1","超时");
//                isComplete = true;
//                localConfig.setScanIdCardOverTime(false);
//                mHandler.removeCallbacks(timeRunnable);
//                return;
//            }
//
//            if(overtime < 0){
//                idCardScanResultCallback.onIDCardError("-1","超时");
//                isComplete = true;
//                localConfig.setScanIdCardOverTime(false);
//                mHandler.removeCallbacks(timeRunnable);
//                return;
//            }
//
//            // 设置最新时间
//            overtime--;
//            // 接着发送刷新任务
//            mHandler.postDelayed(timeRunnable, 1000);
//        }
//    };

    @Override
    public void startIDCardScan(IDCardScanResultCallback idCardScanResultCallback) {
        this.idCardScanResultCallback = idCardScanResultCallback;

//        overtime = allTime;
//        isComplete = false;
//        AppLogUtils.i("startIDCardScan--重置倒计时");
        startRead(100);

    }

    public void startRead(int time){
        if(mHandler == null){
            return;
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                if(idCardReaderThread == null){
//                    idCardReaderThread = new IDCardReaderThread();
//                }
                if(idCardReaderThread!=null){
                    try {
                        idCardReaderThread.read();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
//        },time*1000);
        },time);
    }


    public void closeRead(){
        if(idCardReaderThread!=null){
            idCardReaderThread.close();
        }
    }

    @Override
    public void resumeIDCardScan() {

    }

    @Override
    public void pauseIDCardScan() {

    }

    @Override
    public void stopIDCardScan() {

    }

    @Override
    public void destoryIDCardScan() {
        localConfig.setScanIdCardOverTime(false);
        retryCount = 0;
        if (idCardReaderThread!=null) {
            idCardReaderThread.stop();
            idCardReaderThread.close();
            idCardReaderThread = null;
        }
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        instance = null;
    }
}
