//
//  ELWIFIBloodPressureVC.m
//  AILinkBleSDK_Example
//
//  Created by LarryZhang on 2023/10/6.
//  Copyright © 2023 zhengzida. All rights reserved.
//

#import "ELWIFIBloodPressureVC.h"
#import <AILinkBleSDK/ELAILinkBleManager.h>
#import <AILinkBleSDK/ELBluetoothManager+BleWifi.h>
#import <AILinkBleSDK/ElBloodBleWifiManager.h>
#import <AILinkBleSDK/ELbloodPresureBleWifiDataModel.h>
#import "ELBfsWifiConnectTableViewCell.h"

@interface ELWIFIBloodPressureVC () <ELBluetoothManagerDelegate, ElBleWifiDelegate, ELBloodBleWifiManagerDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITextField *urlTexField;
@property (weak, nonatomic) IBOutlet UITextField *portTexField;
@property (weak, nonatomic) IBOutlet UITextField *pathTexField;

@property (weak, nonatomic) IBOutlet UILabel *bleStatusLabel;

@property (weak, nonatomic) IBOutlet UITextView *logTextView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<ELBleWifiDetailModel *> *dataSource;

@end

@implementation ELWIFIBloodPressureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [ElBloodBleWifiManager shareManager].delegate = self;
    [ElBloodBleWifiManager shareManager].bleWifiDelegate = self;
    [ElBloodBleWifiManager shareManager].bloodDelegate = self;
    [[ElBloodBleWifiManager shareManager] startScanFilterCids:@[@(ELSupportDeviceTypeBLE_WIFIBlood)]];
    NSString *log = @"开始扫描";
    [self addLog:log];
    
    self.urlTexField.text = self.defaultURL;//@"iot.elink.com";
    self.portTexField.text = self.defaultPort;//@"80";
    self.pathTexField.text = self.defaultPath;//@"";
    
    self.dataSource = [NSMutableArray array];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [[ElBloodBleWifiManager shareManager] stopScan];
    [[ElBloodBleWifiManager shareManager] disconnectPeripheral];
    [ElBloodBleWifiManager shareManager].delegate = nil;
    [ElBloodBleWifiManager shareManager].bleWifiDelegate = nil;
    [ElBloodBleWifiManager shareManager].bloodDelegate = nil;
}

#pragma mark - Action

- (IBAction)requestWifiNameAction:(id)sender {
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiName];

    NSString *log = @"获取当前 wifi 名称";
    [self addLog:log];
}

- (IBAction)requestDeviceStatusAcion:(id)sender {
    //获取蓝牙和WiFi连接状态
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeGetConnectState)];
    
    NSString *log = [NSString stringWithFormat:@"获取蓝牙和WiFi连接状态"];
    [self addLog:log];
}

- (IBAction)requestWifiListAction:(id)sender {
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetNearbyWifi];
    
    NSString *log = @"获取 附近的 WIFI 列表";
    [self addLog:log];
}

- (IBAction)setupServerInfoAcion:(id)sender {
    NSString *url = self.urlTexField.text;
    NSString *port = self.portTexField.text;
    NSString *path = self.pathTexField.text;
    
    self.defaultURL = url;
    self.defaultPort = port;
    self.defaultPath = path;
    
    [[ElBloodBleWifiManager shareManager] setDevAccessIpAddress:url portNumber:port.intValue path:path];
    
    NSString *log = @"设置 服务器信息";
    [self addLog:log];
}

- (IBAction)requestServerInfoAcion:(id)sender {
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetURL];
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetPort];
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetPathAddress];
    
    NSString *log = @"获取 服务器信息";
    [self addLog:log];
}

- (IBAction)requestDeviceIdAcion:(id)sender {
    //获取wifi设备的SN号，即设备id
    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetSNNumber];
    
    NSString *log = @"获取 设备ID";
    [self addLog:log];
}

