//
//  ENDeviceManager.m
//  ENBLEProject
//
//  Created by lvwang2002 on 16/4/6.
//  Copyright © 2016年 Facebook. All rights reserved.
//

// 20161023 14:17 修改超时验证的问题.
// 20170223 10:18 增加血压驱动
// 20170223 11:10 修改bug
// 20170223 13:34 修改bug
// 20170223 15:42 修改bug
// 20170223 17:04 增加身份证读卡器
// 20170227 10:43 修改one callback的bug
// 20170227 13:47 修改模拟器下不能运行的bug
// 20170228 11:36 增加血压计断开连接指令
// 20170228 11:36 增加血压计断开连接指令
// 20170302 10:55 修改自动启动血压计测量
// 20170302 13:11 身份证读卡器不能断开连接
// 20170302 15:21 修改bug
// 20170303 16:19 修改身份证bug


#import "RNMethodModule.h"
//#import "RCTLog.h"
//#import "RCTBridge.h"
//#import "RCTEventDispatcher.h"
#import "ENBPDevice.h"
#import "ENPangaoBPDevice.h"
//#import "glucose.h"


@implementation RNMethodModule{
	ENBLEDeviceManager *_deviceManager;
#if TARGET_IPHONE_SIMULATOR//模拟器
 
#elif TARGET_OS_IPHONE//真机
//	INVSBleTool *_bletool;
#endif
	BLEDevice *_cardDevice;
	Boolean _isUpdateDeviceList;
	RCTPromiseResolveBlock _resolve;
	RCTPromiseRejectBlock _reject;
	RCTPromiseResolveBlock _startCardResolve;
	RCTPromiseRejectBlock _startCardRejecte;
	RCTPromiseResolveBlock _endCardResolve;
	RCTPromiseRejectBlock _endCardReject;
	RCTPromiseResolveBlock _connectCardResolve;
	RCTPromiseRejectBlock _connectCardReject;

	NSArray *_deviveStatusList;
}
RCT_EXPORT_MODULE();
@synthesize bridge = _bridge;

-(instancetype)init{
	self = [super init];
	if(self){
		_deviceManager = [ENBLEDeviceManager shareDeviceManager];
		_deviceManager.deviceManagerDelegate = self;
		[_deviceManager setSearchedDeviceType:ENSearchedBPType];
		[_deviceManager setIsShowLog:YES];
		_isUpdateDeviceList = false;
		_deviveStatusList = @[@"Discovered", @"Connecting", @"Connected", @"Disconnecting", @"Disconnect",@"ConnectFailed"];
#if TARGET_IPHONE_SIMULATOR//模拟器
		
#elif TARGET_OS_IPHONE//真机
//		_bletool=[[INVSBleTool alloc]init:self];
		
#endif
		
	}
    
//    uint16 args[] = {6, 279, 0, 150, 18, 80, 52, 0};
//    uint16 *result = [glucose GlucoseCalculatio:args];
//
//    NSLog(@"%hi,%hi,%hi,%hi,%hi,%hi,%hi,%hi", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]);
	return self;
}

RCT_EXPORT_METHOD(addEvent:(NSString *)name location:(NSString *)location){
	NSLog(@"Pretending to create an event %@ at %@", name, location);
}

	//startBleManager
RCT_EXPORT_METHOD(startBLEScan){
	[_deviceManager startScan];
}

-(void)didUpdateBTStatus:(ENBTStatus)status{
	NSString *btStatus = nil;
	if(status == ENBTPowerOnStatus){
		NSLog(@"打开蓝牙");
			//		[_deviceManager startScan];
		btStatus = @"on";
	}else{
		NSLog(@"关闭蓝牙");
		btStatus = @"off";

	}
	NSDictionary *info = @{
			@"status":btStatus
	};
	[self.bridge.eventDispatcher sendAppEventWithName:@"UPDATE_BT_STATUS"													body:info];

}

