package com.device.comm.mylibrary;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;

import com.device.comm.DGMS.algorithm.Algorithm20;
import com.device.comm.mylibrary.NativeDevice.BleDGType2Device;
import com.device.comm.mylibrary.NativeDevice.BleDynamicGlucose;
import com.device.comm.mylibrary.NativeDevice.BleNativeAccuGlucoseDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeBeneCheckerDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeBioLandGlucoseDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeRBPDeviceCallback;
import com.device.comm.mylibrary.NativeDevice.BleNativeYASEE163EBBPDevice;
import com.device.comm.mylibrary.NativeDevice.cgmadi.bean.RequestBean;
import com.device.comm.mylibrary.NativeDevice.cgmadi.constants.Command;
import com.device.comm.mylibrary.NativeDevice.cgmadi.enums.OBJCode;
import com.device.comm.mylibrary.NativeDevice.cgmadi.enums.OPCode;
import com.device.comm.mylibrary.NativeDevice.cgmadi.util.DataFormatUtil;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.device.comm.mylibrary.NativeDevice.BleNativeEnuoBPDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeEnuoGlucoseDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeHMDGlucoseDevice;
import com.device.comm.mylibrary.NativeDevice.GlucoseData;
import com.device.comm.mylibrary.NativeDevice.InvsIdCard;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lvwang2002 on 16/8/8.
 * 20161020 13:27
 * 20161021 13:55 增加支持PDA二维码扫描 赵然
 * 20161021 14:45 修改二维码消息 赵然
 * 20161021 15:44 修改超时的bug 赵然
 * 20161021 18:14 把上传列表和打开/关闭扫描解除绑定 赵然
 * 20161023 16:05 5秒后再次断开一次连接  赵然
 * 20161109 20:38 增加身份证读卡器的断开消息  赵然
 * 20161110 12:07 改进身份证读卡器断开消息发送 赵然
 * 20161216 13:18 增加全局扫描方法 赵然
 * 20161221 11:59 1.修改断开崩溃的的问题 2.修改断开血糖，身份证读卡器被断开。 赵然
 * 20161221 17:41 血糖连接的时候停止扫描3秒钟。 赵然
 * 20161222 11:56 增加查找服务超时断开连接功能 赵然
 * 20170110 14:49 去掉 血糖连接的时候停止扫描3秒钟。 赵然
 * 20170119 16:55 增加对攀高血压计的支持
 * 20170120 13:19 1.修改bugs 2.获取所有连接的血压设备
 * 20170205 20:54 增加血压的public 赵然
 * 20170208 10:59 增加过程中电量报警 赵然
 * 20170209 10:34 修改低电报警错误 赵然
 * 20170227 16:33 增加血压关机消息 赵然
 * 20170302 10:55 修改自动启动血压计测量
 * 20170315 14:38 动态血糖 201703151438
 * 20170401 12:08 增加同时搜索血糖仪和动态血糖仪的方法
 * 20170412 10:13 修改updateList没有生成NativeDevice的时候崩溃的问题
 * 20170417 14:11 增加动态血糖连接前的延迟500ms
 * 20170613 10:55 增加对G系列血糖仪的支持
 * 20170618 13:53 1.异常大数据屏蔽 2.按照时间戳屏蔽重复数据
 * 20170618 15:25 修改2的问题
 * 20170627 14:24 修改g3400四舍五入问题
 * 20170717 11:26 增加对血酮的支持
 * 20171114 16:20 增加对动态血糖新版的支持
 * 20171203 23:11 支持艾奥乐血糖仪
 * 20171213 16:40 修改艾奥乐血糖仪
 * 20171218 18:00 修改艾奥乐血糖仪上传模式为被动模式
 * 20171229 17:52 增加对尿酸支持
 * 20180102 13:44 增加获取所有尿酸设备
 * 20180105 11:47 1.修改艾奥乐血糖不断开的问题 2.修改尿酸显示的位数
 * 20180118 14:21 修改尿酸显示位数不正确问题
 * 20180513 17:16 支持beneCheck血糖
 * 20180521 15:30 修改尿酸单位
 * 20180529 16:55 修改尿酸位数
 * 20180709 15:33 增加对雅思血压计的支持
 * 20180709 16:39 过滤雅思血压计重复数据
 * 20180710 10:40 雅思血压计连接成功消息发送
 * 20180710 13:42 获取已经连接血压计支持雅思
 * 20180710 15:03 fix bug
 * 20180808 10:39 增加对厚美德一体机的支持
 * 20180810 11:20 厚美德一体机拔条消息和单位
 * 20180830 14:50 1.修改厚美德一体机单位 2.解决攀高血压计不能测试的问题
 * 20180831 15:56 解决攀高血压计不能测试的问题
 * 20180930 14:20 重新激活雅思血压计
 * 20181109 14:20 激活带圆角矩形动态血糖
 * 20181222 13:44 增加动态血糖计算升降
 * 20190114 16:09 支持罗氏血糖仪
 * 20190117 14:36 修改罗氏血糖仪问题
 * 20190226 14:39 获取动态血糖电压
 * 20190311 16:02 修改动态血糖崩溃问题
 * 20190314 13:55 孙建伟合并
 * 20190516 18：00 美琪最新算法 IOSG400 IOS支持雷兰
 * 20190524 10:07 iOS雷兰持续读数bug
 * 20190527 17.40 iOS雷兰与G400同时连接Bug
 * 20190604 10：00 android端将美琪血糖仪底层收数据记录
 * 20190610 14：00 sendData 加入trycatch
 * 20190802 14：13 百捷设备四舍五入
 * 20190820 12:00 血糖一体机加入读取code相关
 * 20190829 5:14 将美琪 o0改为 o
 */
public class RNMethodModule  extends ReactContextBaseJavaModule  implements BleDeviceManager.UpdateDeviceListCallback,BleDeviceManager.BTStatusCallback{

    private Activity _activity = null;
    private String TAG = "RN_Android";
    private ReactApplicationContext mReactContext;

    public  KOJNativeEventManager mEventManager;

    BTCSFZReaderDevice mReaderDevice;
    @Override
    public String getName() {
        return "RNMethodModule";
    }

    private boolean mIsUpdateDeviceList = false;
    public RNMethodModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mReactContext = reactContext;

        IntentFilter scanDataIntentFilter = new IntentFilter();
        scanDataIntentFilter.addAction("com.android.scancontext");         //前台输出
        scanDataIntentFilter.addAction("com.android.scanservice.scancontext"); //后台输出

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mReactContext.registerReceiver(mScanDataReceiver, scanDataIntentFilter,Context.RECEIVER_NOT_EXPORTED);
      }else{
        mReactContext.registerReceiver(mScanDataReceiver, scanDataIntentFilter);
      }

      mEventManager = new KOJNativeEventManager(reactContext);
        BleDeviceManager.get(mReactContext).setUpdateDeviceListCallback(this);
        BleDeviceManager.get(mReactContext).setStatusCallback(this);
        BleDeviceManager.get(mReactContext).showLog(false);
    }

    //update device callback
    synchronized public void onUpdateDeviceList(ArrayList<BleDevice> devices){
        if(!mIsUpdateDeviceList){
            return;
        }
        RNLog.d(TAG,"device list:"+devices.size());
        WritableArray tempDevices = Arguments.createArray();
        for(int i=0,length=devices.size();i<length;i++){
            BleDevice device = devices.get(i);
            if(device.getNativeDevice() == null){
                continue;
            }
            WritableMap map = Arguments.createMap();
            if(device.getMacAddress().startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC)){
                map.putString("deviceName", "Glucose");
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatus","Connected"); //Discovered, Connecting, Connected, Disconnect, ConnectFailed;
                map.putString("connectedStatus","Connected");
                map.putString("deviceDisplayName","雅思血糖仪");
            }else{
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatus",device.getDeviceState()+""); //Discovered, Connecting, Connected, Disconnect, ConnectFailed;
                map.putString("connectedStatus",device.getNativeDevice().getConnectedStatus());
                map.putString("deviceDisplayName",device.getNativeDevice().getDeviceDisplayName());
            }


            tempDevices.pushMap(map);
        }