- (IBAction)switchUintAction:(id)sender {
    static BOOL value = YES;
    if (value) {
        [[ElBloodBleWifiManager shareManager] changeUnit:ELDeviceBloodPressureUnit_mmhg];
        
        NSString *log = @"设置单位 mmhg";
        [self addLog:log];
    } else {
        [[ElBloodBleWifiManager shareManager] changeUnit:ELDeviceBloodPressureUnit_kPa];
        
        NSString *log = @"设置单位 kPa";
        [self addLog:log];
    }
    value = !value;
}

- (IBAction)switchSpeechAtion:(id)sender {
    static BOOL value = YES;
    if (value) {
        [[ElBloodBleWifiManager shareManager] sendSwitchVoice:ELBloodBleSwitchVoiceTypeOn];
        
        NSString *log = @"打开 语音";
        [self addLog:log];
    } else {
        [[ElBloodBleWifiManager shareManager] sendSwitchVoice:ELBloodBleSwitchVoiceTypeOff];
        
        NSString *log = @"关闭 语音";
        [self addLog:log];
    }
    value = !value;
}

- (IBAction)startMeasureAction:(id)sender {
    [[ElBloodBleWifiManager shareManager] sendInteractiveInstructions:ELBloodInteractionTypeStartTest];
    
    NSString *log = @"开始 测量";
    [self addLog:log];
}

- (IBAction)stopMeasureAction:(id)sender {
    [[ElBloodBleWifiManager shareManager] sendInteractiveInstructions:ELBloodInteractionTypeStopTest];
    
    NSString *log = @"停止 测量";
    [self addLog:log];
}

- (IBAction)restoreFactoryAction:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"恢复出厂设置" message:@"确认要恢复出厂设置吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了确认按钮");
        
        [[ElBloodBleWifiManager shareManager] setFactoryDataReset];
        NSString *log = @"恢复出厂设置";
        [self addLog:log];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消按钮");
    }];
    
    [alert addAction:conform];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (IBAction)clearAction:(id)sender {
    self.logTextView.text = @"";
}

- (IBAction)shareLogAction:(id)sender {
}

#pragma mark -

- (NSString *)defaultURL {
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"defaultURL"];
}

- (void)setDefaultURL:(NSString *)defautlURL {
    [[NSUserDefaults standardUserDefaults] setObject:defautlURL forKey:@"defaultURL"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)defaultPort {
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"defaultPort"];
}

- (void)setDefaultPort:(NSString *)defaultPort {
    [[NSUserDefaults standardUserDefaults] setObject:defaultPort forKey:@"defaultPort"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)defaultPath {
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"defaultPath"];
}

- (void)setDefaultPath:(NSString *)defaultPath {
    [[NSUserDefaults standardUserDefaults] setObject:defaultPath forKey:@"defaultPath"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
    
#pragma mark - textField Delegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 119) {
        NSLog(@"%@",textField.text);
        //MARK:7.再发送配置wifi的密码的指令
        [[ElBloodBleWifiManager shareManager] bleWifiSetWifiPwd:textField.text];
    }
}

#pragma mark - tableView Delegate And DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"ELBfsWifiConnectTableViewCell";
    ELBfsWifiConnectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[ELBfsWifiConnectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    ELBleWifiDetailModel *model = self.dataSource[indexPath.row];
    
    cell.wifiName = model.wifiName;
    if (model.wifiState == ELBleWifiUseStateConnected) {
        cell.isLink = YES;
    } else {
        cell.isLink = NO;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ELBleWifiDetailModel *model = self.dataSource[indexPath.row];
    
    //MARK:5.先发送配置wifi的mac地址的指令
    [[ElBloodBleWifiManager shareManager] bleWifiSetConnectWifiMac:model.macData];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入wifi密码" message:model.wifiName preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了确认按钮");
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消按钮");
    }];
    //MARK:6.输入wifi密码
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"密码";
        textField.delegate = self;
        textField.tag = 119;
    }];
    
    [alert addAction:conform];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - ELBluetoothManagerDelegate

