package com.hh.lib_dx_qr;

import static com.hh.lib_base.Constants.LogcatValue.LOG_NODE_QR;
import static com.hh.lib_base.Constants.LogcatValue.WARP;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.google.gson.Gson;
import com.hh.ib_base_qr.BaseQRScan;
import com.hh.ib_base_qr.QRInitListener;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.Constants;
import com.hh.lib_base.bean.InitStatusEnum;
import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.UploadLogUtils;
import com.hh.lib_base.utils.device.DeviceUtils;
import com.hh.lib_serialport.MyFunc;
import com.hh.lib_serialport.Serial.SerialPortFinder;
import com.hh.lib_serialport.SerialHelper;
import com.hh.lib_serialport.bean.ComBean;

import java.io.IOException;
import java.security.InvalidParameterException;

/**
 * Description: 东信普通二维码
 * @author xwh
 * time 2024/10/9
 **/
public class DxGeneralQRScan extends BaseQRScan {

    private static volatile DxGeneralQRScan instance = null;

    private QRInitListener qrInitListener;
    private Handler mHandler;

    private volatile QrUsb qrUsb; //USB 二维码-普通东信
    private volatile InitStatusEnum statusEnum = InitStatusEnum.DEFAULT;//设备是否初始化


    private  QrCodeSerialControl qrCodeSerial; //串口二维码