//        RNLog.d(TAG,"update device list:"+tempDevices);
        mEventManager.sendCustomEvent("UPDATE_DEVICE_LIST",tempDevices);
    }


    @ReactMethod
    synchronized public void startUpdateDeviceList(){
        mIsUpdateDeviceList = true;
    }

    @ReactMethod
    synchronized public void stopUpdateDeviceList(){
        mIsUpdateDeviceList = false;
    }

    @ReactMethod
    synchronized public void forceUpdateDeviceList(){
        BleDeviceManager.get(mReactContext).postUpdateDeviceList();
    }

    @ReactMethod
    synchronized public void showLog(boolean isShow){
//        BleDeviceManager.get(mReactContext).showLog(isShow);
    }


    @ReactMethod
    synchronized public void startCardReaderScan(final Promise promise){
        new Thread(){
            public void run() {
                BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_CARD_READER);
                BleDeviceManager.get(mReactContext).enableBleScan();
                // 设备已经连接上,跳转界面

                // 连接血糖设备状态
                BleDeviceManager.get(mReactContext).setDiscoverListener( new BleDeviceManager.DiscoverListener() {
                    @Override
                    public void onEvent(BleDeviceManager.DiscoverEvent e) {

                        BleDevice device = e.getDevice();

                        if(!device.getDeviceName().startsWith("INVS300")){
                            return;
                        }


                        try{
                            Thread.sleep(200);
                        }catch (InterruptedException error){
                            error.printStackTrace();
                        }

                        // 设备进行连接
//                BLE_conn_state = Cons.BLE_STATE_CONNINT;
//                getBLEStateString(BLE_conn_state);

                        BleDeviceManager.get(null).disableBleScan();
                        mReaderDevice = (BTCSFZReaderDevice)device;
                        mReaderDevice.setDeviceCallback(new BTCSFZReaderDevice.BTCSFZReaderDeviceCallback() {
                            @Override
                            public void onConnect(BleDevice device) {

                            }

                            @Override
                            public void onDisconnect(BleDevice device) {
                                WritableMap info = Arguments.createMap();
                                info.putString("deviceName", device.getDeviceName());
                                info.putString("deviceMac",device.getMacAddress());
                                info.putString("deviceStatus","disconnect");

                                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
                            }

                            @Override
                            public void onBonded(BleDevice device){

                            }

                            @Override
                            public void onResult(BleDevice device, InvsIdCard card) {

                            }

                            @Override
                            public void onError(BleDevice device, String error) {

                            }

                            @Override
                            public void onGetServices(BleDevice device) {

                            }

                            @Override
                            public void onConnectError(BleDevice device, String error) {

                            }
                        });

                        mReaderDevice.tryConnect();
                        if(mReaderDevice.getDeviceState() == BleDevice.DeviceConnectState.Connected){
                            promise.resolve("connected");
                        }else{
                            promise.reject("400","error");
                        }

                    }
                });
            }
        }.start();
    }

    @ReactMethod
    synchronized public void connectCardReader(final String deviceMac, final Promise promise) {
        new Thread(){
            public void run(){
                BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
                if(device==null){
                    promise.reject("400","no device");
                    return;
                }

                if(!device.getDeviceName().startsWith("INVS300")){
                    promise.reject("400","no device");
                    return;
                }

                try{
                    Thread.sleep(200);
                }catch (InterruptedException error){
                    error.printStackTrace();
                }

                // 设备进行连接
//                BLE_conn_state = Cons.BLE_STATE_CONNINT;
//                getBLEStateString(BLE_conn_state);

                BleDeviceManager.get(null).disableBleScan();
                mReaderDevice = (BTCSFZReaderDevice)device;
                mReaderDevice.setDeviceCallback(new BTCSFZReaderDevice.BTCSFZReaderDeviceCallback() {
                    @Override
                    public void onConnect(BleDevice device) {

                    }

                    @Override
                    public void onBonded(BleDevice device){

                    }

                    @Override
                    public void onDisconnect(BleDevice device) {
                        WritableMap info = Arguments.createMap();
                        info.putString("deviceName", device.getDeviceName());
                        info.putString("deviceMac",device.getMacAddress());
                        info.putString("deviceStatus","disconnect");

                        mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
                    }

                    @Override
                    public void onResult(BleDevice device, InvsIdCard card) {

                    }

                    @Override
                    public void onError(BleDevice device, String error) {

                    }

                    @Override
                    public void onGetServices(BleDevice device) {

                    }

                    @Override
                    public void onConnectError(BleDevice device, String error) {

                    }
                });

                mReaderDevice.tryConnect();
                BleDeviceManager.get(null).enableBleScan();
                if(mReaderDevice.getDeviceState() == BleDevice.DeviceConnectState.Connected){
                    promise.resolve("connected");
                }else{
                    promise.reject("400","error");
                }
            }
        }.start();

    }


    @ReactMethod
    synchronized public void stopCardReaderScan(Promise promise){
        BleDeviceManager.get(mReactContext).disableBleScan();
        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
        BTCSFZReaderDevice readerDevice  = null;
        ArrayList<BleDevice> listOfDevices = BleDeviceManager.get(null).getDevices();
        for(int i=0,j=listOfDevices.size();i<j;i++){
            BleDevice device = BleDeviceManager.get(null).getDevices().get(i);
            if(device.getDeviceName().startsWith("INVS300")){
                readerDevice = (BTCSFZReaderDevice)device;
                break;
            }
        }

        if(readerDevice == null){
            Log.i(TAG,"no reader device");
            if(promise == null) return;

            promise.reject("400","no device");
            return;
        }

        readerDevice.setDeviceCallback(null);
        readerDevice.disconnect();

        if(promise == null) return;
        promise.resolve("disconnect");

    }

    @ReactMethod
    synchronized public void readCard(final Promise promise){
        new Thread(){
            public void run(){
                BTCSFZReaderDevice readerDevice  = null;
                ArrayList<BleDevice> listOfDevices = BleDeviceManager.get(null).getDevices();
                for(int i=0,j=listOfDevices.size();i<j;i++){
                    BleDevice device = BleDeviceManager.get(null).getDevices().get(i);
                    if(device.getDeviceName().startsWith("INVS300")){
                        readerDevice = (BTCSFZReaderDevice)device;
                        break;
                    }
                }


                if(readerDevice == null){
                    Log.i(TAG,"no reader device");
                    if(promise == null){
                        return;
                    }
                    promise.reject("400","no device");
                    return;
                }

                InvsIdCard card  = mReaderDevice.readCard();
                if(card == null){
                    Log.i(TAG,"得到的数据为空");
                    if(promise == null){
                        return;
                    }
                    promise.reject("400","no data");
                    return;
                }

                Log.i(TAG,""+card.getName()+card.getAddress()+card.getBirth());
                WritableMap map = Arguments.createMap();
                map.putString("name",card.getName());
                map.putString("address",card.getAddress());
                map.putString("birth",card.getBirth());
                map.putString("end",card.getEnd());
                map.putString("idNo",card.getIdNo());
                map.putString("nation",card.getNation());
                map.putString("police",card.getPolice());
                map.putString("sex",card.getSex());
                map.putString("start",card.getStart());


                promise.resolve(map);
            }
        }.start();
    }

    //开启扫描血糖设备.
    @ReactMethod
    synchronized public void startScanGlucose(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_BLOOD_GLUCOSE);
        BleDeviceManager.get(mReactContext).enableBleScan();

        Log.i(TAG,"开启启动设备");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