/**
 Callback Bluetooth status(回调蓝牙状态)
 @param state Bluetooth status(蓝牙状态)
 */
-(void)bloodBleManagerUpdateBleState:(ELBluetoothState)state {
    NSLog(@"## bluetoothManagerUpdateBleState = %ld", state);
    if (state == ELBluetoothStateScaning) {
        self.bleStatusLabel.text = @"正在连接...";
//        NSString *log = @"正在连接...";
//        [self addLog:log];
    } else if (state == ELBluetoothStateDidValidationPass) {
        self.bleStatusLabel.text = [@"连接成功 " stringByAppendingString:self.per.macAddressString];
        NSString *log = [@"连接成功 " stringByAppendingString:self.per.macAddressString];
        [self addLog:log];
        
//        //获取蓝牙和WiFi连接状态
//        [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeGetConnectState)];
//        log = [NSString stringWithFormat:@"获取蓝牙和WiFi连接状态"];
//        [self addLog:log];
    } else if (state == ELBluetoothStateDidDisconnect) {
        self.bleStatusLabel.text = @"连接已断开";
        NSString *log = @"连接已断开";
        [self addLog:log];
    } else {
//        self.bleStatusLabel.text = @"";
    }
}

/**
 Callback scanned device(回调扫描到的设备)
 @param devices 设备
 */
- (void)bloodBleManagerScanDevices:(NSArray<ELPeripheralModel *> *_Nullable)devices {
    NSLog(@"## bloodBleManagerScanDevices = %@", devices);
    for (int i = 0; i < devices.count; i++) {
        ELPeripheralModel *device = devices[i];
        if ([device.macAddress isEqualToString:self.per.macAddressString]) {
            [[ElBloodBleWifiManager shareManager] stopScan];
            
            [[ElBloodBleWifiManager shareManager] connectPeripheral:device];
            return;
        }
    }
}

#pragma mark - ElBleWifiDelegate

/**
 Callback Wifi details(回调Wifi详情)
 @param model 模型
 */
- (void)bleWifiReceiveWifiDetailModel:(ELBleWifiDetailModel *)model {
    NSLog(@"## bleWifiReceiveWifiDetailModel");
//    [self addLog:[NSString stringWithFormat:@"wifi type---%lu name---%@ link state--%zd",(unsigned long)model.wifiState,model.wifiName,model.wifiState]];
    //    MARK:3.WiFi配置得到Wifi列表
    if (model.wifiName.length > 0) {
        [self.dataSource addObject:model];
    }
    [self.tableView reloadData];
}

/**
Scan nearby wifi results(扫描附近wifi结果)
 @param count Number of nearby wifi(附近wifi数量)
 */
- (void)bleWifiReceiveScanedWifiCount:(int)count {
    NSLog(@"## bleWifiReceiveScanedWifiCount() count:%@", @(count));
    //MARK:4.WiFi配置得到一个附近wifi的列表，点击选择一个wifi，进行配置
    [self.tableView reloadData];
}

/**
 Callback Wifi MAC address(回调Wifi MAC地址)
 @param macData mac
 */
- (void)bleWifiReceiveWifiMacData:(NSData *_Nullable)macData {
    NSLog(@"## bleWifiReceiveWifiMacData");
}

/**
Callback WIFI password(回调WIFI密码)
 @param pwd password(密码)
 */
- (void)bleWifiReceiveWifiPwd:(NSString *_Nonnull)pwd {
    NSLog(@"## bleWifiReceiveWifiPwd");
}

/**
 Get DTIM interval (unit: ms)(获取DTIM间隔(单位:ms))
 @param interval Interval (unit: ms)(间隔(单位:ms))
 */
- (void)bleWifiReceiveWifiDTIMInterval:(NSInteger)interval {
    NSLog(@"## bleWifiReceiveWifiDTIMInterval");
}