-(void)didDiscoverDevice:(BLEDevice *)device IsNewly:(BOOL)isNewly{
//	RCTLogInfo(@"Pretending to create an event%@", [device getDeviceName]);
	
	if(!isNewly){
		ENLog(@"已经侦测到设备");
		return;
	}
	device.deviceDelegate = self;
		//	[device connect];
	
	NSDictionary *body =@{
						  @"deviceName":[device getDeviceName],
						  @"deviceMac":[[device getUUID] UUIDString],
						  @"deviceStatusDescription":@"开始连接",
						  @"deviceStatus":@"startConnect"
						  };
		//	[self sendEventWithName:@"DISCOVER_BT_DEVICE"	body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"DISCOVER_ALL_BT_DEVICE"													body:body];
	
	
//	if([[device getDeviceName] hasPrefix:@"INVS300"]){
//		dispatch_async([_deviceManager getPostQueue], ^{
//#if TARGET_IPHONE_SIMULATOR//模拟器
//			
//#elif TARGET_OS_IPHONE //真机
//			BOOL isOk = [_bletool connectBt:[device getPeripheral]];
//			_cardDevice = device;
//#endif
//			
//		});
//		return;
//		
//	}
	
//	NSLog(@"设备名字:%@",[device getDeviceDisplayName]);
}


-(void)didUpdateSearchedDevices:(NSArray *)searchedDevices{
	
	if(!_isUpdateDeviceList){
		return;
	}
	
	NSMutableArray *tempDevices = [[NSMutableArray alloc] initWithCapacity:10];
	for(BLEDevice *device in searchedDevices){
		NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithCapacity:10];
		[map setObject:[device getDeviceName] forKey:@"deviceName"];
		[map setObject:[[device getDeviceUUID] UUIDString] forKey:@"deviceMac"];
        [map setObject:[[(BLEDevice *)device getNativeDevice] getDeviceDisplayName]  forKey:@"deviceDisplayName"];
        
		unsigned long  statusIndex = (unsigned long)device.connectStatus;
		NSString *deviceStatus = _deviveStatusList[statusIndex];
        
		[map setObject:deviceStatus forKey:@"deviceStatus"];
		[tempDevices addObject:map];
        
        NSString *connectedStatus = [[device getNativeDevice] getConnectedStatus];
        [map setObject:connectedStatus forKey:@"connectedStatus"];
	}
	
		//	[self sendEventWithName:@"UPDATE_DEVICE_LIST"													body:tempDevices];
	
	[self.bridge.eventDispatcher sendAppEventWithName:@"UPDATE_DEVICE_LIST"													body:tempDevices];
}


//开始接收扫描到的设备
RCT_EXPORT_METHOD(setBluetooth){
}

	//开始接收扫描到的设备
RCT_EXPORT_METHOD(startUpdateDeviceList){
	_isUpdateDeviceList = true;
}

	//停止接收扫描到的设备
RCT_EXPORT_METHOD(stopUpdateDeviceList){
	_isUpdateDeviceList = false;
}

	//是否显示日志
RCT_EXPORT_METHOD(showLog:(BOOL)isShow){
	[_deviceManager setIsShowLog:isShow];
}

RCT_EXPORT_METHOD(forceUpdateDeviceList){
//    BleDeviceManager.get(mReactContext).postUpdateDeviceList();
    [[ENBLEDeviceManager shareDeviceManager] postUpdateDeviceList];
}

-(void)didConnectedDevice:(BLEDevice *)device{
    /** MQ动态血糖有单独模块处理 */
    if([[device getDeviceName] hasPrefix:@"O"]){
        return;
    }
    
    if([[device getDeviceName] hasPrefix:@"TH-"]){
        return;
    }
    
	device.nativeDevice.deviceDelegate = self;
	
	if([[device getDeviceName] hasPrefix:@"ClinkBlood"]){
		return;
	}
	
	NSDictionary *body =@{
						  @"deviceName":[device getDeviceName],
						  @"deviceMac":[[device getUUID] UUIDString],
						  @"deviceStatusDescription":@"连接成功",
						  @"deviceStatus":@"connectSuc"
						  };
   [self.bridge.eventDispatcher sendAppEventWithName:@"CONNECTED_BT_DEVICE"													body:body];

}

