package com.hh.lib_m1_card;


import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.donsee.devices.CardReader;
import com.donsee.devices.HexUtil;
import com.hh.lib_m1_card.bean.AmpeResultM1CardBean;
import com.hh.lib_m1_card.bean.DxM1CardLoopResultBean;
import com.hh.lib_m1_card.config.M1CardConfig;
import com.hh.lib_m1_card.config.M1CardInitvalConfig;
import com.hh.lib_m1_card.config.M1CardWriteConfig;
import com.hh.lib_ampe.bean.BaseAmpeAppletResultBean;
import com.hh.lib_base.BaseApplication;
import com.hh.lib_base.utils.GsonUtils;
import com.hh.lib_dx_base_multi.DxInitListener;
import com.hh.lib_dx_base_multi.serialport.DxSerialportCardReader;
import com.hh.lib_dx_base_multi.serialport.listener.ReadM1CardListener;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/11/5
 **/
public class DxM1CardReader {
    private static volatile DxM1CardReader instance = null;
    private M1CardConfig m1CardLoopConfig;
    private M1CardReaderResultListener m1CardReaderResultListener;

    private final int SUCCESS = 0; //读卡器操作时状态 >=0 成功;

    public DxM1CardReader() {
        init(BaseApplication.getContext());
    }


    public void setM1CardLoopConfig(M1CardConfig m1CardLoopConfig) {
        this.m1CardLoopConfig = m1CardLoopConfig;
    }

    /**
     * @author xwh
     * Time 2024/11/5
     * Description: 初始化
     **/
    public void init(Context context) {
        switch (DxSerialportCardReader.getInstance().getStatusEnum()) {
            case SUCCESS:
                if (m1CardReaderResultListener != null) {
                    m1CardReaderResultListener.onInitSuccessState(true);
                    m1CardReaderResultListener.onLogInfo("NFC-M1卡  初始化串口成功！");
                }
                DxSerialportCardReader.getInstance().setReadM1CardListener(readM1CardListener);
                return;
            case FAIL:
                if(m1CardReaderResultListener !=null){
                    m1CardReaderResultListener.onInitSuccessState(false);
                    m1CardReaderResultListener.onLogInfo("NFC-M1卡  初始化串口失败！");
                }
                DxSerialportCardReader.getInstance().setReadM1CardListener(null);
                return;
            case DEFAULT:
                break;
        }
        initReader(context);
    }

    /**
     * @author xwh
     * Time 2024/11/5
     * Description: 初始化读卡器
     **/
    private void initReader(Context context) {
        DxSerialportCardReader.getInstance().init(context, DxM1CardReader.class.getName(), new DxInitListener() {
            @Override
            public void onLogInfo(String msg) {

            }

            @Override
            public void initSuccess() {
                if (m1CardReaderResultListener != null) {
                    m1CardReaderResultListener.onInitSuccessState(true);
                    m1CardReaderResultListener.onLogInfo("NFC-M1卡  初始化串口成功！");
                }
                DxSerialportCardReader.getInstance().setReadM1CardListener(readM1CardListener);
            }

            @Override
            public void initFailed(String code, String msg) {
                if(m1CardReaderResultListener !=null){
                    m1CardReaderResultListener.onInitSuccessState(false);
                    m1CardReaderResultListener.onLogInfo("NFC-M1卡  初始化串口失败！");
                }
                DxSerialportCardReader.getInstance().setReadM1CardListener(null);
            }
        });
    }


    ReadM1CardListener readM1CardListener = new ReadM1CardListener() {
        @Override
        public void readM1() throws InterruptedException {
            readM1Card();
        }
    };

