//
//  EZBluetoothConfigViewController.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2024/9/19.
//  Copyright © 2024 hikvision. All rights reserved.
//

#import "EZBluetoothConfigViewController.h"
#import "UIView+Toast.h"
#import "EZConfigTokenInfo.h"
#import "EZAPDevInfo.h"

#import <EZIoTBluetoothSDK/EZIoTBluetoothGlobalSetting.h>
#import <EZIoTBluetoothSDK/EZIoTBLECenterMgr.h>
#import <EZIoTBluetoothSDK/EZIoTWiFiConfigParam.h>

#define SEARCH_MAX_COUNT (20)

#define SSID          @""  ///< WiFi名称
#define SsidPWD       @""  ///< WiFi密码

@interface EZBluetoothConfigViewController ()

@property (weak, nonatomic) IBOutlet UITextField *tf_ssid;///< WiFi名称
@property (weak, nonatomic) IBOutlet UITextField *tf_password;///< WiFi密码
@property (weak, nonatomic) IBOutlet UITextField *tf_deviceSerial;///< 设备序列号
@property (weak, nonatomic) IBOutlet UITextField *tf_configToken;///< 接触式配网所需的配网token

@property (nonatomic, strong) NSMutableArray<EZIoTPeripheral *> *deviceArray;///< 蓝牙搜索到的设备列表
@property (nonatomic, strong) EZIoTPeripheral *connectDevice;///< 蓝牙连接的设备
@property (nonatomic, strong) EZConfigTokenInfo *tokenInfo;///< token信息
@property (nonatomic, strong) NSTimer *mTimer;
@property (nonatomic, assign) NSInteger searchCount;

@end

@implementation EZBluetoothConfigViewController

- (instancetype)init {
    if (self = [super init]) {
        self = [EZStoryBoardTool getViewController:@"AddDevice" andIdentifier:@"EZBluetoothConfigViewController"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"wifi_bluetooth_device_config", @"霍曼蓝牙配网");
    
    self.tf_ssid.text = SSID;
    self.tf_password.text = SsidPWD;
    
    [self initIoTBleSDK];
}

#pragma mark - 霍曼蓝牙配网

/** 蓝牙设备扫描 */
- (IBAction)scanDeviceAction:(id)sender {
    [self.deviceArray removeAllObjects];
    // 请求蓝牙权限，并获取权限回调
    [[EZIoTBLECenterMgr sharedInstance] requestBluetoothPermission:^(CBManagerState state) {
        NSLog(@"state：%ld",(long)state);
        // 步骤1：蓝牙设备扫描
        [EZToast show:NSLocalizedString(@"wifi_bluetooth_scan_start", @"开始扫描")];
        [[EZIoTBLECenterMgr sharedInstance] stopScan];
        [[EZIoTBLECenterMgr sharedInstance] scanPeripherals:YES allowDuplicate:NO filterBindDevice:NO scanBlock:^(EZIoTPeripheral * _Nullable peripheral, NSError * _Nullable error) {
            if (peripheral && !kStringIsEmpty(peripheral.devSerial)) {
                // 遍历列表，已经存在的拦截；只将新扫描到的设备加入列表
                for (int i = 0; i < self.deviceArray.count; i ++) {
                    NSString *scanDevSerial = peripheral.devSerial;
                    NSString *existDevSerial = self.deviceArray[i].devSerial;
                    if ([scanDevSerial isEqualToString:existDevSerial]) {
                        return;
                    }
                }
                [self.deviceArray addObject:peripheral];
            }
        }];
    }];
}

/** 显示已扫描设备 */
- (IBAction)showDeviceAction:(id)sender {
    if (self.deviceArray.count == 0) {
        NSString *tip = [[EZIoTBLECenterMgr sharedInstance] isCentralScaning] ? NSLocalizedString(@"wifi_bluetooth_scanning_device_tip", @"正在扫描蓝牙设备，请稍后") : NSLocalizedString(@"wifi_bluetooth_scan_device_tip", @"请先扫描蓝牙设备");
        [EZToast show:tip];
        return;
    }
    [self showActionSheetWithTitle:NSLocalizedString(@"wifi_bluetooth_device_select_tip", @"请选择要连接的设备") message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        for (int i = 0; i < self.deviceArray.count; i ++) {
            alertMaker.addActionDefaultTitle(self.deviceArray[i].devSerial);
        }
        alertMaker.addActionCancelTitle(NSLocalizedString(@"cancel", @"取消"));
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex < self.deviceArray.count) {
            [[EZIoTBLECenterMgr sharedInstance] stopScan];
            self.connectDevice = self.deviceArray[buttonIndex];
            // 步骤2：蓝牙设备连接
            [[EZIoTBLECenterMgr sharedInstance] connectPeripheral:self.deviceArray[buttonIndex] success:^(EZIoTPeripheral * _Nullable peripheral) {
                [EZToast show:NSLocalizedString(@"wifi_bluetooth_device_connect_success", @"蓝牙设备连接成功")];
                self.tf_deviceSerial.text = peripheral.devSerial;
            } failure:^(EZIoTPeripheral * _Nullable peripheral, NSError * _Nullable error) {
                [EZToast show:[NSString stringWithFormat:NSLocalizedString(@"wifi_bluetooth_device_connect_failed", @"蓝牙设备连接失败。错误码：%d"), error.code]];
            }];
        }
    }];
}