-(void)didDisconnectDevice:(BLEDevice *)device{
	NSDictionary *body =@{
						  @"deviceName":[device getDeviceName],
						  @"deviceMac":[[device getUUID] UUIDString],
						  @"deviceStatus":@"disconnect"
						  };
		//	[self sendEventWithName:@"DISCONNECTED_BT_DEVICE" body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"DISCONNECT_BT_DEVICE"													body:body];
}

-(void)didOverTimeForConnectDevice:(BLEDevice *)device{
	NSDictionary *body =@{
						  @"deviceName":[device getDeviceName],
						  @"deviceMac":[[device getUUID] UUIDString],
						  @"deviceStatus":@"connect time over"
						  };
	[self.bridge.eventDispatcher sendAppEventWithName:@"ERROR_BT_DEVICE"													body:body];
}


	//开始扫描血糖
RCT_EXPORT_METHOD(startScanGlucose){
	@synchronized (self) {
		[_deviceManager setSearchedDeviceType:ENSearchedGlucoType];
		_deviceManager.deviceManagerDelegate = self;
		[_deviceManager startScan];
	}
}

	//停止扫描血糖
RCT_EXPORT_METHOD(stopScanGlucose){
	@synchronized (self) {
		[_deviceManager setSearchedDeviceType:ENSearchedGlucoType];
			//	_deviceManager.deviceManagerDelegate = nil;
		[_deviceManager stopScan];
	}
}

	//连接单个血糖仪器,并断开其他所有的连接.
RCT_EXPORT_METHOD(connectSingleDevice:(NSString *)deviceMac){
	@synchronized (self) {
		NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:deviceMac];
		BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
		if(!device){
				//		reject(@"402",@"can not find device",nil);
			NSDictionary *body = @{
								   @"deviceName":@"no device",
								   @"deviceMac":deviceMac,
								   @"deviceStatusDescription":@"no device",
								   @"deviceStatus":@"error"
								   };
			[self.bridge.eventDispatcher sendAppEventWithName:@"ERROR_BT_DEVICE"													body:body];
			return;
		}
		device.deviceDelegate = self;
		[device connect];
		
		//其他的设备都关闭
		NSArray *devices = [_deviceManager getSearchedDevices];
        NSLog(@"%@", devices);
		for(BLEDevice *myDevice in devices){
			NSString *myDeviceUUID = [[myDevice getUUID] UUIDString];
			
			
			if([myDeviceUUID isEqualToString:deviceMac]){
				continue;
			}
			
			if((myDevice.connectStatus != DeviceConnectingStatus) &&
			   (myDevice.connectStatus != DeviceConnectedStatus)){
				continue;
			}
            if([[myDevice getDeviceName] hasPrefix:@"O"]){
                continue;
            }
            if([[myDevice getDeviceName] hasPrefix:@"TH-"]){
                continue;
            }
            
			
			dispatch_async([_deviceManager getPostQueue], ^{
				[myDevice disconnect];
			});
			
		}
	}
}


RCT_EXPORT_METHOD(disconnectGlucose:(NSString *)deviceMac){
	@synchronized (self) {
		NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:deviceMac];
		BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
		
		if(!device){
			return;
		}
		
		[device disconnect];
	}
}