//               Log.d(TAG,"通过E发现设备");
                if(!e.isNewlyDiscovered()){
//               Log.d(TAG,"改设备已经被发现过");
                    return;
                }

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_BT_DEVICE",map);
            }
        });
    }

    @ReactMethod
    synchronized public void startScanDevice(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_ALL);
        BleDeviceManager.get(mReactContext).enableBleScan();

        Log.i(TAG,"开启启动设备");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
//               Log.d(TAG,"通过E发现设备");
                if(!e.isNewlyDiscovered()){
//               Log.d(TAG,"改设备已经被发现过");
                    return;
                }

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_ALL_BT_DEVICE",map);
            }
        });
    }

    @ReactMethod
    synchronized public void stopScanDevice(){
        BleDeviceManager.get(mReactContext).disableBleScan();
        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }


    @ReactMethod
    synchronized public void stopScanGlucose(){
        BleDeviceManager.get(mReactContext).disableBleScan();
        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }

    @ReactMethod
    synchronized public void disconnectGlucose(String deviceMac){
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);

        if(device == null){
            //没有找到设备,直接返回
            return;
        }

        device.disconnect();
    }

    @ReactMethod
    synchronized public void connectSingleDevice(String deviceMac){
        ArrayList<BleDevice> devices = (ArrayList<BleDevice>)BleDeviceManager.get(mReactContext).getDevices().clone();

        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
        if(device == null){
            Log.i(TAG,"no device");

            WritableMap map = Arguments.createMap();
            map.putString("deviceName", "no device");
            map.putString("deviceMac",deviceMac);
            map.putString("deviceStatusDescription","连接失败");
            map.putString("deviceStatus","connectError");
            mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);

            return;
        }

