//
//  BodyScaleVC.m
//  AILinkBleSDKSourceCode
//
//  Created by LarryZhang on 2023/3/27.
//  Copyright © 2020 IOT. All rights reserved.
//

#import <AILinkBleSDK/ELAILinkBleManager.h>
#import <AILinkBleSDK/ELBluetoothManager+Settings.h>
#import <AILinkBleSDK/ELBodyFatScaleBleManager.h>
#import <AILinkBleSDK/ELBodyFatScaleBleUserModel.h>
#import <AILinkBleSDK/ELBodyFatScaleBleWeightModel.h>
#import "BodyScaleVC.h"
#import "Masonry.h"

#import <AILinkBleSDK/ELUnitConvertTool.h>
#import <AILinkBleSDK/OEMAlgorithmSDK.h>

@interface BodyScaleVC () <ELBluetoothManagerDelegate, ELBodyFatScaleBleDelegate>

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, copy) NSArray<NSNumber *> *units;
@end

@implementation BodyScaleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [ELBodyFatScaleBleManager shareManager].delegate = self;
    [ELBodyFatScaleBleManager shareManager].bodyFatScaleDelegate = self;
    [[ELBodyFatScaleBleManager shareManager] startScan];

    [self setupUIView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[ELBodyFatScaleBleManager shareManager] disconnectPeripheral];
}

- (void)dealloc {
}

#pragma mark - Init UI

- (void)setupUIView {
    UIButton *button1 = [UIButton buttonWithType:(UIButtonTypeCustom)];

    [button1 setTitle:@"Get BM Version" forState:(UIControlStateNormal)];
    button1.tag = 1;
    button1.titleLabel.adjustsFontSizeToFitWidth = YES;
    button1.titleLabel.numberOfLines = 2;
    button1.backgroundColor = [UIColor blackColor];
    [button1 addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button1];
    [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(100);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];

    UIButton *button2 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button2 setTitle:@"Get C V P ID" forState:(UIControlStateNormal)];
    button2.tag = 2;
    button2.titleLabel.adjustsFontSizeToFitWidth = YES;
    button2.titleLabel.numberOfLines = 2;
    button2.backgroundColor = [UIColor blackColor];
    [button2 addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button2];
    [button2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(button1.mas_right).mas_offset(10);
        make.top.mas_equalTo(100);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];

    UIButton *button3 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button3 setTitle:@"Get Name" forState:(UIControlStateNormal)];
    button3.tag = 3;
    button3.titleLabel.adjustsFontSizeToFitWidth = YES;
    button3.titleLabel.numberOfLines = 2;
    button3.backgroundColor = [UIColor blackColor];
    [button3 addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button3];
    [button3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(button2.mas_right).mas_offset(10);
        make.top.mas_equalTo(100);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    //
    UIButton *button4 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button4 setTitle:@"Set Name" forState:(UIControlStateNormal)];
    button4.tag = 4;
    button4.titleLabel.adjustsFontSizeToFitWidth = YES;
    button4.titleLabel.numberOfLines = 2;
    button4.backgroundColor = [UIColor blackColor];
    [button4 addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button4];
    [button4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.equalTo(button1.mas_bottom).mas_offset(10);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    //
    UIButton *button5 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button5 setTitle:@"Change unit" forState:(UIControlStateNormal)];
    button5.tag = 5;
    button5.titleLabel.adjustsFontSizeToFitWidth = YES;
    button5.titleLabel.numberOfLines = 2;
    button5.backgroundColor = [UIColor blackColor];
    [button5 addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button5];
    [button5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(button4.mas_right).mas_offset(10);
        make.top.equalTo(button1.mas_bottom).mas_offset(10);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    //
    self.textView = [[UITextView alloc] init];
    self.textView.backgroundColor = [UIColor blackColor];
    self.textView.text = @"Log";
    self.textView.textColor = [UIColor redColor];
    [self.view addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.bottom.mas_equalTo(-10);
        make.top.equalTo(button5.mas_bottom).mas_offset(10);
    }];
}

#pragma mark - Action