/** 获取配网所需的token  */
- (IBAction)getConfigTokenAction:(id)sender {
    // 步骤3：获取蓝牙设备配网必要的token信息
    [EZOPENSDK getNewApConfigToken:^(EZConfigTokenInfo * _Nonnull tokenInfo, NSError * _Nonnull error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        self.tokenInfo = tokenInfo;
        self.tf_configToken.text = tokenInfo.token;
    }];
}

/** 
 * 发起配网
 * 必填项：ssid、password、configToken（点击 '获取配网token' 按钮获取）
 */
- (IBAction)bluetoothConfigAction:(id)sender {
    [self stopTimer];
    
    // 步骤1：获取配网所需的tokenInfo；获取成功后手动切换连接设备热点
    NSString *wifiSsid = self.tf_ssid.text;
    NSString *wifiPwd = self.tf_password.text;
    NSString *devSerial = self.tf_deviceSerial.text;
    NSString *configToken = self.tf_configToken.text;
    if (kStringIsEmpty(wifiSsid)) {
        [EZToast show:NSLocalizedString(@"wifi_ssid_cannot_empty", @"WiFi用户名不能为空")];
        return;
    }
    if (kStringIsEmpty(wifiPwd)) {
        [EZToast show:NSLocalizedString(@"wifi_password_cannot_empty", @"WiFi密码不能为空")];
        return;
    }
    if (kStringIsEmpty(devSerial)) {
        [EZToast show:NSLocalizedString(@"wifi_bluetooth_device_connect_first", @"请先连接蓝牙设备")];
        return;
    }
    if (kStringIsEmpty(configToken)) {
        [EZToast show:NSLocalizedString(@"wifi_get_token_first", @"请先获取配网token")];
        return;
    }
    
    // 创建配网对象
    EZIoTWiFiConfigParam *param = [[EZIoTWiFiConfigParam alloc] init];
    param.ssid = wifiSsid;
    param.password = wifiPwd;
    param.lbs = self.tokenInfo.lbsDomain;
    param.token = self.tokenInfo.token;
    param.countryCode = @"CN";
    param.encryptType = 3;
    // 如果是门锁设备，需要认证，调用iConnectDevice.startLocalAuthentication("设备序列号", "验证码", completion)认证成功后再发起步骤4-配网
//    [[EZIoTBLECenterMgr sharedInstance] startLocalAuthentication:self.tf_deviceSerial verifyCode:@"验证码" completion:^(BOOL status, int failType, NSDictionary * _Nullable statistics, NSError * _Nullable error) {
//        if (status) {
//            // 认证成功后，发起配网请求
//        }
//    }];
    // 步骤4：发起配网请求，设备配网成功后会自动绑定到账号下
    [[EZIoTBLECenterMgr sharedInstance] wifiConfig:devSerial configParam:param completion:^(EZIoTPeripheral * _Nullable peripheral, BOOL status, NSError * _Nullable error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        [EZToast show:NSLocalizedString(@"wifi_info_send_success", @"向设备发送WiFi信息成功")];
        // 步骤5：开始轮询设备的绑定情况
        self.mTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(searchDeviceFromService) userInfo:nil repeats:YES];
    }];
}