RCT_REMAP_METHOD(getConnectedGlucose,
				 resolver:(RCTPromiseResolveBlock)resolve
				 rejecter:(RCTPromiseRejectBlock)reject){
	@synchronized (self) {
		NSArray *devices = [_deviceManager getSearchedDevices];
		NSMutableArray *glucoseDevices = [[NSMutableArray alloc]initWithCapacity:10];
		
		for(BLEDevice *device in devices){
			if(!([[device getDeviceName] hasPrefix:@"Glucose"]
                 || [[device getDeviceName] hasPrefix:@"BLE-ENUO"]
                 || [[device getDeviceName] hasPrefix:@"ENUO-G"])){
				continue;
			}
			
			ConnectStatus status = device.connectStatus;
			if(status != DeviceConnectedStatus && status != DeviceConnectingStatus){
				continue;
			}
			
			NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10];
			[info setObject:[device getDeviceName] forKey:@"deviceName"];
			[info setObject:[[device getDeviceUUID] UUIDString] forKey:@"deviceMac"];
			[glucoseDevices addObject:info];
		}
		
		resolve(glucoseDevices);
	}
}
/** 开始扫描全部设备 */
RCT_EXPORT_METHOD(startScanDevice){
	@synchronized (self) {
		[_deviceManager setSearchedDeviceType:ENSearchedAllType];
		_deviceManager.deviceManagerDelegate = self;
		[_deviceManager startScan];
	}
}

RCT_EXPORT_METHOD(stopScanDevice){
	@synchronized (self) {
		[_deviceManager stopScan];
	}
}

/** 开始扫描血压 */
RCT_EXPORT_METHOD(startScanBP){
	@synchronized (self) {
		[_deviceManager setSearchedDeviceType:ENSearchedBPType];
		_deviceManager.deviceManagerDelegate = self;
		[_deviceManager startScan];
	}
}

/** 停止扫描血压 */
RCT_EXPORT_METHOD(stopScanBP){
	@synchronized (self) {
		[_deviceManager stopScan];
	}
}


	//连接单个血压计
//public void connectSingleBPDevice(String deviceMac)
RCT_EXPORT_METHOD(connectSingleBPDevice:(NSString *)uuid){
	@synchronized (self) {
		NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:uuid];
		BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
		if(!device){
				//		reject(@"402",@"can not find device",nil);
			NSDictionary *body = @{
								   @"deviceName":@"no device",
								   @"deviceMac":uuid,
								   @"deviceStatusDescription":@"no device",
								   @"deviceStatus":@"error"
								   };
			[self.bridge.eventDispatcher sendAppEventWithName:@"ERROR_BT_DEVICE"													body:body];
			return;
		}
		device.deviceDelegate = self;
		[device connect];
		
			//其他的设备都关闭
		NSArray *devices = [_deviceManager getSearchedDevices];
		for(BLEDevice *myDevice in devices){
			NSString *myDeviceUUID = [[myDevice getUUID] UUIDString];
			
			
			if([myDeviceUUID isEqualToString:uuid]){
				continue;
			}
			
			if((myDevice.connectStatus != DeviceConnectingStatus) &&
			   (myDevice.connectStatus != DeviceConnectedStatus)){
				continue;
			}
			
			dispatch_async([_deviceManager getPostQueue], ^{
				[myDevice disconnect];
			});
			
		}
	}
}
	//开始血压测量
RCT_EXPORT_METHOD(startTestBP:(NSString *)uuid){
	NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:uuid];
	BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
	
	if([device.getDeviceName isEqualToString:@"ClinkBlood"]){
		ENPangaoBPDevice *bpDevice = (ENPangaoBPDevice *)device.nativeDevice;
		if(device == nil){
			ENLog(@"start test bp");
			return;
		}
		
		[bpDevice  startTest];
	}else{
		ENBPDevice *bpDevice = (ENBPDevice *)device.nativeDevice;
		if(device == nil){
			ENLog(@"start test bp");
			return;
		}
		
		[bpDevice  startTest];
	}
	
}

	//停止血压测量
RCT_EXPORT_METHOD(stopTestBP:(NSString *)uuid){
	NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:uuid];
	BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
	ENBPDevice *bpDevice = (ENBPDevice *)device.nativeDevice;
	if(device == nil){
		ENLog(@"stop test bp");
		return;
	}
	
	[bpDevice  stopTest];
}