//        BleDeviceManager.get(null).disableBleScan();
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                BleDeviceManager.get(null).enableBleScan();
//            }
//        },3000);

        device.connect(new BleDevice.BleDeviceCallback() {
            @Override
            public void onConnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","connect");

            }
            @Override
            public void onBonded(BleDevice device){
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","bounded");

                mEventManager.sendCustomEvent("BOUNDED_BT_DEVICE",info);
            }

            @Override
            public void onDisconnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","disconnect");

                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
            }

            @Override
            public void onGetServices(BleDevice device) {
                String deviceName = device.getDeviceName();

                if (deviceName.startsWith("BLE-") || deviceName.startsWith("ENUO_")) {
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
//                    promise.resolve(map);
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);


                    device.setNativeDeviceCallback(new BleNativeEnuoGlucoseDevice.BleNativeEnuoGlucoseDeviceCallback() {
                        @Override
                        public void onResult(BleDevice device, GlucoseData data) {
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                            String curDateString = formatter.format(curDate);
                            String result = data.getYear() + "年" + data.getMonth() + "月" + data.getDay() + "日" + data.getHour() + "时" + data.getMinute() + "分" + "\n 结果："
                                    + new BigDecimal((float) (data.getGlucose() / 18.0) + 0.05).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue() + "指示：" + data.getFlagValue();

//                            Log.d(TAG,"time:"+dateString+"\n血糖值:"+result+"");
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
                            String dateString = data.getYear() + "-" + data.getMonth() + "-" + data.getDay() + " " + data.getHour() + "-" + data.getMinute();
                            Date deviceDate;
                            String deviceTime;
                            try {
                                deviceDate = dateFormat.parse(dateString);
                                deviceTime = deviceDate.getTime() + "";
                            } catch (Exception exception) {
                                deviceTime = "" + 0;
                            }

                            String displayValue;
                            String resultType = "";
                            if (data.getFlagValue() >= 4096) {
                                displayValue = getKetoneData(data.getGlucose()) + "";
                                resultType = "ketone";
                            } else {
                                displayValue = getXueTangData(data.getGlucose()) + "";
                                resultType = "glucose";
                            }


                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac", device.getMacAddress());
                            map.putString("deviceStatusDescription", "测量成功");
                            map.putString("resultType", resultType);
                            map.putString("deviceStatus", "result");
                            map.putString("time", curDateString);
                            map.putString("deviceTime", deviceTime);
                            map.putString("value", "" + data.getGlucose());
                            map.putString("displayValue", "" + displayValue);

                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
                        }
                    });
                } else if (deviceName.startsWith("Glucose")) {
                    Log.d(TAG, "血糖" + deviceName);
                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
//                    promise.resolve(map);
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);


                    device.setNativeDeviceCallback(new BleNativeHMDGlucoseDevice.BleNativeHMDGlucoseDeviceCallback() {
                        @Override
                        public void onResult(BleDevice device, double data) {
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                            String dateString = formatter.format(curDate);

                            Log.d(TAG, "time:" + dateString + "\n血糖值:" + data + "");
                            String displayValue = new BigDecimal(data).setScale(1, RoundingMode.HALF_UP).toString();


                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac", device.getMacAddress());
                            map.putString("deviceStatusDescription", "测量成功");
                            map.putString("deviceStatus", "result");
                            map.putString("resultType", "glucose");

                            map.putString("time", dateString);
                            map.putString("value", "" + data);
                            map.putString("displayValue", "" + displayValue);

                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
                        }

                        @Override
                        public void onSerialNumber(BleDevice device, String serialNumber) {
                            Log.i(TAG, "设备编号:" + serialNumber);
                        }
                    });
                } else if (deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_G_GLUCOSE)) {
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");

//                    promise.resolve(map);
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);


                    device.setNativeDeviceCallback(new BleNativeEnuoGlucoseDevice.BleNativeEnuoGlucoseDeviceCallback() {
                        @Override
                        public void onResult(BleDevice device, GlucoseData data) {
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                            String curDateString = formatter.format(curDate);

                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                            String dateString = data.getYear() + "-" + data.getMonth() + "-" + data.getDay() + " " + data.getHour() + "-" + data.getMinute() + "-" + data.getSecond();
                            Date deviceDate;
                            String deviceTime;
                            try {
                                deviceDate = dateFormat.parse(dateString);
                                deviceTime = deviceDate.getTime() + "";
                            } catch (Exception exception) {
                                deviceTime = "" + 0;
                            }


                            String displayValue = new BigDecimal((data.getGlucose() * 0.055) + 0.0001).setScale(1, RoundingMode.HALF_UP).toString();
//                            Log.d(TAG,"value:"+data.getGlucose()+"");
//                            Log.d(TAG," display"+displayValue);


                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac", device.getMacAddress());
                            map.putString("deviceStatusDescription", "测量成功");
                            map.putString("deviceStatus", "result");
                            map.putString("time", curDateString);
                            map.putString("deviceTime", deviceTime);
                            map.putString("value", "" + data.getGlucose());
                            map.putString("displayValue", "" + displayValue);
                            map.putString("resultType", "glucose");


                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
                        }
                    });
                } else if (deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_BIOLAND_GLUCOSE)) {
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);


                    device.setNativeDeviceCallback(new BleNativeBioLandGlucoseDevice.BleNativeGlucoseDeviceCallback() {
                        @Override
                        public void onResult(BleDevice device, GlucoseData data, String displayValue) {
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                            String curDateString = formatter.format(curDate);

                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                            String dateString = data.getYear() + "-" + data.getMonth() + "-" + data.getDay() + " " + data.getHour() + "-" + data.getMinute() + "-" + data.getSecond();
                            Date deviceDate;
                            String deviceTime;
                            try {
                                deviceDate = dateFormat.parse(dateString);
                                deviceTime = deviceDate.getTime() + "";
                            } catch (Exception exception) {
                                deviceTime = "" + 0;
                            }


                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac", device.getMacAddress());
                            map.putString("deviceStatusDescription", "测量成功");
                            map.putString("deviceStatus", "result");
                            map.putString("time", curDateString);
                            map.putString("deviceTime", deviceTime);
                            map.putString("value", "" + data.getGlucose());
                            map.putString("displayValue", "" + displayValue);
                            map.putString("resultType", "glucose");
                            RNLog.d(TAG, "glucose info:" + map);

                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
                        }
                    });
                } else if (deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_BENE_CHECKER)) {
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);

                    device.setNativeDeviceCallback(new BleNativeBeneCheckerDevice.BleNativeBeneCheckerCallback() {
                        @Override
                        public void onResult(BleDevice device, GlucoseData data, String type) {
                            SimpleDateFormat formatter =   new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                            Date curDate =  new Date(System.currentTimeMillis());//获取当前时间
                            String curDateString =  formatter.format(curDate);
//                            String result = data.getYear() +"年"+ data.getMonth() +"月"+ data.getDay() + "日" + data.getHour() + "时" + data.getMinute() + "分" +"\n 结果："
//                                    + new BigDecimal((float)(data.getGlucose()/168.1) + 0.05).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue() + "指示：" + data.getFlagValue();

//                            Log.d(TAG,"time:"+dateString+"\n血糖值:"+result+"");
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
                            String dateString  = data.getYear()+"-"+data.getMonth()+"-"+data.getDay()+" "+data.getHour()+"-"+data.getMinute();
                            Date deviceDate;
                            String deviceTime;
                            try{
                                deviceDate = dateFormat.parse(dateString);
                                deviceTime =deviceDate.getTime()+"";
                            }catch (Exception exception){
                                deviceTime = ""+0;
                            }
                          //  Log.d("zll11111", "onResult: "+new BigDecimal((float)(data.getGlucose()/18.0)).toString()+"原始值："+data.getGlucose());

                            String displayValue = new BigDecimal((float)(data.getGlucose()/18.0)).setScale(1,BigDecimal.ROUND_HALF_UP).toString();



                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac",device.getMacAddress());
                            map.putString("deviceStatusDescription","测量成功");
                            map.putString("resultType",type);
                            map.putString("deviceStatus","result");
                            map.putString("time",curDateString);
                            map.putString("deviceTime",deviceTime);
                            map.putString("value",""+data.getGlucose());
                            map.putString("displayValue",""+displayValue);

                            RNLog.d(TAG,map.toString());

                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
                        }
                    });

                }else if(deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_ACCU_CHEK)){
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);
                    device.setNativeDeviceCallback(new BleNativeAccuGlucoseDevice.BleNativeAccuGlucoseDeviceCallback(){
                        @Override
                        public void onResult(BleDevice device, GlucoseData data) {

                        }
                    });
                }else if(deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_TD_GLUCOSE)){
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
//                    promise.resolve(map);
                    mEventManager.sendCustomEvent("" +
                            "", map);
                }
            }

            @Override
            public void onConnectError(BleDevice device, String error) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","连接失败");
                map.putString("deviceStatus","connectError");

                mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);
            }
        });


        for(int i=0,length= devices.size();i<length;i++){
            BleDevice myDevice = devices.get(i);
            if(!myDevice.getMacAddress().startsWith(deviceMac) &&
                (myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_AIKE_GLUCOSE) ||
                myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_HMD_GLUCOSE) ||
                myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_G_GLUCOSE) ||
                myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_BIOLAND_GLUCOSE))){

                myDevice.forceDisconnect();
            }
        }
    }

    @ReactMethod
    synchronized public void getConnectedGlucose(Promise promise){
        ArrayList<BleDevice> devices  = (ArrayList<BleDevice>)BleDeviceManager.get(mReactContext).getDevices().clone();
        WritableArray glucoseDevices = Arguments.createArray();
        for(int i=0,length=devices.size();i<length;i++){
            BleDevice device = devices.get(i);
            if(device.getMacAddress().startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_UART_GLUCOSE_MAC)){
                continue;
            }

            if(!((device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_HMD_GLUCOSE) ||
                    device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_AIKE_GLUCOSE)))){
                continue;
            }


            BleDevice.DeviceConnectState state = device.getDeviceState();
            if(state != BleDevice.DeviceConnectState.Connected && state != BleDevice.DeviceConnectState.Connecting ){
                continue;
            }


            WritableMap info = Arguments.createMap();
            info.putString("deviceName", device.getDeviceName());
            info.putString("deviceMac",device.getMacAddress());
            glucoseDevices.pushMap(info);
        }

        promise.resolve(glucoseDevices);
    }

    @ReactMethod
    public void autoConnectAccu(String deviceMac){
        BleDevice device = BleDeviceManager.get(mReactContext).addAutoConnectDevice(ENDeviceConst.DEVICE_TYPE_ACCU_CHEK);
        device.autoConnect(new BleDevice.BleDeviceCallback() {
            @Override
            public void onConnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","connect");

            }
            @Override
            public void onBonded(BleDevice device){
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","bounded");

                mEventManager.sendCustomEvent("BOUNDED_BT_DEVICE",info);
            }

            @Override
            public void onDisconnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","disconnect");

                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
            }

            @Override
            public void onGetServices(BleDevice device) {
                String deviceName = device.getDeviceName();

                if(deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_ACCU_CHEK)){
                    Log.d(TAG, "血糖" + deviceName);

                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);
                    device.setNativeDeviceCallback(new BleNativeAccuGlucoseDevice.BleNativeAccuGlucoseDeviceCallback(){
                        @Override
                        public void onResult(BleDevice device, GlucoseData data) {
                            WritableMap map = Arguments.createMap();
                            map.putString("deviceName", device.getDeviceName());
                            map.putString("deviceMac",device.getMacAddress());
                            map.putString("deviceStatusDescription","测量成功");
                            map.putString("deviceStatus","result");
                            map.putString("value",""+data.getGlucose());
                            map.putString("displayValue",""+(data.getGlucose()/10.0)+"");

                            RNLog.d(TAG,map.toString());

                            mEventManager.sendCustomEvent("RESULT_BT_DEVICE", map);
//                            device.disconnect();
                        }
                    });
                }
            }

            @Override
            public void onConnectError(BleDevice device, String error) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","连接失败");
                map.putString("deviceStatus","connectError");

                mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);
            }
        });



    }


    /** 开始扫描血压 */
    @ReactMethod
    public void startScanBP(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_BLOOD_PRESSURE);
        BleDeviceManager.get(mReactContext).enableBleScan();

        Log.i(TAG,"开启启动设备");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
                if(!e.isNewlyDiscovered()){
                    return;
                }

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_BP_BT_DEVICE",map);
            }
        });
    }

    /** 停止扫描血压 */
    @ReactMethod
    public void stopScanBP(){
        BleDeviceManager.get(mReactContext).disableBleScan();
        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }


    /** 连接单个血压计 */
    @ReactMethod
    public void connectSingleBPDevice(String deviceMac){
        ArrayList<BleDevice> devices = (ArrayList<BleDevice>)BleDeviceManager.get(mReactContext).getDevices().clone();
        RNLog.d(TAG,"start connect");
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
        if(device == null){
            Log.i(TAG,"no device");

            WritableMap map = Arguments.createMap();
            map.putString("deviceName", "no device");
            map.putString("deviceMac",deviceMac);
            map.putString("deviceStatusDescription","连接失败");
            map.putString("deviceStatus","connectError");
            mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);

            return;
        }

        RNLog.d(TAG,"start connecting");
        device.connect(new BleDevice.BleDeviceCallback() {
            @Override
            public void onConnect(BleDevice device) {
                // WritableMap info = Arguments.createMap();
                // info.putString("deviceName", device.getDeviceName());
                // info.putString("deviceMac",device.getMacAddress());
                // info.putString("deviceStatus","connect");

            }
            @Override
            public void onBonded(BleDevice device){

            }

            @Override
            public void onDisconnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","disconnect");

                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
            }

            @Override
            public void onGetServices(BleDevice device) {
                String deviceName = device.getDeviceName();

                //目前只有雅思的血压计需要在这里发送链接成功
                if(deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_BP) ||
                    deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_JN163_BP)){
                    WritableMap map = Arguments.createMap();
                    map.putString("deviceName", device.getDeviceName());
                    map.putString("deviceMac", device.getMacAddress());
                    map.putString("deviceStatusDescription", "连接成功");
                    map.putString("deviceStatus", "connectSuc");
                    mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE", map);
                }