/**
 Returns the visited URL(返回访问的url)
 @param url url
 */
- (void)bleWifiReceiveWifiAccessURL:(NSString *)url {
    NSLog(@"## bleWifiReceiveWifiAccessURL() url:%@", url);
    
    NSString *log = [NSString stringWithFormat:@"url:%@", url];
    [self addLog:log];
}

/**
  Call back wifi port number(回调wifi的端口号)
 @param port 端口号
 */
- (void)bleWifiReceiveWifiPort:(int)port {
    NSLog(@"## bleWifiReceiveWifiPort() port:%@", @(port));
    NSString *log = [NSString stringWithFormat:@"port:%@", @(port)];
    [self addLog:log];
}

//Returns the visited path(返回访问的path)
- (void)bleWifiReceiveWifiPath:(NSString *)path {
    NSLog(@"## bleWifiReceiveWifiPath() path:%@", path);
    
    NSString *log = [NSString stringWithFormat:@"path:%@", path];
    [self addLog:log];
}

/**
 Set or query the callback of the instruction execution result（设置指令蓝牙WIFI响应回调方法）
 只支持蓝牙Wifi部分枚举
 @param type Type of setting （设置的类型）
 @param result Set result（设置的结果）
 */
- (void)bleWifiReceiceResponseType:(ELInetSetCmdType)type result:(ELSetBluetoothResponseType)result {
    NSLog(@"## bleWifiReceiceResponseType");
    
    if (result == ELSetBluetoothResponseTypeSuccess) {
        //设置WiFi结果
        if (type == ELInetSetCmdTypeBleWifiSetWifiMac) {
            
        } else if (type == ELInetSetCmdTypeBleWifiSetWifiPwd){
            //MARK:8.然后发起连接Wifi
            [[ElBloodBleWifiManager shareManager] bleWifiSetupWifiConnect:YES];
        } else if (type == ELInetSetCmdTypeBleWifiSetConnectWifi){
            //获取连接状态,更新Wi-Fi列表
//            [self.dataSource removeAllObjects];
//            [self.tableView reloadData];
//            [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetNearbyWifi];
        }
    } else {
        //TODO:Wifi配置过程中失败的情况自行处理
    }
}

/**
 获取会话码(deviceId)

 @param code (deviceId) deviceId(0 means no:为0时表示不存在)
 */
- (void)bleWifiReceiveWifiSNCode:(int)code {
    NSLog(@"## bleWifiReceiveWifiSNCode() code:%@", @(code));
    if (code == 0) {
        //失败
    }
    
    NSString *log = [NSString stringWithFormat:@"会话码(deviceId): %@", @(code)];
    [self addLog:log];
}

/** 返回wifi名称 */
- (void)bleWifiName:(NSString *)wifiName {
    NSLog(@"## bleWifiName() wifi名称: %@", wifiName);
    
    NSString *log = [NSString stringWithFormat:@"wifi名称: %@", wifiName];
    [self addLog:log];
}

//- (void)bluetoothManagerReceiveMCUConnectedState:(struct ELMCUStateStruct)stateStrct {
//    NSLog(@"## bluetoothManagerReceiveMCUConnectedState");
//    BleWiFiConnectState wifiState = stateStrct.wifiState;
//    
////    //请求会话码
////    [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetSNNumber];
//    //MARK:1.WiFi配置提示用户配网
//    //TODO:注意：wifi配置过程必须保持蓝牙与设备的连接
//    if (wifiState == BleWiFiConnectStateNoWiFi) {
//        //1.如果没有配网，则提示用户去配网
//        //MARK:2.WiFi配置先获取wifi列表
//        [self.dataSource removeAllObjects];
//        [self.tableView reloadData];
//        [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetNearbyWifi];
//        NSString *log = @"获取附近 wifi 列表";
//        [self addLog:log];
//    } else if (wifiState == BleWiFiConnectStateSuccess) {
//        [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiName];
//        
//        NSString *log = @"获取当前 wifi 名称";
//        [self addLog:log];
//    } else {
////        //MARK:2.没网也可以获取Wi-Fi列表，如果需要更新Wi-Fi的话
////        [self.dataSource removeAllObjects];
////        [self.tableView reloadData];
////        [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetNearbyWifi];
//    }
//    
//    ///MARK:9.wifi配置结果
//    //wifi相关的其他指令和数据接收，请查看ELBluetoothManager.h文件
//    if (stateStrct.wifiState == BleWiFiConnectStateSuccess) {
//        //成功
//        //MARK:10.获取wifi设备的SN号，即设备id
//        [[ElBloodBleWifiManager shareManager] getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeBleWifiGetSNNumber];
//    }
//}