/** 请求血压电量 */
RCT_EXPORT_METHOD(getBPBatteryValue:(NSString *)uuid){
	NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:uuid];
	BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
	ENPangaoBPDevice *bpDevice = (ENPangaoBPDevice *)device.nativeDevice;
	if(device == nil){
		ENLog(@"stop test bp");
		return;
	}
	
	[bpDevice  sendGetBatteryValue];
}

RCT_REMAP_METHOD(getConnectedBP,
				 BPResolver:(RCTPromiseResolveBlock)resolve
				 BPRejecter:(RCTPromiseRejectBlock)reject){
	@synchronized (self) {
		NSArray *devices = [_deviceManager getSearchedDevices];
		NSMutableArray *bpDevices = [[NSMutableArray alloc]initWithCapacity:10];
		
		for(BLEDevice *device in devices){
			if(!([[device getDeviceName] hasPrefix:@"RBP"] ||
				 [[device getDeviceName] hasPrefix:@"ClinkBlood"])){
				continue;
			}
			
			ConnectStatus status = device.connectStatus;
			if(status != DeviceConnectedStatus && status != DeviceConnectingStatus){
				continue;
			}
			
			NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10];
			[info setObject:[device getDeviceName] forKey:@"deviceName"];
			[info setObject:[[device getDeviceUUID] UUIDString] forKey:@"deviceMac"];
			[bpDevices addObject:info];
		}
		
		resolve(bpDevices);
	}
}

#pragma mark -
#pragma mark 血糖代理
-(void)getResult:(NSDictionary *)result WithDevice:(BLEDevice *)device{
	@synchronized (self) {
		NSString *glucoseValue = nil;
        NSString *resultType = @"glucose";
		NSNumber *checkTimeFlagNumber;
		NSDate *curDate = [NSDate date];
		
		NSString *deviceName  = [device getDeviceName];
			//	NSString *uuid = [[device getUUID] UUIDString];
		if([deviceName hasPrefix:@"BLE-ENUO"]){
            if([result[@"flag"]intValue]>=4096){
                float value = [result[@"Glucose"] floatValue]/10+0.05;
                glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
                resultType = @"ketone";
            }else{
                float value = [result[@"Glucose"] floatValue]/18+0.05;
                glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
                resultType = @"glucose";

            }
            
			float value = [result[@"Glucose"] floatValue]/18+0.05;
			glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
			NSString *checkTimeString = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",[result objectForKey:@"year"], [result objectForKey:@"month"],[result objectForKey:@"date"],[result objectForKey:@"hour"],[result objectForKey:@"minute"]];// yyyy-MM-dd HH:mm
			checkTimeFlagNumber = @([RNMethodModule getLongLongTimeIntervalWithStrDate:checkTimeString]);
			
        }else if([deviceName hasPrefix:@"ENUO-G"]){
            resultType = @"glucose";
            glucoseValue =result[@"displayValue"];
            NSString *checkTimeString = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",[result objectForKey:@"year"], [result objectForKey:@"month"],[result objectForKey:@"date"],[result objectForKey:@"hour"],[result objectForKey:@"minute"]];// yyyy-MM-dd HH:mm
            checkTimeFlagNumber = @([RNMethodModule getLongLongTimeIntervalWithStrDate:checkTimeString]);
        }else{
			float value = [result[@"Glucose"] floatValue];
			glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
			
			checkTimeFlagNumber = @([RNMethodModule getLongLongTimeIntervalWithDate:curDate]);
		}
		
		
		NSString *content = [NSString stringWithFormat:@"time:%@ /n血糖值:%@",
							 [NSDate date],glucoseValue];
		NSLog(@"result:%@",content);
		NSDictionary *body = @{
							   @"deviceName":[device getDeviceName],
							   @"deviceMac":[[device getUUID] UUIDString],
							   @"deviceStatusDescription":@"测量成功",
							   @"deviceStatus":@"result",
							   @"time":[[NSDate date] description],
                               @"resultType":resultType,
							   @"value":result[@"Glucose"],
							   @"displayValue":glucoseValue,
							   @"deviceTime":[NSString stringWithFormat:@"%@",checkTimeFlagNumber]
							   };
		
			//	[self sendEventWithName:@"RESULT_BT_DEVICE"	body:body];
		[self.bridge.eventDispatcher sendAppEventWithName:@"RESULT_BT_DEVICE"													body:body];
	}
}