//                if(deviceName.startsWith("ClinkBlood")){
                if(deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_CLINK_BP) ||
                    deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_BP) ||
                        deviceName.startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_JN163_BP)
                ){

                    Log.d(TAG,"血压"+deviceName);
                    device.setNativeDeviceCallback(new BleNativeRBPDeviceCallback() {
                               @Override
                               public void onResult(BleDevice device,Map<String, String> result) {

                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","测量成功");
                                   map.putString("deviceStatus","result");

                                   map.putString("pul",result.get("pul"));
                                   map.putString("dia",result.get("dia"));
                                   map.putString("sys",result.get("sys"));

//                                eventManager.sendCustomEvent("RESULT_BT_DEVICE",map);
                                   mEventManager.sendCustomEvent("RESULT_BP_BT_DEVICE",map);

                               }

                               @Override
                               public void onProgressStatus(BleDevice device,BleNativeEnuoBPDevice.BPStatus status) {
//
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","测量过程");
                                   map.putString("deviceStatus","receivingData");



                                   mEventManager.sendCustomEvent("START_RECEIVING_DATA_BP_BT_DEVICE",map);

                               }

                               @Override
                               public void onProgressValue(BleDevice device,Map<String, String> value) {
//
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","测量过程");
                                   map.putString("deviceStatus","receivingData");

                                   map.putString("value",""+value.get("value"));

                                   mEventManager.sendCustomEvent("RECEIVING_DATA_BP_BT_DEVICE",map);

                               }

                               @Override
                               public void onError(BleDevice device,Map<String,String>error){
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription",error.get("error"));
                                   map.putString("errorDescription",error.get("error"));
                                   map.putString("errorCode",error.get("errorCode"));
                                   map.putString("deviceStatus","BPDeviceError");
                                   mEventManager.sendCustomEvent("BP_DEVICE_ERROR",map);
                               }

                               @Override
                               public  void onStartTest(BleDevice device){
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   mEventManager.sendCustomEvent("BP_START_TEST",map);
                               }

                               @Override
                               public void onStopTest(BleDevice device){

                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   mEventManager.sendCustomEvent("BP_STOP_TEST",map);
                               }

                               @Override
                               public void onStopZero(BleDevice device){
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   mEventManager.sendCustomEvent("BP_STOP_ZERO",map);
                               }


                               @Override
                               public void onPower(BleDevice device,int power){
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   map.putString("value",""+power);
                                   mEventManager.sendCustomEvent("BP_POWER",map);
                               }

                               @Override
                               public void onDeviceShutDown(BleDevice device){
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   mEventManager.sendCustomEvent("DEVICE_SHUT_DOWN",map);
                               }

                               @Override
                               public void onCheckConnectFinish(BleDevice device,boolean isSuc){
                                   if(!isSuc){
                                       return;
                                   }

                                   //攀高的血压计需要在这里发送
                                   WritableMap map = Arguments.createMap();
                                   map.putString("deviceName", device.getDeviceName());
                                   map.putString("deviceMac",device.getMacAddress());
                                   map.putString("deviceStatusDescription","连接成功");
                                   map.putString("deviceStatus","connectSuc");
                                   mEventManager.sendCustomEvent("CONNECTED_BT_DEVICE",map);
                               }

                                               }
                    );
                }

            }

            @Override
            public void onConnectError(BleDevice device, String error) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","连接失败");
                map.putString("deviceStatus","connectError");

                mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);
            }
        });


        for(int i=0,length= devices.size();i<length;i++){
            BleDevice myDevice = devices.get(i);

            try{
                if(!myDevice.getMacAddress().startsWith(deviceMac) &&
                        (myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_CLINK_BP) ||
                                myDevice.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_RBP))){

                    myDevice.forceDisconnect();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    /** 开始测量血压 */
    @ReactMethod
    public void startTestBP(String mac){
        BleDeviceManager _deviceManager = BleDeviceManager.get(mReactContext);
        BleDevice device =  _deviceManager.getDevice(mac);

        if(device == null){
            Log.i(TAG,"获取不到指定的设备");
            return;
        }
//        BleNativeEnuoBPDevice nativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
        BleNativeDevice nativeDevice = device.getNativeDevice();
        if(nativeDevice.getDeviceType().equals(ENDeviceConst.DEVICE_TYPE_YASEE_JN163_BP)){
            BleNativeYASEE163EBBPDevice myNativeDevice = (BleNativeYASEE163EBBPDevice) device.getNativeDevice();
            myNativeDevice.sendStartTest();
        }else{
            BleNativeEnuoBPDevice myNativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
            myNativeDevice.sendStartTest();
        }
    }

    /** 停止测量血压 */
    @ReactMethod
    public void stopTestBP(String mac){
        BleDeviceManager _deviceManager = BleDeviceManager.get(mReactContext);
        BleDevice device =  _deviceManager.getDevice(mac);

        if(device == null){
            Log.i(TAG,"获取不到指定的设备");
            return;
        }
//        BleNativeEnuoBPDevice nativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
        BleNativeDevice nativeDevice = device.getNativeDevice();
        if(nativeDevice.getDeviceType().equals(ENDeviceConst.DEVICE_TYPE_YASEE_JN163_BP)){
            BleNativeYASEE163EBBPDevice myNativeDevice = (BleNativeYASEE163EBBPDevice) device.getNativeDevice();
            myNativeDevice.sendStopTest();
        }else{
            BleNativeEnuoBPDevice myNativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
            myNativeDevice.sendStopTest();
        }

    }

    /** 得到血压计电量 */
    @ReactMethod
    public void getBPBatteryValue(String mac){
        BleDeviceManager _deviceManager = BleDeviceManager.get(mReactContext);
        BleDevice device =  _deviceManager.getDevice(mac);

        if(device == null){
            Log.i(TAG,"获取不到指定的设备");
            return;
        }
        BleNativeEnuoBPDevice nativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
        nativeDevice.sendGetBatteryValue();
    }

    /** 关断设备 */
    @ReactMethod
    public void  powerOffDevice(String mac){
        BleDeviceManager _deviceManager = BleDeviceManager.get(mReactContext);
        BleDevice device =  _deviceManager.getDevice(mac);

        if(device == null){
            Log.i(TAG,"获取不到指定的设备");
            return;
        }
        BleNativeEnuoBPDevice nativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
        nativeDevice.sendPowerOffDevice();
    }

    @ReactMethod
    synchronized public void getConnectedBP(Promise promise){
        ArrayList<BleDevice> devices  = (ArrayList<BleDevice>)BleDeviceManager.get(mReactContext).getDevices().clone();
        WritableArray glucoseDevices = Arguments.createArray();
        for(int i=0,length=devices.size();i<length;i++){
            BleDevice device = devices.get(i);
            if(device.getDeviceName() == null){
                continue;
            }

            if(!(
                 device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_CLINK_BP) ||
                 device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_RBP) ||
                 device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_YASEE_BP)
                )
              ){
                continue;
            }


            BleDevice.DeviceConnectState state = device.getDeviceState();
            if(state != BleDevice.DeviceConnectState.Connected && state != BleDevice.DeviceConnectState.Connecting ){
                continue;
            }


            WritableMap info = Arguments.createMap();
            info.putString("deviceName", device.getDeviceName());
            info.putString("deviceMac",device.getMacAddress());
            glucoseDevices.pushMap(info);
        }

        promise.resolve(glucoseDevices);
    }

    @ReactMethod
    synchronized public void disconnectDevice(String deviceMac){
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);

        if(device == null){
            //没有找到设备,直接返回
            return;
        }

        device.disconnect();
    }
    synchronized public static double getXueTangData(int value) {
        double data = 0;
        int uiMmol = 0;
        uiMmol = value * 100;
        uiMmol /= 18;
        uiMmol += 5;
        uiMmol /= 10;
        data = uiMmol;
        return data / 10;
    }

    synchronized public double getKetoneData(int value){
        return ((double) value)/10;
    }



    /** 开始扫描动态血糖仪 */
    @ReactMethod
    synchronized public void startScanDynamicGlucose(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_DYNAMIC_GLUCOSE);
        BleDeviceManager.get(mReactContext).enableBleScan();

        Log.i(TAG,"开启动态血糖");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
               RNLog.d(TAG,"通过E发现设备"+e.getDevice().getDeviceName());