- (void)buttonAction:(UIButton *)sender {
    if ([ELBodyFatScaleBleManager shareManager].state != ELBluetoothStateDidValidationPass) {
        [self addLog:@"Disconnected"];
        return;
    }

    [self addLog:sender.titleLabel.text];
    NSInteger tag = sender.tag;

    if (tag == 1) {
        //getBluetoothInfoWithELInetGetCmdType是获取设备信息的方法
        [[ELBodyFatScaleBleManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeGetBMVersion)];
    } else if (tag == 2) {
        [[ELBodyFatScaleBleManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeGetC_V_P_ID)];
    } else if (tag == 3) {
        [[ELBodyFatScaleBleManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeGetName)];
    } else if (tag == 4) {
        [[ELBodyFatScaleBleManager shareManager] setBluetoothName:@"AILink"];
    } else if (tag == 5) {
        if (self.units.count == 0) {
            [self addLog:@"No units obtained"];
            return;
        }

//        [[ELBodyFatScaleBleManager shareManager] changeBodyFatScaleUnit:(ELDeviceWeightUnit_KG)];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Change Unit" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];

        for (int i = 0; i < self.units.count; i++) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:AiLinkBleWeightUnitDic[self.units[i]]
                                                             style:(UIAlertActionStyleDefault)
                                                           handler:^(UIAlertAction *_Nonnull action) {
                [[ELBodyFatScaleBleManager shareManager] changeBodyFatScaleUnit:self.units[i].integerValue];
            }];
            [alert addAction:action];
        }

        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - ELBodyFatScaleBleDelegate

- (void)bodyFatScaleManagerScanDevices:(NSArray<ELPeripheralModel *> *)scaleDevices {
    for (ELPeripheralModel *per in scaleDevices) {
        if ([per.macAddress isEqualToString:self.per.macAddressString]) {
            [[ELBodyFatScaleBleManager shareManager] stopScan];
            
            [[ELBodyFatScaleBleManager shareManager] connectPeripheral:per];
        }
    }
}

- (void)bodyFatScaleManagerUpdateState:(ELBluetoothState)state {
    switch (state) {
        case ELBluetoothStateUnavailable: {
            self.title = @"Please open the bluetooth";
        }
        break;

        case ELBluetoothStateAvailable: {
            self.title = @"Bluetooth is open";
        }
        break;

        case ELBluetoothStateScaning: {
            self.title = @"Scaning";
        }
        break;

        case ELBluetoothStateConnectFail: {
            self.title = @"Connect fail";
        }
        break;

        case ELBluetoothStateDidDisconnect: {
            self.title = @"Disconnected";
        }
        break;

        case ELBluetoothStateDidValidationPass: {
            self.title = @"Connected";
            //获取设备支持的单位
            [[ELBodyFatScaleBleManager shareManager] getBluetoothInfoWithELInetGetCmdType:(ELInetGetCmdTypeReadDeviceSupportUnit)];
            //将你自己设置的单位发给秤
            ELDeviceWeightUnit unit = ELDeviceWeightUnit_KG;
            [[ELBodyFatScaleBleManager shareManager] changeBodyFatScaleUnit:unit];
        }
        break;

        case ELBluetoothStateFailedValidation: {
            self.title = @"Illegal equipment";
        }
        break;

        case ELBluetoothStateWillConnect:
            self.title = @"Connecting";
            break;

        default:
            break;
    }
}

- (void)bluetoothManagerReceiceResponseType:(ELInetSetCmdType)type result:(ELSetBluetoothResponseType)result {
    if (type == ELInetSetCmdTypeSetName) {
        if (result == ELSetBluetoothResponseTypeSuccess) {
            [self addLog:@"Set name Success "];
        } else if (result == ELSetBluetoothResponseTypeFailure) {
            [self addLog:@"Set name failure "];
        } else if (result == ELSetBluetoothResponseTypeNoSupport) {
            [self addLog:@"Set name unsupport "];
        }
    }
}

- (void)bluetoothManagerReceiceName:(NSString *)name {
    [self addLog:name];
}

- (void)bluetoothManagerReceiveDID:(struct ELDIDStruct)did {
    [self addLog:[NSString stringWithFormat:@"CID = %lu, VID = %d, PID = %d", (unsigned long)did.deviceType, did.vendorID, did.productID]];
}

- (void)bluetoothManagerReceiveBMVersion:(NSString *)bmVersion {
    [self addLog:bmVersion];
}

- (void)bluetoothManagerBackDeviceSupportUnitWithWeight:(NSArray<NSNumber *> *)weightArray Height:(NSArray<NSNumber *> *)heightArray Temperature:(NSArray<NSNumber *> *)temperatureArray BloodPressure:(NSArray<NSNumber *> *)bloodPressureArray Pressure:(NSArray<NSNumber *> *)pressureArray {
    //这里只要体重数据
    self.units = weightArray;
}