#pragma mark 血压
/** 血压连接成功 */
-(void)onConnectedBP{
	ENLog(@"连接成功.");
}

/** 获得电池电量 */
-(void)onBatteryPower:(unsigned long)power{
	NSLog(@"电池电量:%ld",power);
}

/** 得到测量结果 */
-(void)onResult:(NSDictionary *)result WithDevice:(BLEDevice *)device{
	NSLog(@"血压结果:%@",result);
	
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"测量成功",
						   @"deviceStatus":@"result",
						   @"pul":result[@"pul"],
						   @"dia":result[@"dia"],
						   @"sys":result[@"sys"]
						   };
	
	
		//	[self sendEventWithName:@"RESULT_BT_DEVICE"	body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"RESULT_BP_BT_DEVICE"													body:body];
	
}

/** 得到测量  */
-(void)onProgressValue:(NSInteger)value IsHeart:(Boolean)isHeart WithDevice:(BLEDevice *)device{
	NSLog(@"测量过程:%ld",(long)value);
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"测量过程",
						   @"deviceStatus":@"receivingData",
						   @"value":@(value)
						   };
	
	
		//	[self sendEventWithName:@"RECEIVING_DATA_BT_DEVICE"	body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"RECEIVING_DATA_BP_BT_DEVICE"													body:body];
	
	
}

/** 得到错误数据 */
-(void)onError:(NSDictionary *)error WithDevice:(BLEDevice *)device{
	NSLog(@"错误:%@",error);
	
//	NSString *errorDescription = [NSString stringWithFormat:@"测量错误:%@",error];
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"errorCode":error[@"errorCode"],
						   @"errorDescription":error[@"error"],
						   @"deviceStatus":@"BPDeviceError"
						   };
	
	
		//	[self sendEventWithName:@"ERROR_BT_DEVICE" body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"BP_DEVICE_ERROR"													body:body];
	
}

/** 开始测量  */
-(void)onStartTestWithDevice:(BLEDevice *)device{
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"bp start test",
						   @"deviceStatus":@"start.test"
						   };
	[self.bridge.eventDispatcher sendAppEventWithName:@"BP_START_TEST"												body:body];
}

/** 停止测量  */
-(void)onStopTestWithDevice:(BLEDevice *)device{
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"bp stop test",
						   @"deviceStatus":@"stop.test"
						   };
	[self.bridge.eventDispatcher sendAppEventWithName:@"BP_STOP_TEST"												body:body];
}

/** 停止浮零 */
-(void)onStopZeroWithDevice:(BLEDevice *)device{
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"bp stop test",
						   @"deviceStatus":@"stop.zero"
						   };
	[self.bridge.eventDispatcher sendAppEventWithName:@"BP_STOP_ZERO"												body:body];
}

/** 获取电量 */
-(void)onPower:(int)power WithDevice:(BLEDevice *)device{
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"bp power",
						   @"deviceStatus":@"device.power",
						   @"value":[[NSNumber numberWithInt:power] stringValue]
						   };
	[self.bridge.eventDispatcher sendAppEventWithName:@"BP_POWER"												body:body];
}

/** 血压计发送关机指令 */
-(void)onDeviceShutDownWithDevice:(BLEDevice *) device{
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"bp shut down",
						   @"deviceStatus":@"device.power.shut.down"
						   };
	[self.bridge.eventDispatcher sendAppEventWithName:@"DEVICE_SHUT_DOWN"												body:body];

}