//                if(!e.isNewlyDiscovered()){
//               Log.d(TAG,"改设备已经被发现过");
//                    return;
//                }

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_DYG_BT_DEVICE",map);

//                connectDynamicGlucose(e.getDevice().getMacAddress());
            }
        });
    }

    @ReactMethod
    synchronized public void startScanAllGlucose(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_ALL_GLUCOSE);
        BleDeviceManager.get(mReactContext).enableBleScan();

        RNLog.i(TAG,"开启所有血糖扫描");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_DYG_BT_DEVICE",map);
            }
        });
    }

    /** 停止扫描 */
    @ReactMethod
    synchronized public void stopScanDynamicGlucose(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_ALL_GLUCOSE);
        BleDeviceManager.get(mReactContext).disableBleScan();

        RNLog.d(TAG,"关闭动态血糖");

        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }

    /** 停止扫描 */
    @ReactMethod
    synchronized public void stopScanAllGlucose(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_ALL_GLUCOSE);
        BleDeviceManager.get(mReactContext).disableBleScan();

        RNLog.d(TAG,"关闭所有血糖扫描");

        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }

    /** 开始启动扫描仪 */
    @ReactMethod
    synchronized  public void connectDynamicGlucose(String deviceMac){
        Log.d(TAG,"android start connect dy");
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
        if(device == null){
            RNLog.d(TAG,"no device");

            WritableMap map = Arguments.createMap();
            map.putString("deviceName", "no device");
            map.putString("deviceMac",deviceMac);
            map.putString("deviceStatusDescription","连接失败");
            map.putString("deviceStatus","connectError");
            mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);

            return;
        }

        try{
            Thread.sleep(500);
        }catch (InterruptedException error){
            error.printStackTrace();
        }


        device.connect(new BleDevice.BleDeviceCallback() {
            @Override
            public void onConnect(BleDevice device) {
                RNLog.d(TAG,"on connect");
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","connect");

            }
            @Override
            public void onBonded(BleDevice device){

            }

            @Override
            public void onDisconnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","disconnect");

                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
            }

            @Override
            public void onGetServices(BleDevice device) {



            }

            @Override
            public void onConnectError(BleDevice device, String error) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","连接失败");
                map.putString("deviceStatus","connectError");

                mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);
            }
        });

//        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        nativeDevice.setNativeDeviceCallback(

        BleDynamicGlucose.BleNativeDYDeviceCallback callback = new BleDynamicGlucose.BleNativeDYDeviceCallback() {
            @Override
            public void onCreatedChannel(BleDevice device) {
                RNLog.d(TAG,"创建服务完成");

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","创建通道完成");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","createdChannel");

                mEventManager.sendCustomEvent("DYG_CREATED_CHANNEL",map);
            }

            @Override
            public void onAuthenticated(BleDevice device,Boolean isSuc) {
                RNLog.d(TAG,"认证成功");

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","认证成功");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","onAuthenticated");
                map.putBoolean("isSuc",isSuc);

                mEventManager.sendCustomEvent("DYG_ON_DO_AUTHORIZATION",map);
            }

            @Override
            public void onGetName(BleDevice device,String name){

            }

            @Override
            public void onGetBattery(BleDevice device,Double value){

                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());

                map.putDouble("value",value);


                mEventManager.sendCustomEvent("DYG_ON_GET_BATTERY",map);
            }

            @Override
            public void onGetMonitorStatus(BleDevice device,Boolean isStartMonitor){
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","getAllDataCount");
                map.putBoolean("isStartMonitor",isStartMonitor);


                mEventManager.sendCustomEvent("DYG_ON_GET_MONITOR_STATUS",map);
            }

            @Override
            public void onGetAllDataCount(BleDevice device,int count){
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","getAllDataCount");
                map.putInt("count",count);


                mEventManager.sendCustomEvent("DYG_ON_GET_ALL_DATA_COUNT",map);
            }

            @Override
            public void onGetProgressData(BleDevice device,Double[] dataList,int index){
                RNLog.d(TAG,dataList.length+"");
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","getAllData");

                WritableArray array = Arguments.createArray();

                for(Double data :dataList){
                    array.pushDouble(data);
                }

                map.putArray("dataList",array);
                map.putInt("dataIndex",index);


                mEventManager.sendCustomEvent("DYG_ON_GET_ALL_DATA",map);
            }

            @Override
            public void onStartMonitor(BleDevice device,Boolean isSuc){
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","startMonitor");
                map.putBoolean("isSuc",isSuc);


                mEventManager.sendCustomEvent("DYG_ON_START_MONITOR",map);
            }

            @Override
            public void onStopMonitor(BleDevice device,Boolean isSuc){
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","stopMonitor");
                map.putBoolean("isSuc",isSuc);


                mEventManager.sendCustomEvent("DYG_ON_STOP_MONITOR",map);
            }



            @Override
            public void onUpdateNewData(BleDevice device,int index,Double value){
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","得到所有数据数量");
                map.putString("deviceStatus","connect");
                map.putString("connectStatus","getAllData");
                map.putInt("index",index);
                map.putDouble("value",value);


                mEventManager.sendCustomEvent("DYG_ON_UPDATE_NEW_DATA",map);

            }

        };