-(void)bluetoothManagerReceiveWMState:(ELWMStateStruct)stateStrct {
    NSString *bleString = @"0_无连接";
    if (stateStrct.bleState == WMBleStateConnected) {
        bleString = @"1_已连接";
    } else if (stateStrct.bleState == WMBleStatePaired) {
        bleString = @"2_配对完成";
    }
    
    NSString *wifiString = @"0_未配置AP";
    if (stateStrct.wifiState == WMWiFiStateConnectAPFail) {
        wifiString = @"1_连接AP失败";
    } else if (stateStrct.wifiState == WMWiFiStateConnectServerFail) {
        wifiString = @"2_与服务器通讯失败";
    } else if (stateStrct.wifiState == WMWiFiStateConnectedAP) {
        wifiString = @"3_成功连接上AP";
    } else if (stateStrct.wifiState == WMWiFiStateConnectingAP) {
        wifiString = @"4_正在连接AP";
    }
    
    NSString *workString = @"0_唤醒";
    if (stateStrct.workState == WMWorkStateSleep) {
        workString = @"1_进入休眠";
    } else if (stateStrct.workState == WMWorkStateReady) {
        workString = @"2_模块准备就绪";
    }
    
    NSString *errorString = @"0_未知原因";
    if (stateStrct.failCode == WMWorkStateFailCodeAPSignalBad) {
        errorString = @"1_AP信号差";
    } else if (stateStrct.failCode == WMWorkStateFailCodeWrongPassword) {
        errorString = @"2_密码错误";
    } else if (stateStrct.failCode == WMWorkStateFailCodeNoIP) {
        errorString = @"3_获取不到IP";
    } else {
        errorString = @"";
    }
    
    
    NSLog(@"## bluetoothManagerReceiveMCUConnectedState()模块状态 蓝牙状态: %@, wifi状态: %@, 工作状态: %@ 失败原因: %@", bleString, wifiString, workString, errorString);
    if (errorString.length > 0) {
        NSString *log = [NSString stringWithFormat:@"模块状态 蓝牙状态: %@, wifi状态: %@, 工作状态: %@ 失败原因: %@", bleString, wifiString, workString, errorString];
        [self addLog:log];
    } else {
        NSString *log = [NSString stringWithFormat:@"模块状态\n 蓝牙状态: %@,\n wifi状态: %@,\n 工作状态: %@", bleString, wifiString, workString];
        [self addLog:log];
    }
}

//-(void)bluetoothManagerReceiveWMStateFailCode:(WMWorkStateFailCode)failCode {
//    NSLog(@"## bluetoothManagerReceiveMCUConnectedState");
//    
//}

#pragma mark - ELBloodBleWifiManagerDelegate

/**
 Call back real-time, stable data(回调实时、稳定数据)
 @param model 数据
 @param type 类型
 */
- (void)bloodBleManagerReceiceTestData:(ELbloodPresureBleWifiDataModel *)model type:(ELBloodBleDataModelType)type {
    NSLog(@"## bloodBleManagerReceiceTestData");
    
    static BOOL testEnd = NO;
    
    if (type == ELBloodBleDataModelTypeStable) {
        if (testEnd == NO) {
            testEnd = YES;
        }
        NSString *log = [NSString stringWithFormat:@"收缩压:%@, 舒张压:%@, ", model.sys, model.dia];
        [self addLog:log];
    } else if (type == ELBloodBleDataModelTypeRealTime) {
        testEnd = NO;
        NSString *log = [NSString stringWithFormat:@"压力:%@", model.dia];
        [self addLog:log];
    }
    
}