-(void)onCheckConnectFinishWithDevice:(BLEDevice *)device Status:(BOOL)isSuc{
	if(!isSuc){
		return;
	}
	
	NSDictionary *body =@{
						  @"deviceName":[device getDeviceName],
						  @"deviceMac":[[device getUUID] UUIDString],
						  @"deviceStatusDescription":@"连接成功",
						  @"deviceStatus":@"connectSuc"
						  };
	[self.bridge.eventDispatcher sendAppEventWithName:@"CONNECTED_BT_DEVICE"													body:body];
}




#pragma mark 血脂
-(void)onCholesterolResult:(NSDictionary *)result WithDevice:(BLEDevice *)device{
		//	@"chol":dataArr[0],
		//	@"hdl":dataArr[1],
		//	@"trig":dataArr[2],
		//	@"ldl":dataArr[3]
	NSString *cholesterolResult = [NSString stringWithFormat:@"chol:%@ hdl:%@ trig:%@ ldl:%@",result[@"chol"],result[@"hdl"],result[@"trig"],result[@"ldl"]];
	NSLog(@"血脂结果:%@",cholesterolResult);
	
	NSDictionary *body = @{
						   @"deviceName":[device getDeviceName],
						   @"deviceMac":[[device getUUID] UUIDString],
						   @"deviceStatusDescription":@"测量成功",
						   @"deviceStatus":@"result",
						   @"time":[[NSDate date] description],
						   @"chol":result[@"chol"],
						   @"hdl":result[@"hdl"],
						   @"trig":result[@"trig"],
						   @"ldl":result[@"ldl"]
						   };
	
	
		//	[self sendEventWithName:@"RESULT_BT_DEVICE"	body:body];
	[self.bridge.eventDispatcher sendAppEventWithName:@"RESULT_BT_DEVICE"													body:body];
}

//synchronized public void connectCardReader(final String deviceMac, final Promise promise) {
#pragma mark -
#pragma mark 身份证读卡器
RCT_REMAP_METHOD(startCardReaderScan,
				 startCardResolve:(RCTPromiseResolveBlock)resolve
				 startCardReject:(RCTPromiseRejectBlock)reject){
	[_deviceManager setSearchedDeviceType:ENSearchedAllType];
	_deviceManager.deviceManagerDelegate = self;
	[_deviceManager startScan];
	_startCardResolve = resolve;
}

RCT_REMAP_METHOD(stopCardReaderScan,
				 endCardResolve:(RCTPromiseResolveBlock)resolve
				 endCardReject:(RCTPromiseRejectBlock)reject){
	dispatch_async([_deviceManager getPostQueue], ^{
		[_deviceManager stopScan];
		_endCardResolve = resolve;
#if TARGET_IPHONE_SIMULATOR//模拟器
		
#elif TARGET_OS_IPHONE//真机
//		[_bletool disconnectBt];
#endif
		
			//		if(!_cardDevice){
			//			reject(@"400",@"no device",nil);
			//			return;
			//		}
			//
			//		[_bletool disconnectBt];
		
		resolve(@"disconnect");
	});
	
}

RCT_EXPORT_METHOD(connectCardReader:(NSString *)uuid
				  connectCardResolve:(RCTPromiseResolveBlock)resolve
				  connectCardReject:(RCTPromiseRejectBlock)reject){
	@synchronized ([NSDate date]) {
		NSLog(@"connect card reader");
		NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:uuid];
		BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
		if(device == nil){
			NSLog(@"stop test bp");
			return;
		}
		
		
		
#if TARGET_IPHONE_SIMULATOR//模拟器
		
#elif TARGET_OS_IPHONE//真机
//		[_bletool connectBt:[device getPeripheral]];
#endif
		
		_cardDevice = device;
		_connectCardResolve = resolve;
		_connectCardReject = reject;
	}
	
	
}