//        );

        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
        nativeDevice.setNativeDeviceCallback(callback);
    }


    @ReactMethod
    synchronized public void disconnecAllDYGDevicetWithout(String deviceMac){
        ArrayList<BleDevice> devices = BleDeviceManager.get(mReactContext).getDevices();

        for(BleDevice device:devices){
            if(!device.getMacAddress().startsWith(deviceMac) &&
                (device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_DYNAMIC_GLUCOSE))){

                device.forceDisconnect();
            }
        }
    }


    @ReactMethod
    synchronized public void doAuthorizationDYG(String deviceMac,int requestCode){
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"do auth");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
        nativeDevice.doAuthorization(requestCode);
    }

    @ReactMethod
    synchronized public void getMonitorStatusDYG(String deviceMac,int requestCode){
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get monitor status");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getMonitorStatus(requestCode);
    }

    @ReactMethod
    synchronized public void getBatteryDYG(String deviceMac,int requestCode){
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        Log.d(TAG,"get battery dyg");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();

        nativeDevice.getBattery(requestCode);
    }

    @ReactMethod
    synchronized public void startMonitorDYG(String deviceMac,int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"start monitor");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.startMonitor(requestCode);
    }

    @ReactMethod
    synchronized public void stopMonitorDYG(String deviceMac,int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"stop monitor");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.stopMonitor(requestCode);
    }

    @ReactMethod
    synchronized public  void getNumberDataFromIndexDYG(String deviceMac,int requestCode, int index, int number) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get all data count from index");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getNumberDataFromIndex(requestCode,index,number);
    }

    @ReactMethod
    synchronized public  void getAllDataFromIndexDYG(String deviceMac,int requestCode, int index) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get all data count from index");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getAllDataFromIndex(requestCode,index);
    }

    @ReactMethod
    synchronized public void getAllDataCountDYG(String deviceMac,int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get all data count");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getAllDataCount(requestCode);
    }

    @ReactMethod
    synchronized public void getAllDataDYG(String deviceMac,int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get all data");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getAllData(requestCode);

    }

    @ReactMethod
    synchronized public  void getNameDYG(String deviceMac, int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get name");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getName(requestCode);
    }

    public  void getMaxNumber(int requestCode) {

    }


    @ReactMethod
    synchronized public  void getSnDYG(String deviceMac, int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get sn");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getSn(requestCode);
    }

    @ReactMethod
    synchronized public  void getVersionDYG(String deviceMac, int requestCode) {
        BleDevice device = getAssignedDevice(deviceMac);
        if(device == null){
            return;
        }

        RNLog.d(TAG,"get version");
        BleDynamicGlucose nativeDevice = (BleDynamicGlucose) device.getNativeDevice();
//        BleDGType2Device nativeDevice = (BleDGType2Device) device.getNativeDevice();

        nativeDevice.getVersion(requestCode);
    }



    public  void getRecord(int requestCode) {

    }



    synchronized private BleDevice getAssignedDevice(String deviceMac){
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
        if(device == null){
            RNLog.i(TAG,"no device");

            WritableMap map = Arguments.createMap();
            map.putString("deviceName", "no device");
            map.putString("deviceMac",deviceMac);
            map.putString("deviceStatusDescription","no device");
            map.putString("deviceStatus","noDevice");
            mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);

            return null;
        }

        return device;
    }


    @ReactMethod
    public void caculateBloodGlucose(ReadableMap info,Promise promise){
        Algorithm20 algorithm = new Algorithm20();
        ReadableArray values = info.getArray("values");
        ArrayList<Double> valueList = new ArrayList<>();
        for(int i=0;i<values.size();i++){
            Double value = values.getDouble(i);
            valueList.add(value);
        }
        ArrayList<Double> bgValues = algorithm.calculateBloodGlucose(
                    info.getInt("index"),info.getDouble("refValue"),valueList);

        WritableArray bgRNValues = Arguments.createArray();
        for(Double bgValue: bgValues){
            RNLog.d(TAG,bgValue.toString());
            bgRNValues.pushDouble(bgValue);
        }

        promise.resolve(bgRNValues);

    }

    @ReactMethod
    public void caculateDyRoc(ReadableMap info,Promise promise){
        Algorithm20 algorithm = new Algorithm20();
        ReadableArray values = info.getArray("values");
        ArrayList<Double> valueList = new ArrayList<>();
        for(int i=0;i<values.size();i++){
            Double value = values.getDouble(i);
            valueList.add(value);
        }
        algorithm.calculateBloodGlucose(
                info.getInt("index"),info.getDouble("refValue"),valueList);
        int result = algorithm.calRoc();


        promise.resolve(result);

    }


    /**   下面是尿酸相关的程序   */
    @ReactMethod
    synchronized public void startScanACID(){
        BleDeviceManager.get(mReactContext).setSearchedDeviceType(ENDeviceConst.SEARCH_TYPE_ACID);
        BleDeviceManager.get(mReactContext).enableBleScan();

        RNLog.i(TAG,"开启所有血糖扫描");

        BleDeviceManager.get(mReactContext).setDiscoverListener(new BleDeviceManager.DiscoverListener() {
            @Override
            public void onEvent(BleDeviceManager.DiscoverEvent e) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", e.getDevice().getDeviceName());
                map.putString("deviceMac",e.getDevice().getMacAddress());
                map.putString("deviceStatusDescription","开始连接");
                map.putString("deviceStatus","startConnect");
                mEventManager.sendCustomEvent("DISCOVER_DYG_BT_DEVICE",map);
            }
        });

    }


    @ReactMethod
    synchronized public void stopScanACID(){
        BleDeviceManager.get(mReactContext).disableBleScan();
        BleDeviceManager.get(mReactContext).setDiscoverListener(null);
    }

    @ReactMethod
    synchronized public void connectACID(String deviceMac){
        Log.d(TAG,"android start connect dy");
        BleDevice device = BleDeviceManager.get(mReactContext).getDevice(deviceMac);
        if(device == null){
            RNLog.d(TAG,"no device");

            WritableMap map = Arguments.createMap();
            map.putString("deviceName", "no device");
            map.putString("deviceMac",deviceMac);
            map.putString("deviceStatusDescription","连接失败");
            map.putString("deviceStatus","connectError");
            mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);

            return;
        }

        try{
            Thread.sleep(500);
        }catch (InterruptedException error){
            error.printStackTrace();
        }


        device.connect(new BleDevice.BleDeviceCallback() {
            @Override
            public void onConnect(BleDevice device) {
                RNLog.d(TAG,"on connect");
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","connect");

            }

            @Override
            public void onDisconnect(BleDevice device) {
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","disconnect");

                mEventManager.sendCustomEvent("DISCONNECT_BT_DEVICE",info);
            }

            @Override
            public void onBonded(BleDevice device){
                WritableMap info = Arguments.createMap();
                info.putString("deviceName", device.getDeviceName());
                info.putString("deviceMac",device.getMacAddress());
                info.putString("deviceStatus","bounded");

                mEventManager.sendCustomEvent("BOUNDED_BT_DEVICE",info);
            }

            @Override
            public void onGetServices(BleDevice device) {
                RNLog.d(TAG,"on get service");

                BleNativeBeneCheckerDevice.BleNativeBeneCheckerCallback callback = new BleNativeBeneCheckerDevice.BleNativeBeneCheckerCallback() {
                    @Override
                    public void onResult(BleDevice device, GlucoseData data,String type) {
                        SimpleDateFormat formatter =   new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                        Date curDate =  new Date(System.currentTimeMillis());//获取当前时间
                        String curDateString =  formatter.format(curDate);
                        String result = data.getYear() +"年"+ data.getMonth() +"月"+ data.getDay() + "日" + data.getHour() + "时" + data.getMinute() + "分" +"\n 结果："
                                + new BigDecimal((float)(data.getGlucose()/168.1) + 0.05).setScale(3,BigDecimal.ROUND_DOWN).floatValue() + "指示：" + data.getFlagValue();
//                            Log.d(TAG,"time:"+dateString+"\n血糖值:"+result+"");
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
                        String dateString  = data.getYear()+"-"+data.getMonth()+"-"+data.getDay()+" "+data.getHour()+"-"+data.getMinute();
                        Date deviceDate;
                        String deviceTime;
                        try{
                            deviceDate = dateFormat.parse(dateString);
                            deviceTime =deviceDate.getTime()+"";
                        }catch (Exception exception){
                            deviceTime = ""+0;
                        }

//                        String displayValue = new BigDecimal((float)(data.getGlucose()/168.1)).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
                        String displayValue =new BigDecimal((float)(data.getGlucose()/168.1)).setScale(3,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(1000)).toString();

                        WritableMap map = Arguments.createMap();
                        map.putString("deviceName", device.getDeviceName());
                        map.putString("deviceMac",device.getMacAddress());
                        map.putString("deviceStatusDescription","测量成功");
                        map.putString("resultType",type);
                        map.putString("deviceStatus","result");
                        map.putString("time",curDateString);
                        map.putString("deviceTime",deviceTime);
                        map.putString("value",""+data.getGlucose());
                        map.putString("displayValue",""+displayValue);

                        RNLog.d(TAG,map.toString());

                        mEventManager.sendCustomEvent("RESULT_ACID",map);
                    }
                };
                RNLog.d(TAG,"start set");

                BleNativeBeneCheckerDevice nativeDevice = (BleNativeBeneCheckerDevice)device.getNativeDevice();
                nativeDevice.setNativeDeviceCallback(callback);


            }

            @Override
            public void onConnectError(BleDevice device, String error) {
                WritableMap map = Arguments.createMap();
                map.putString("deviceName", device.getDeviceName());
                map.putString("deviceMac",device.getMacAddress());
                map.putString("deviceStatusDescription","连接失败");
                map.putString("deviceStatus","connectError");

                mEventManager.sendCustomEvent("ERROR_BT_DEVICE",map);
            }
        });
    }

    @ReactMethod
    synchronized public void getConnectedACID(Promise promise){
        ArrayList<BleDevice> devices  = (ArrayList<BleDevice>)BleDeviceManager.get(mReactContext).getDevices().clone();
        WritableArray ACIDDeviceList = Arguments.createArray();
        for(int i=0,length=devices.size();i<length;i++){
            BleDevice device = devices.get(i);
            if(!(device.getDeviceName().startsWith(ENDeviceConst.DEVICE_TYPE_BENE_CHECKER))){
                continue;
            }


            BleDevice.DeviceConnectState state = device.getDeviceState();
            if(state != BleDevice.DeviceConnectState.Connected && state != BleDevice.DeviceConnectState.Connecting ){
                continue;
            }


            WritableMap info = Arguments.createMap();
            info.putString("deviceName", device.getDeviceName());
            info.putString("deviceMac",device.getMacAddress());
            ACIDDeviceList.pushMap(info);
        }

        promise.resolve(ACIDDeviceList);
    }



    synchronized public void turnOnBT(){
        WritableMap info = Arguments.createMap();
        info.putString("status","on");
        mEventManager.sendCustomEvent("UPDATE_BT_STATUS",info);
    }

    synchronized public void turnOffBT(){
        WritableMap info = Arguments.createMap();
        info.putString("status","off");
        mEventManager.sendCustomEvent("UPDATE_BT_STATUS",info);
    }

    synchronized public void turningOnBT(){

    }

    //Receiver
    private BroadcastReceiver mScanDataReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            if (action.equals("com.android.scancontext")){
                // “前台输出”不打勾时,不会发送此 Intent
                String str = intent.getStringExtra("Scan_context");
                Log.i(TAG,"card info1:"+intent.getExtras().toString());
                WritableMap map = Arguments.createMap();
                map.putString("deviceStatus","ScanResultFront");
                map.putString("result",str);
                mEventManager.sendCustomEvent("SCAN_CODE",map);
            } else if (action.equals("com.android.scanservice.scancontext")) {
                String str = intent.getStringExtra("Scan_context");
                Log.i(TAG,"card info2:"+intent.getExtras().toString());

                WritableMap map = Arguments.createMap();
                map.putString("deviceStatus","ScanResultBackground");
                map.putString("result",str);
                mEventManager.sendCustomEvent("SCAN_CODE",map);
            }

        } };

    /** 设置动态血压 */
    @ReactMethod public void sendSetDyBP(String mac){
        BleDeviceManager _deviceManager = BleDeviceManager.get(mReactContext);
        BleDevice device =  _deviceManager.getDevice(mac);

        if(device == null){
            Log.i(TAG,"获取不到指定的设备");
            return;
        }
        BleNativeEnuoBPDevice nativeDevice = (BleNativeEnuoBPDevice) device.getNativeDevice();
//        nativeDevice.sendSetDyBP();
    }


    /** 厚美德一体机 */