/** 获取设备信息（需要先连接上设备蓝牙）  */
- (IBAction)getDeviceInfoAction:(id)sender {
    if (kStringIsEmpty(self.tf_deviceSerial.text)) {
        [EZToast show:NSLocalizedString(@"wifi_bluetooth_device_connect_first", @"请先连接蓝牙设备")];
        return;
    }
    
    EZIoTPeripheral *peripheralConnect = [[EZIoTBLECenterMgr sharedInstance] getPeripheralWithDevSerial:self.tf_deviceSerial.text];
    NSString *info = [NSString stringWithFormat:@"pid: %@\ndeviceName: %@", peripheralConnect.pid, peripheralConnect.devName];
    [self showAlertWithTitle:NSLocalizedString(@"wifi_device_info", @"设备信息") message:info];
}

/** 获取WiFi列表（需要先连接上设备蓝牙）  */
- (IBAction)getWiFiListAction:(id)sender {
    if (kStringIsEmpty(self.tf_deviceSerial.text)) {
        [EZToast show:NSLocalizedString(@"wifi_bluetooth_device_connect_first", @"请先连接蓝牙设备")];
        return;
    }
    [[EZIoTBLECenterMgr sharedInstance] getWiFiList:self.tf_deviceSerial.text completion:^(EZIoTPeripheral * _Nullable peripheral, NSArray * _Nullable list, NSError * _Nullable error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        [EZToast show:[NSString stringWithFormat:@"%@", list]];
    }];
}

/** 继续查询 */
- (IBAction)continueSearchAction:(id)sender {
    [self stopTimer];
    [EZOPENSDK queryPlatformBindStatus:self.tf_deviceSerial.text completion:^(BOOL isBindSuccess, NSError * _Nonnull error) {
        if (isBindSuccess) {
            [self showAlertWithTitle:NSLocalizedString(@"wifi_device_bind_success", @"设备已联网成功并绑定账号")];
        } else {
            NSLog(@"error--->%@", error);
        }
    }];
}

/** 停止配网 */
- (IBAction)stopWiFiConfigAction:(id)sender {
    [self stopTimer];
    [[EZIoTBLECenterMgr sharedInstance] stopScan];
    if (self.connectDevice) {
        [[EZIoTBLECenterMgr sharedInstance] stopConnect:self.connectDevice complement:^(EZIoTPeripheral * _Nullable peripheral, NSError * _Nullable error) {
            if (error) {
                [EZToast show:[NSString stringWithFormat:@"%@", error]];
                return;
            }
            NSLog(NSLocalizedString(@"wifi_bluetooth_device_disconnect_success", @"设备连接断开成功"));
        }];
    }
}

/** 使用说明 */
- (IBAction)instructionsAction:(id)sender {
    [self showAlertWithTitle:NSLocalizedString(@"wifi_bluetooth_config_instructions", @"使用说明") message:NSLocalizedString(@"wifi_bluetooth_config_instructions_content", @"第一步：点击'蓝牙设备扫描'按钮\n\n第二步：点击'显示已扫描设备'，没有就重新打开查看\n\n第三步：选择要连接的蓝牙设备\n\n第四步：点击'获取token'按钮，获取霍曼蓝牙配网所需的信息\n\n第五步：点击'向设备配网'按钮，发起配网\n\n注意：其他灰色按钮非必须，按需使用")];
}


- (void)searchDeviceFromService {
    self.searchCount ++;
    if (self.searchCount >= SEARCH_MAX_COUNT) {
        [self.mTimer invalidate];
        self.mTimer = nil;
        return;
    }
    [EZOPENSDK queryPlatformBindStatus:self.tf_deviceSerial.text completion:^(BOOL isBindSuccess, NSError * _Nonnull error) {
        if (isBindSuccess) {
            [self showAlertWithTitle:NSLocalizedString(@"wifi_device_bind_success", @"设备已联网成功并绑定账号")];
            [self stopTimer];
        } else {
            NSLog(@"error--->%@", error);
        }
    }];
}

- (void)stopTimer {
    if (!self.mTimer) {
        return;
    }
    if ([self.mTimer isValid]) {
        [self.mTimer invalidate];
    }
    self.mTimer = nil;
    self.searchCount = 0;
}

/** 蓝牙配网SDK初始化 */
- (void)initIoTBleSDK {
    // 设置日志等级及回调，0 DEBUG  1 INFO  2 ERROR 默认日志等级： DEBUG
    [EZIoTBluetoothGlobalSetting setLogLevel:0 callBack:^(NSString * _Nonnull log) {
        NSLog(@"EZIoTBluetooth: %@", log);
    }];
}

- (NSMutableArray<EZIoTPeripheral *> *)deviceArray {
    if (!_deviceArray) {
        _deviceArray = [NSMutableArray array];
    }
    return _deviceArray;
}

@end
