package com.sxyz.rfid;

import android.app.Activity;
import android.content.Context;
import android.device.DeviceManager;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.orhanobut.hawk.Hawk;
import com.sxyz.rfid.greendao.GreenDaoManager;
import com.sxyz.rfid.utils.L;
import com.sxyz.rfid.widgets.MyActivityLifecycle;
import com.ubx.usdk.RFIDSDKManager;
import com.ubx.usdk.rfid.RfidManager;
import com.ubx.usdk.util.SoundTool;

import java.util.LinkedList;
import java.util.List;

public class App extends MultiDexApplication {
    public static App instance;
    public static Context mContext;
    private List<Activity> mActivityList;
    public RfidManager mRfidManager;
    public boolean RFID_INIT_STATUS = false;
    public int readerType = 0;
    public static ScanManager mScanManager;
    public static String ip;
    public static String port;

    public static App getInstance() {
        return instance;
    }

    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mContext = getApplicationContext();
        mActivityList = new LinkedList<>();
        Hawk.init(getApplicationContext()).build();
        ip = Hawk.get(AppConfig.Ip.IP);
        port = Hawk.get(AppConfig.Ip.PORT);
//        initRfid();
        initScan();
        initGreenDao();
        registerActivityLifecycleCallbacks(new MyActivityLifecycle(getContext()));
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.closeScanner();
        mScanManager.switchOutputMode(0);//0： 广播模式   1：键盘模式
        mScanManager.setTriggerMode(Triggering.HOST);
        mScanManager.setPropertyInts(new int[]{PropertyID.SEND_GOOD_READ_BEEP_ENABLE}, new int[]{1});
        //value * 100 ms  ；MIN == 1 ,MAX == 99  设置两个间隔条码的间隔时间，例如传1--> 1*100ms == 100ms;传最大值 99 --> 99*100ms == 9900ms ,即间隔 9900毫秒
//        mScanManager.setPropertyInts(new int[]{PropertyID.TIMEOUT_BETWEEN_SAME_SYMBOL}, new int[]{1});
        //关闭广播模式的声音
//        mScanManager.setPropertyInts(new int[]{PropertyID.SEND_GOOD_READ_BEEP_ENABLE},new int[]{0});
        //关闭键盘模式的声音
//        mScanManager.setParameterInts(new int[]{PropertyID.SEND_GOOD_READ_BEEP_ENABLE},new int[]{0});
//        hostModel();//设置连续扫码或者单次扫码
//        eventKeyEnable523();
//        getHandShankKeyCode();
    }

    /**
     * 单扫模式
     */
    public void hostModel() {
        mScanManager.setTriggerMode(Triggering.HOST);
    }

    /**
     * 连扫模式
     */
    public void continuousModel() {
        mScanManager.setTriggerMode(Triggering.CONTINUOUS);
        String sn = new DeviceManager().getDeviceId();//SN号，唯一
    }

    /**
     * 设置间隔时间
     *
     * @param interval 连续扫码的间隔时间 单位毫秒  范围0~5000ms
     */
    public void setIntervalTime(int interval) {
        int[] idGap = new int[]{0x0a2a, 0x0028};
        int[] idmode = new int[2];
        idmode[0] = interval;//连续间隔 单位毫秒
        idmode[1] = 50;
        mScanManager.setParameterInts(idGap, idmode);
    }

    private void eventKeyEnable523() {
        //TODO 设置触发扫描出光的按钮
        DeviceManager mDeviceManager = new DeviceManager();
        mDeviceManager.setSettingProperty("persist-persist.sys.rfid.key", "0");//新增代码逻辑
        mDeviceManager.setSettingProperty("persist-persist.sys.scan.key", "520-521-522-523-"); //"520-521-522-523-"   520、521、522、523出光
        Log.e("ScanManager", " mDeviceManager.setSettingProperty() ");
    }

    private String getHandShankKeyCode() {
        //TODO 获取触发扫描出光的键值
        DeviceManager mDeviceManager = new DeviceManager();
        String scanKey = mDeviceManager.getSettingProperty("persist-persist.sys.scan.key"); //"520-521-522-523-"   520、521、522、523出光
        if (!TextUtils.isEmpty(scanKey)) {
            //判断是否有523的键值注册，true：有523键值  false：没有
            // 如果没有，可根据业务来进行后续处理，比如判断没有包含523，这时候又需要手柄按键自动触发出光，那么可以调用注册 523 按键值的方法
            boolean contains = scanKey.contains("523");
        }
        return scanKey;
    }

    public void initRfid() {
        SoundTool.getInstance(getApplicationContext());
        // 在异步回调中拿到RFID实例
        RFIDSDKManager.getInstance().power(true);
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean connect = RFIDSDKManager.getInstance().connect();
                if (connect) {
                    L.i("initRfid()  success.");
                    RFID_INIT_STATUS = true;
                    readerType = RFIDSDKManager.getInstance().getRfidManager().getReaderType();//80为短距，其他为长距
                    mRfidManager = RFIDSDKManager.getInstance().getRfidManager();
                    String firmware = RFIDSDKManager.getInstance().getRfidManager().getFirmwareVersion();
                    L.i("initRfid: GetReaderType() = " + readerType);
                } else {
                    L.i("initRfid  fail.");
                }
            }
        }, 1500);
    }


    public void addActivity(Activity activity) {
        // 判断当前集合中不存在该Activity
        if (!mActivityList.contains(activity)) {
            mActivityList.add(activity);//把当前Activity添加到集合中
        }
    }

    /**
     * @description 销毁单个Activity
     * @author wuchunyuan
     * @time 2020/7/10 10:01
     */
    public void removeActivity(Activity activity) {
        if (mActivityList.contains(activity)) {//判断当前集合中存在该Activity
            mActivityList.remove(activity);//从集合中移除
            activity.finish();//销毁当前Activity
        }
    }

    public void exit() {
        try {
            for (Activity activity : mActivityList) {
                if (activity != null) activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    /**
     * @description 获取activity是否存在
     * @author wuchunyuan
     * @time 2020/7/10 10:01
     */
    public boolean currentActivity(Class<?> cls) {
        for (Activity activity : mActivityList) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 初始化GreenDao,直接在Application中进行初始化操作
     */
    private void initGreenDao() {
        GreenDaoManager.getInstance().init(this);
    }

}