//    @ReactMethod
//    public void startMonitT8601MD(){
//        Log.d(TAG,"start monit");
//        mMcuDataOptAnysis = new McuDataOperateAndAnysis(mReactContext);
//        mMcuDataOptAnysis.setCommandAnysisRstCallback(mDataCb);
//        mMcuDataOptAnysis.startReceiveData();
//       // mMcuDataOptAnysis.sendGetSupportStripsCodeCommand((byte)0);
//
//    }
//
//    @ReactMethod
//    public void  setScripCode(int code){
//        Log.d(TAG, "setScripCode: "+code);
//        mMcuDataOptAnysis.sendSetStripCodeCommand(code);
//    }


//  private McuDataOperateAndAnysis mMcuDataOptAnysis = null;

//    McuDataOperateAndAnysis.CommandAnysisRstCallback mDataCb = new McuDataOperateAndAnysis.CommandAnysisRstCallback() {
//        @Override
//        public void onInsertStrip(McuDataOperateAndAnysis.STRIP_TYPE strip_type) {
//            Log.d(TAG,"insert strip"+strip_type);
//            WritableMap map = Arguments.createMap();
//
//            map.putString("deviceStatusDescription","状态");
//            map.putString("deviceStatus","result");
//
//            switch (strip_type) {
//                case NEW_STRIP://插入新的试纸（“请滴血”）
//                    map.putString("deviceStatus","insert");
//                    mEventManager.sendCustomEvent("T8601MD_INSERT_NEW_STRIP",map);
//                    break;
//                case SELF://自检试纸
//                    break;
//                case CHECK_RESISTOR://校正电阻
//                    break;
//                case TEST_RESISTOR://质检ok
//                    break;
//                case USED://试纸已使用
//                    mEventManager.sendCustomEvent("T8601MD_INSERT_USED_STRIP",map);
//                    break;
//                case UNKNOW://不正确试纸
//                    mEventManager.sendCustomEvent("T8601MD_INSERT_UNKNOWN_STRIP",map);
//
//                    break;
//            }
//        }
//
//        @Override
//        public void onGetBoold() {
//            Log.d(TAG,"get blood");
//            WritableMap map = Arguments.createMap();
//
//            map.putString("deviceStatusDescription","状态");
//            map.putString("deviceStatus","result");
//            mEventManager.sendCustomEvent("T8601MD_GET_BLOOD",map);
//
//
//        }
//
//        @Override
//        public void onTestCountDown(int i) {
//            Log.d(TAG,"get count "+i);
//
//            WritableMap map = Arguments.createMap();
//
//            map.putString("deviceStatusDescription","状态");
//            map.putString("value",""+i);
//
//            mEventManager.sendCustomEvent("T8601MD_TEST_COUNT_DOWN",map);
//
//
//        }
//
//        @Override
//        public void onGetResult(int i, int i1, int i2, float v) {
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
//            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
//            String dateString = formatter.format(curDate);
//
//            Log.d(TAG, "time:" + dateString + "\n血糖值:" + i + "");
//            String displayValue = new BigDecimal(i/18.0).setScale(1,BigDecimal.ROUND_FLOOR).toString();
//
//            WritableMap map = Arguments.createMap();
//            map.putString("deviceStatusDescription", "测量成功");
//            map.putString("deviceStatus", "result");
//            map.putString("resultType", "glucose");
//
//            map.putString("time", dateString);
//            map.putString("value", displayValue);
//            map.putString("displayValue", displayValue);
//
//            mEventManager.sendCustomEvent("T8601MD_RESULT_BT_DEVICE", map);
//        }
//
//        @Override
//        public void onStripOutOrSleep() {
//            Log.d(TAG,"strip out");
//            WritableMap map = Arguments.createMap();
//            map.putString("deviceStatusDescription", "Strip out");
//
//            mEventManager.sendCustomEvent("T8601MD_STRIP_OUT_OR_SLEEP", map);
//        }
//
//        @Override
//        public void onError() {
//            Log.d(TAG,"get error");
//
//        }
//
//        @Override
//        public void onGetTemper(float v) {
//            Log.d(TAG,"get temp"+v);
//
//        }
//
//        @Override
//        public void onGetStripCode(int i){
//            Log.d(TAG, "onGetStripCode: "+i);
//
//            WritableMap map = Arguments.createMap();
//            map.putString("code",""+i);
//
//            mEventManager.sendCustomEvent("T8601MD_stripCode",map);
//            mMcuDataOptAnysis.startGetSupportStripsCodeEx();
//        }
//
//        @Override
//        public void onGetSupportStripCodesFinished() {
//            SharedPreferences preferences=mReactContext.getSharedPreferences("gluc", Context.MODE_PRIVATE);
//             String codes =   preferences.getString("supStripCodes","");
//            Log.d(TAG, "onGetSupportStripCodesFinished: "+codes);
//            WritableMap map = Arguments.createMap();
//            map.putString("codes",codes);
//            mEventManager.sendCustomEvent("T8601MD_onGetSupportStripCodesFinished", map);
//
//
//        }
//    };



}