/**
 Set unit callback(设置单位回调)
 @param type 结果
 */
- (void)bloodBleManagerReceiveSetUnitResult:(ELSetBluetoothResponseType)type {
    NSLog(@"## bloodBleManagerReceiveSetUnitResult() type:%@", @(type));
    if (type == ELSetBluetoothResponseTypeSuccess) {
        NSString *log = @"切换单位 成功";
        [self addLog:log];
    } else if (type == ELSetBluetoothResponseTypeFailure) {
        NSString *log = @"切换单位 失败";
        [self addLog:log];
    } else if (type == ELSetBluetoothResponseTypeNoSupport) {
        NSString *log = @"切换单位 不支持";
        [self addLog:log];
    }
}

/**
 Set the interaction type(设置交互类型)
 @param type 结果
 */
- (void)bloodBleManagerReceiveInteractionType:(ELBloodInteractionType)type {
    NSLog(@"## bloodBleManagerReceiveInteractionType");
    if (type == ELBloodInteractionTypeStartTest) {
        NSString *log = @"设备状态 已开始测量";
        [self addLog:log];
    } else if (type == ELBloodInteractionTypeStopTest) {
        NSString *log = @"设备状态 已停止测量";
        [self addLog:log];
    } else if (type == ELBloodInteractionTypeShutdown) {
        NSString *log = @"设备状态 已关机";
        [self addLog:log];
    } else if (type == ELBloodInteractionTypeBoot) {
        NSString *log = @"设备状态 已开机";
        [self addLog:log];
    }
}

/**
 Error code sent on the device(设备上发错误码)
 @param code error code(错误码)
 */
- (void)bloodBleManagerReceiveFailCode:(ELBloodFailCode)code {
    NSLog(@"## bloodBleManagerReceiveFailCode");
}

/**
 Send voice alarm setting result(下发语音报警设置结果)
 @param type 操作类型
 @param result 结果
 */
- (void)bloodBleManagerReceiveSetSwitchVoiceOperationType:(ELBloodBleSwitchVoiceType)type result:(ELSetBluetoothResponseType)result {
    NSLog(@"## bloodBleManagerReceiveSetSwitchVoiceOperationType");
    if (result == ELSetBluetoothResponseTypeSuccess) {
        if (type == ELBloodBleSwitchVoiceTypeOn) {
            NSString *log = @"语音 打开 成功";
            [self addLog:log];
        }else if (type == ELBloodBleSwitchVoiceTypeOff){
            NSString *log = @"语音 关闭 成功";
            [self addLog:log];
        }
    } else {
        NSString *log = @"语音 设置 失败";
        [self addLog:log];
    }
}

//获取版本号
- (void)bluetoothManagerReceiveBMVersion:(NSString *)bmVersion {
    NSLog(@"%@", bmVersion);
    
    NSString *log = [NSString stringWithFormat:@"模块版本: %@", bmVersion];
    [self addLog:log];
}

#pragma mark - addLog

- (void)addLog:(NSString *)log {
    [self addLog:log newline:YES];
}

- (void)addWithoutNewlineLog:(NSString *)log {
    [self addLog:log newline:NO];
}

- (void)addLog:(NSString *)log newline:(BOOL)newline {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"HH:mm:ss.SSS";
    NSString *time = [format stringFromDate:[NSDate date]];
    if (newline) {
        self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@ %@\n", time, log];
    } else {
        self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@ %@", time, log];
    }
    [self.logTextView scrollRangeToVisible:NSMakeRange(self.logTextView.text.length, 1)];
}

@end