/**
   Callback to set unit result(回调设置单位结果)

   @param result 结果
 */
- (void)bodyFatScaleManagerCallBackSetUnitResult:(ELSetBluetoothResponseType)result {
    switch (result) {
        case ELSetBluetoothResponseTypeSuccess: {
            [self addLog:@"Change Unit Success"];
        }
        break;

        case ELSetBluetoothResponseTypeFailure: {
            [self addLog:@"Change Unit Failure"];
        }
        break;

        case ELSetBluetoothResponseTypeNoSupport: {
            [self addLog:@"Unsupport Change Unit"];
        }
        break;

        default:
            break;
    }
}

/**
   Return weight and body fat model(返回重量及体脂model)
 */
- (void)bodyFatScaleManagerCallBackWeight:(ELBodyFatScaleBleWeightModel *)weightModel state:(BodyFatScaleMeasureStatus)status {
    switch (status) {
        case BodyFatScaleMeasureStatus_Unstable: {
            [self addLog:[NSString stringWithFormat:@"Unstable data weight = %ld unit = %@ point = %ld", weightModel.weight, AiLinkBleWeightUnitDic[@(weightModel.weightUnit)], weightModel.weightPoint]];
        }
        break;

        case BodyFatScaleMeasureStatus_Stable: {
            [self addLog:[NSString stringWithFormat:@"Stable data weight = %ld unit = %@ point = %ld", weightModel.weight, AiLinkBleWeightUnitDic[@(weightModel.weightUnit)], weightModel.weightPoint]];
        }
        break;

        case BodyFatScaleMeasureStatus_Failed: {
            [self addLog:@"Test failure"];
        }
        break;

        case BodyFatScaleMeasureStatus_Complete: {
            [self addLog:[NSString stringWithFormat:@"Tested weight = %ld unit = %@ point = %ld", weightModel.weight, AiLinkBleWeightUnitDic[@(weightModel.weightUnit)], weightModel.weightPoint]];
            NSLog(@"weightModel:%@", weightModel);
            
            //App算法
            [self algorithmWithBleModel:weightModel user:self.getOneUser];
        }
        break;

        default:
            break;
    }
}

- (void)algorithmWithBleModel:(ELBodyFatScaleBleWeightModel *)weightModel user:(ELBodyFatScaleBleUserModel *)user {
    NSString *weightKg = [ELUnitConvertTool getWeightShowStrWithTargetUnit:ELDeviceWeightUnit_KG bleWeightInt:weightModel.weight bleWeightUnit:weightModel.weightUnit bleWeightPoint:weightModel.weightPoint];

    OEMAlgorithmModel *algorithmModel = [OEMAlgorithmSDK getBodyfatWithWeight:weightKg.floatValue adc:(int)weightModel.adc sex:user.sex age:(int)user.age height:(int)user.height];

    NSLog(@"algorithmModel.bmi:%@", algorithmModel.bmi);
}

/**
   Return error code(返回错误码)

   @param code 错误码
   1:超重
 */
- (void)bodyFatScaleManagerCallBackErrorCode:(NSInteger)code {
    [self addLog:[NSString stringWithFormat:@"error code = %ld", code]];
}

#pragma mark - private

- (void)addLog:(NSString *)log {
    self.textView.text = [NSString stringWithFormat:@"%@\n%@", log, self.textView.text];
}

- (NSArray<ELBodyFatScaleBleUserModel *> *)get8Users {
    NSMutableArray *users = [[NSMutableArray alloc] init];

    for (int i = 0; i < 8; i++) {
        ELBodyFatScaleBleUserModel *user = [[ELBodyFatScaleBleUserModel alloc] init];
        user.createTime = [[NSDate date] timeIntervalSince1970];
        user.usrID = i;
        user.role = i % 4;
        user.sex = i % 2;
        user.age = 26 + i;
        user.height = 170 + i;
        user.weight = 600 + i;
        user.adc = 560 + i;
        [users addObject:user];
    }

    return users.copy;
}

- (ELBodyFatScaleBleUserModel *)getOneUser {
    ELBodyFatScaleBleUserModel *user = [[ELBodyFatScaleBleUserModel alloc] init];

    user.createTime = [[NSDate date] timeIntervalSince1970];
    user.usrID = 0;
    user.role = BodyFatScaleRole_Ordinary;
    user.sex = ELBluetoothUserSex_Woman;
    user.age = 26;
    user.height = 170;
    user.weight = 600;
    user.adc = 560;
    return user;
}

@end