-(void)BR_connectResult:(BOOL)isconnected{
	@synchronized ([NSDate date]) {
		if(!isconnected){
			NSDictionary *body =@{
								  @"deviceName":[_cardDevice getDeviceName],
								  @"deviceMac":[[_cardDevice getUUID] UUIDString],
								  @"deviceStatus":@"disconnect"
								  };
			[_deviceManager removeDevice:_cardDevice];
			[self.bridge.eventDispatcher sendAppEventWithName:@"DISCONNECT_BT_DEVICE"													body:body];
			return;
		}
		
		
		if(!_connectCardResolve){
#if TARGET_IPHONE_SIMULATOR//模拟器
			
#elif TARGET_OS_IPHONE//真机
//			[_bletool disconnectBt];
#endif
			return;
		}
		
		_connectCardResolve(@"connected");
		_startCardResolve =nil;
		_connectCardResolve = nil;
		_connectCardReject = nil;
	}
	
	
}
RCT_EXPORT_METHOD(disconnectDevice:(NSString *)deviceMac){
	@synchronized (self) {
		NSUUID *myUUID = [[NSUUID alloc] initWithUUIDString:deviceMac];
		BLEDevice *device = [_deviceManager getDeviceWithUUID:myUUID];
		
		if(!device){
			return;
		}
		
		[device disconnect];
	}
}



/** 开始服务 */
RCT_REMAP_METHOD(readCard,
				 readCardResolver:(RCTPromiseResolveBlock)resolve
				 readCardRejecter:(RCTPromiseRejectBlock)reject){
	dispatch_async([_deviceManager getPostQueue], ^{
#if TARGET_IPHONE_SIMULATOR//模拟器
		
#elif TARGET_OS_IPHONE//真机
//		if(!_bletool){
//			reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]);
//			return;
//		}
//		
//		NSDictionary *obj = [_bletool readCard];
//		if(!obj){
//			reject(@"400",@"no device",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]);
//			return;
//		}
//		
////		NSMutableString *resultContent = [[NSMutableString alloc] init];
//		
//		NSInteger resultFlag = [obj[@"resultFlag"] integerValue];
//		if(resultFlag == -1){
//			reject(@"400",@"no data",[NSError errorWithDomain:@"device" code:400 userInfo:@{}]);
//		}else{
//			NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10];
//			
//			[info setObject:obj[@"partyName"] forKey:@"name"];
//			[info setObject:obj[@"certAddress"] forKey:@"address"];
//			[info setObject:obj[@"bornDay"] forKey:@"birth"];
//			[info setObject:obj[@"expDate"] forKey:@"end"];
//			[info setObject:obj[@"certNumber"] forKey:@"idNo"];
//			[info setObject:obj[@"nation"] forKey:@"nation"];
//			[info setObject:obj[@"certOrg"] forKey:@"police"];
//			[info setObject:obj[@"gender"] forKey:@"sex"];
//			[info setObject:obj[@"effDate"] forKey:@"start"];
//			
//			resolve([info copy]);
//		}
#endif
		
		
	});
}

	// 根据日期字符串yyyy-MM-dd HH:mm获取整形的毫秒时间戳，后三位为000
+ (long long)getLongLongTimeIntervalWithStrDate:(NSString *)strDate{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
	
	NSDate *currentDate = [dateFormatter dateFromString:strDate];
	return [RNMethodModule getLongLongTimeIntervalWithDate:currentDate];
}

	// 根据日期date 获取整形的毫秒时间戳，后三位为000
+ (long long)getLongLongTimeIntervalWithDate:(NSDate *)date{
	long long longtimeInterval = (long long)[date timeIntervalSince1970] * 1000;
	return longtimeInterval;
}

//开始扫描血糖
RCT_EXPORT_METHOD(startScanDynamicGlucose){
    @synchronized (self) {
        [_deviceManager setSearchedDeviceType:ENSearchedAllType];
        _deviceManager.deviceManagerDelegate = self;
        [_deviceManager startScan];
    }
}

//停止扫描血糖
RCT_EXPORT_METHOD(stopScanDynamicGlucose){
    @synchronized (self) {
        [_deviceManager setSearchedDeviceType:ENSearchedAllType];
        //    _deviceManager.deviceManagerDelegate = nil;
        [_deviceManager stopScan];
    }
}




@end