    @Override
    public void onInit(QRInitListener qrInitListener) {
        this.qrInitListener=qrInitListener;
        initQr();
    }


    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 这段逻辑目前和重构之前一样，先初始化串口，如果失败则初始化东信普通二维码（USB）
     *
    **/
    public void initQr(){
        String logLine = (new Throwable().getStackTrace())[0].toString();
        UploadLogUtils.sendLogs(LOG_NODE_QR,"",
                logLine,"二维码---初始化---开始打开串口");
        qrCodeSerial = new QrCodeSerialControl();
        String pat = "";
        String deviceModel = DeviceUtils.getDeviceModel();
        if (Build.MODEL.indexOf("F2") != -1) {
            pat = "/dev/ttyACM0";
        } else if (Build.MODEL.indexOf("TPS980") != -1) {
            pat = "/dev/ttyS0";
        } else if (Build.MODEL.indexOf("K8") != -1) {
            pat = "/dev/ttyACM0";
        } else if (deviceModel.equals(Constants.DeviceModel.D2)) {
            pat = "/dev/ttyHSL0";
        } else {
            String[] DevicesPath = new SerialPortFinder().getAllDevicesPath();
            AppLogUtils.e("-------startQrCodeSeria串口-----" + new Gson().toJson(DevicesPath));
            boolean isACM = false;
            for (int i = 0; i < DevicesPath.length; i++) {
                if (DevicesPath[i].indexOf("/dev/ttyACM") != -1) {
                    isACM = true;
                    continue;
                }
            }
            if (isACM) {
                for (int i = 0; i < DevicesPath.length; i++) {
                    if (DevicesPath[i].indexOf("ttyACM") != -1) {
                        pat = DevicesPath[i];
                        return;
                    }
                }
            } else {
                String logLine22 = (new Throwable().getStackTrace())[0].toString();
                String logNode22 = "二维码---初始化---打开串口失败---未能找到对应串口";
                UploadLogUtils.sendLogs(LOG_NODE_QR,"",logLine22,logNode22);
                // 开始USB
                startUsbQr();


                return;
            }
        }
        AppLogUtils.e("--------------pat串口路径  " + pat);


        // 设置串口路径
        qrCodeSerial.setPort(pat);
        // 波特率
        qrCodeSerial.setBaudRate("9600");
        OpenQrCodeComPort(qrCodeSerial);
    }

    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 启动串口
     *
    **/
    public void OpenQrCodeComPort(SerialHelper comPort) {
        try {
            comPort.open();
            String logLine11 = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine11, "初始化---打开串口成功");
            if (qrInitListener!=null){
                qrInitListener.onInitSuccess();
            }

        } catch (SecurityException e) {
            AppLogUtils.e("-----------打开串口失败:没有串口读/写权限");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine, "初始化---打开串口失败:没有串口读/写权限");
            if (qrInitListener!=null){
                qrInitListener.onInitFail(-1,"打开串口失败:没有串口读/写权限");
            }

        } catch (IOException e) {
            AppLogUtils.e("-----------打开串口失败:未知错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine, "初始化---打开串口失败:未知错误");

        } catch (InvalidParameterException e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine, "初始化---打开串口失败:参数错误");
        }catch (UnsatisfiedLinkError e2) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine, "初始化---打开串口失败:串口地址不存在");
            return;
        } catch (Exception e) {
            AppLogUtils.e("-----------打开串口失败:参数错误");
            String logLine = (new Throwable().getStackTrace())[0].toString();
            UploadLogUtils.sendLogs(LOG_NODE_QR, "---",
                    logLine, "初始化---打开串口失败:"+e.toString());
            return;
        }
    }
    /**
     *
     * @author xwh
     * Time 2024/10/11
     * Description: 串口读写
     *
    **/
    public class QrCodeSerialControl extends SerialHelper {
        public QrCodeSerialControl() {
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData) {
            AppLogUtils.e("-----------原始数据 bRec  " + new Gson().toJson(ComRecData.bRec));
//            qrCodeQueueList.clear();
//            qrCodeQueueList.add(ComRecData);
            AppLogUtils.e("-------数据处理后  " + MyFunc.ByteArrToHex(ComRecData.bRec));
            String qrData = new String(ComRecData.bRec);
            AppLogUtils.e("-------qrData  " + qrData);
            String logLine = (new Throwable().getStackTrace())[0].toString();
            StringBuilder logContentSb = new StringBuilder();
            logContentSb .append("原始数据 = ").append(new Gson().toJson(ComRecData.bRec)).append(WARP)
                    .append("原始数据MyFunc转换 = ").append(MyFunc.ByteArrToHex(ComRecData.bRec)).append(WARP)
                    .append("qrData = ").append(qrData);
            UploadLogUtils.sendLogs(false,Constants.LogcatValue.LOG_NODE_QR,"",logLine,logContentSb.toString());
            onScanSuccess(qrData);
        }

        //尝试进行转换
        @Override
        protected void DoQueue() {
        }
    }


    /**
     *
     * @author xwh
     * Time 启动东信普通二维码
     * Description:
     *
    **/
    private synchronized void startUsbQr() {
        if(qrUsb==null){
            synchronized (DxGeneralQRScan.this){
                if(qrUsb==null){
                    qrUsb = new QrUsb();
                    qrUsb.init(BaseApplication.getContext(), new QrUsb.DxQrResultCallback() {
                        @Override
                        public void onSuccess(String qrCode) {
                            onScanSuccess(qrCode);
                        }

                        @Override
                        public void onFail() {
                            onScanFail("");
                        }

                        @Override
                        public void onInitSuccess() {
                            if(qrInitListener!=null){
                                qrInitListener.onInitSuccess();
                            }
                            statusEnum= InitStatusEnum.SUCCESS;
                            //todo "二维码-" + "USB-扫码头初始化成功...."
                            mHandler.removeMessages(3);
                        }

                        @Override
                        public void onInitFail(int code, String errMsg) {

                            //todo "二维码-" + "USB-扫码头初始化失败....\n" + errMsg
                            if(statusEnum!=InitStatusEnum.FAIL){
                                statusEnum=InitStatusEnum.FAIL;
                                if(qrInitListener!=null){
                                    qrInitListener.onInitFail(code, errMsg);
                                }
                            }
                            getmHandler().removeMessages(3);
                            getmHandler().sendEmptyMessageDelayed(3,5000);
                        }
                    });
                }
            }
        }
    }





    @Override
    public void onScanSuccess(String qrCode) {
        if(qrResultCallback!=null){
            qrResultCallback.onScanSuccess(qrCode);
        }
    }

    @Override
    public void onScanFail(String errMsg) {
        if(qrResultCallback!=null){
            qrResultCallback.onScanFail();
        }
    }

    @Override
    public void onRelease() {
        instance = null;
        qrResultCallback = null;
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        if (qrUsb != null) {
            qrUsb.onRelease();
            qrUsb = null;
        }
        if (qrCodeSerial != null) {
            qrCodeSerial.close();
            qrCodeSerial = null;
        }
    }


    public Handler getmHandler() {
        if (mHandler == null) {
            synchronized (DxGeneralQRScan.class) {
                if (mHandler == null) {
                    mHandler = new Handler(Looper.getMainLooper()) {
                        @Override
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case 3:
                                    if(msg.what==3){
                                        if (qrUsb != null) {
                                            qrUsb.onRelease();
                                            qrUsb = null;
                                        }
                                        startUsbQr();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            super.handleMessage(msg);
                        }
                    };
                }
            }
        }
        return mHandler;
    }

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