    /**
     *
     * @author xwh
     * Time 2024/11/8
     * Description: 读M1卡
     *
    **/
    private void readM1Card()throws InterruptedException{
        byte[] uid = new byte[64];
        byte[] resp = new byte[30];
        long ret = 0;
        CardReader cardReader=DxSerialportCardReader.getInstance().getCardReader();
        if(cardReader == null){
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("readM1Card cardReader = null");
            }
            return;
        }
        if (m1CardLoopConfig == null) {
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("M1读取失败：" + "配置为空");
            }
            return;
        }
        ret = cardReader.Donsee_ReadICUid(uid);
        if (ret < 0) {
            long finalRet = ret;
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("M1读取失败：" + CardReader.getErrorMessage(finalRet));
            }
        }else{
            Thread.sleep(20);
            String uidInfo = HexUtil.bytesToHex(uid, 4);
            ret = cardReader.Donsee_M1VerifyPass(m1CardLoopConfig.getKeyMode(),
                    ((byte) m1CardLoopConfig.getSector()), HexUtil.hexToBytes(m1CardLoopConfig.getSecretKey()));
            if (ret != SUCCESS) {
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("M1读取失败：" +"秘钥认证失败");
                }
                return;
            }
            if (m1CardLoopConfig.getBlockList().length > 0){
                StringBuffer cardStr=new StringBuffer();
                for (int i = 0; i< m1CardLoopConfig.getBlockList().length; i++){

                    byte tempByte= -1 ;

                    try {
                        tempByte=(byte) Integer.parseInt(m1CardLoopConfig.getBlockList()[i]);
                    }catch (NumberFormatException e){

                    }catch (Exception e){

                    }
                    if(tempByte<0){
                        if(m1CardReaderResultListener!=null){
                            m1CardReaderResultListener.onLogInfo("M1读取失败：" +"读卡  块地址出错。");
                            break;
                        }
                    }

                    ret = cardReader.Donsee_M1Read((byte) (tempByte
                            + m1CardLoopConfig.getSector() * 4), resp);//读卡是读块地址（0~63），块地址=当前块号+扇区号*4
                    if (ret >= SUCCESS) {
                        cardStr.append(HexUtil.bytesToHex(resp, 16));
                    }else {
                        if(m1CardReaderResultListener!=null){
                            m1CardReaderResultListener.onLogInfo("M1读取失败：" +"读卡  块："+i);
                            break;
                        }
                    }

                }
                DxM1CardLoopResultBean data=new DxM1CardLoopResultBean();
                data.setUid(uidInfo);
                data.setReadContent(cardStr.toString());
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onJsonInfo(GsonUtils.getGson().toJson(data));
                }

            }else{
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("M1读取失败：" +"没有需要读取的块地址");
                }
                return;
            }
        }

    }

    /**
     *
     * @author xwh
     * Time 2024/11/8
     * Description: 写M1卡
     *
    **/
    public BaseAmpeAppletResultBean<AmpeResultM1CardBean> writeM1Card(M1CardWriteConfig config){
        byte[] uid = new byte[64];
        byte[] resp = new byte[30];
        long ret = 0;
        BaseAmpeAppletResultBean<AmpeResultM1CardBean> resultBean=new BaseAmpeAppletResultBean<>();
        CardReader cardReader=DxSerialportCardReader.getInstance().getCardReader();
        if(cardReader == null){
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("writeM1Card cardReader = null");
            }
            resultBean.setMessage("初始化失败");
            resultBean.setSuccess(false);
            return resultBean;
        }
        if (config == null) {
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("writeM1Card M1写卡失败：" + "配置为空");
            }
            resultBean.setMessage("配置参数有误");
            resultBean.setSuccess(false);
            return resultBean;
        }
        ret = cardReader.Donsee_ReadICUid(uid);
        if (ret < 0) {
            long finalRet = ret;
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("writeM1Card M1写卡失败：" + CardReader.getErrorMessage(finalRet));
            }
            resultBean.setMessage("M1寻卡失败：" + CardReader.getErrorMessage(finalRet));
            resultBean.setSuccess(false);
            return resultBean;
        }else{
            String uidInfo = HexUtil.bytesToHex(uid, 4);
            ret = cardReader.Donsee_M1VerifyPass(config.getKeyMode(),
                    (byte) config.getSector(), HexUtil.hexToBytes(config.getSecretKey()));
            if (ret != SUCCESS) {
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("writeM1Card M1读取失败：" +"秘钥认证失败");
                }
                resultBean.setMessage("秘钥认证失败");
                resultBean.setSuccess(false);
                return resultBean;
            }

            byte tempByte= -1 ;

            try {
                tempByte=(byte) Integer.parseInt(config.getBlock());
            }catch (NumberFormatException e){

            }catch (Exception e){

            }
            if(tempByte<0 || TextUtils.isEmpty(config.getContent())){
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("writeM1Card M1写卡失败：" +"块地址或者写的内容错误");
                    resultBean.setMessage("块地址或者写的内容错误");
                    resultBean.setSuccess(false);
                    return resultBean;
                }
            }

            ret = cardReader.Donsee_M1Write((byte) (tempByte +config.getSector()  * 4), HexUtil.hexToBytes(config.getContent().trim()));
            if (ret == SUCCESS) {
                resultBean.setMessage("成功");
                resultBean.setSuccess(true);
                return resultBean;
            }else {
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("writeM1Card M1写卡失败：" +""+ret);
                }
                resultBean.setMessage("M1写卡失败"+ret);
                resultBean.setSuccess(false);
                return resultBean;
            }

        }
    }


    /**
     *
     * @author xwh
     * Time 2024/11/13
     * Description: M1卡初始值
     *
    **/
    public BaseAmpeAppletResultBean<AmpeResultM1CardBean>  m1CardInitval(M1CardInitvalConfig config){
        byte[] uid = new byte[64];
        byte[] resp = new byte[30];
        long ret = 0;
        BaseAmpeAppletResultBean<AmpeResultM1CardBean> resultBean=new BaseAmpeAppletResultBean<>();
        CardReader cardReader=DxSerialportCardReader.getInstance().getCardReader();
        if(cardReader == null){
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("m1CardInitval cardReader = null");
            }
            resultBean.setMessage("初始化失败");
            resultBean.setSuccess(false);
            return resultBean;
        }
        if (config == null) {
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("m1CardInitval ：" + "配置为空");
            }
            resultBean.setMessage("配置参数有误");
            resultBean.setSuccess(false);
            return resultBean;
        }
        ret = cardReader.Donsee_ReadICUid(uid);
        if (ret < 0) {
            long finalRet = ret;
            if(m1CardReaderResultListener!=null){
                m1CardReaderResultListener.onLogInfo("m1CardInitval M1写卡失败：" + CardReader.getErrorMessage(finalRet));
            }
            resultBean.setMessage("M1寻卡失败：" + CardReader.getErrorMessage(finalRet));
            resultBean.setSuccess(false);
            return resultBean;
        }else{
            String uidInfo = HexUtil.bytesToHex(uid, 4);
            ret = cardReader.Donsee_M1VerifyPass(config.getKeyMode(),
                    (byte)config.getSector(),  HexUtil.hexToBytes(config.getSecretKey()));
            if (ret != SUCCESS) {
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("m1CardInitval " +"秘钥认证失败");
                }
                resultBean.setMessage("秘钥认证失败");
                resultBean.setSuccess(false);
                return resultBean;
            }
            byte tempByte= -1 ;

            try {
                tempByte=(byte) Integer.parseInt(config.getBlock());
            }catch (NumberFormatException e){

            }catch (Exception e){

            }
            if(tempByte < 0 ){
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("m1CardInitval M1初始值失败：" +"  块地址出错");
                }
                resultBean.setMessage("块地址出错");
                resultBean.setSuccess(false);
                return resultBean;
            }
            ret = cardReader.Donsee_M1Initval((byte) (tempByte +config.getSector()  * 4), config.getValue());
            if (ret == SUCCESS) {
                resultBean.setMessage("成功");
                resultBean.setSuccess(true);
                return resultBean;
            }else {
                if(m1CardReaderResultListener!=null){
                    m1CardReaderResultListener.onLogInfo("m1CardInitval M1写卡失败：" +""+ret);
                }
                resultBean.setMessage("M1初始值失败");
                resultBean.setSuccess(false);
                return resultBean;
            }

        }
    }

    /**
     *
     * @author xwh
     * Time 2024/11/7
     * Description: 启动东信读卡器循环读取线程
     * TODO 此线程是一个东线串口读卡器总线程
     **/
    public boolean startRead(){
        if(DxSerialportCardReader.getInstance().isInitSuccessed()) {
            DxSerialportCardReader.getInstance().startRead();
            return true;
        }
        return false;
    }


    /**
     *
     * @author xwh
     * Time 2024/11/7
     * Description: 停止东信读卡器循环读取线程
     * TODO 此线程是一个东线串口读卡器总线程
     *
     **/
    public boolean stopRead(){
        if(DxSerialportCardReader.getInstance().isInitSuccessed()) {
            DxSerialportCardReader.getInstance().stopRead();
            return true;
        }
        return false;
    }

    public void setM1CardReaderResultListener(M1CardReaderResultListener m1CardReaderResultListener) {
        this.m1CardReaderResultListener = m1CardReaderResultListener;
    }

    /**
     *
     * @author xwh
     * Time 2024/11/8
     * Description: 释放支资源
     *
    **/
    public void release() {
        DxSerialportCardReader.getInstance().setReadM1CardListener(null);
        DxSerialportCardReader.getInstance().release();
        instance = null;

    }

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

                    instance = new DxM1CardReader();
                }
            }
        }
        return instance;
    }

    public interface M1CardReaderResultListener {
        //初始化是否成功
        void onInitSuccessState(boolean isSuccess);
        //循环,获取卡片信息
        void onJsonInfo(String info);
        //循环，返回寻卡失败
        void onCardSearchFailed();
        //公共错误信息
        void onLogInfo(String errMsg);


    }

}
