//
//  RoomsControllerPairViewController.m
//  HWMSDKDemo
//
//  Created by yaolili/ywx577644 on 2023/8/21.
//  Copyright © 2023 HuaWei. All rights reserved.
//

#import "RemoteControlPairViewController.h"
#import "sys/utsname.h"
#import <HWMUISDK/HWMRoomsControllerSdk.h>
#import "UIUtil.h"
#import "LoginManager.h"
#import "SliderCodeView.h"
#import "RemoteControlWebViewController.h"
#import "RemoteControlVerificationCodeViewController.h"

@interface RemoteControlPairViewController () <SliderCodeViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) SliderCodeView *sliderCodeView;
@property (nonatomic, strong) HWMSDKRequestControllerSliderResultModel *sliderInfo;
@property (weak, nonatomic) IBOutlet UITextField *pairCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *pairButton;
@property (nonatomic, copy) NSString *pairCodeUrl;
@property (nonatomic, strong) HWMRequestPairInfoModel *pairInfo;

@end

@implementation RemoteControlPairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"控制器配对";
    self.pairCodeTextField.delegate = self;
    if (![self isLogined]) {
        // 离线配对。先尝试配对，如果已经被设为常用设备会配对成功，否则失败。失败再输入配对码配对
        [self showLoading];
        HWMRequestPairInfoModel *model = [[HWMRequestPairInfoModel alloc] init];
        model.deviceId = [self deviceID];

        [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestPair:model successCallback:^(HWMSDKRequestPairResultModel * _Nonnull requestPairResult) {
            [self hideLoading];
            [self showWebviewWithNonce:requestPairResult.nonce code:requestPairResult.code isForce:NO];
        } failedCallback:^(NSError * _Nullable error) {
            [self hideLoading];
            if (error.code == HWMSDKSdkLoginlogicNeedRepairController || error.code == HWMSDKUsgOfflinePairAuthFixedLinkUnfound) {
                // do nothing。没有离线常用设备，输入配对码后直接请求滑块
            } else {
                [UIUtil showMessageWithError:error];
            }
        }];
    } else {
        [self showLoading];
        // 登录后什么参数都不用传打开web，在web上输入配对码配对
        HWMRequestPairInfoModel *model = [[HWMRequestPairInfoModel alloc] init];
        [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestPair:model successCallback:^(HWMSDKRequestPairResultModel * _Nonnull requestPairResult) {
            [self hideLoading];
            [self showWebviewWithNonce:requestPairResult.nonce code:requestPairResult.code isForce:NO];
        } failedCallback:^(NSError * _Nullable error) {
            [self hideLoading];
            [UIUtil showMessage:@"设备配对失败" error:error];
        }];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.activityIndicator.frame = self.view.bounds;
}

- (IBAction)pairBtnClickAction:(UIButton *)sender {
    [self.pairCodeTextField endEditing:YES];
    if ([self isLogined]) {
        [self showLoading];
        // 登录后什么参数都不用传打开web，在web上输入配对码配对
        HWMRequestPairInfoModel *model = [[HWMRequestPairInfoModel alloc] init];
        [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestPair:model successCallback:^(HWMSDKRequestPairResultModel * _Nonnull requestPairResult) {
            [self hideLoading];
            [self showWebviewWithNonce:requestPairResult.nonce code:requestPairResult.code isForce:NO];
        } failedCallback:^(NSError * _Nullable error) {
            [self hideLoading];
            [UIUtil showMessage:@"设备配对失败" error:error];
        }];
    } else {
        [self requestSliderWithIsRefresh:NO];
    }
}

- (void)forcePair {
    self.pairInfo.isForcePair = YES;
    [self showLoading];
    [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestPair:self.pairInfo successCallback:^(HWMSDKRequestPairResultModel * _Nonnull requestPairResult) {
        [self hideLoading];
        [self showWebviewWithNonce:requestPairResult.nonce code:requestPairResult.code isForce:YES];
    } failedCallback:^(NSError * _Nullable error) {
        [self hideLoading];
        [self pairFailedWithError:error];
    }];
}

- (void)pairFailedWithError:(NSError *)error {
    if (error.code == HWMSDKUsgOfflineFixedPairAlreadyExist) { // 有离线固定链路代表大屏有离线配对的常用设备，不能互踢。离线的临时链路可以互踢
        [UIUtil showMessage:@"非登录配对同一时间仅支持连接一台设备，请先在Smartrooms解除固定设备"];
    } else if (error.code == HWMSDKSdkLoginlogicNeedRepairWithCredential) {
        // 输入验证码后再配对
        RemoteControlVerificationCodeViewController *ctrl = [[RemoteControlVerificationCodeViewController alloc] init];
        ctrl.pairInfo = self.pairInfo;
        [self.navigationController pushViewController:ctrl animated:YES];
    } else if (error.code == HWMSDKUsgOfflinePairAlreadyExist) {
        [UIUtil showMessage:@"当前设备已有控制器，继续配对会将其他控制器踢掉"];
        [self forcePair];
    } else {
        [UIUtil showMessageWithError:error];
    }
}

#pragma mark SliderCodeViewDelegate
/// 校验滑块
- (void)checkSliderCodeWithPointX:(NSInteger)pointX slideTime:(NSInteger)timer {
    [self showLoading];
    HWMCheckControllerSliderInfoModel *model = [[HWMCheckControllerSliderInfoModel alloc] init];
    model.verificationId = self.sliderInfo.verificationId;
    model.pointX = pointX;
    model.slideTime = timer;
    [[HWMRoomsControllerSdk getRoomsControllerOpenApi] checkSlider:model successCallback:^(HWMSDKCheckControllerSliderResultModel * _Nonnull checkControllerSliderResult) {
        [self checkSliderSuccess:checkControllerSliderResult];
    } failedCallback:^(NSError * _Nullable error) {
        [self checkSliderFailWithError:error];
    }];
}

/// 滑块校验成功
- (void)checkSliderSuccess:(HWMSDKCheckControllerSliderResultModel *)sliderInfo {
    [self.sliderCodeView changeSliderViewWithSuccessViewHidden:NO sliderIsSuccess:YES sliderEnable:YES];
    [self.sliderCodeView sliderCheckSuccess];
    [self moveToVerificationCode];
    
    // 校验成功再次调用配对接口，把token带上
    HWMRequestPairInfoModel *pairInfo = [[HWMRequestPairInfoModel alloc] init];
    pairInfo.pairCode = self.pairCodeTextField.text;
    pairInfo.token = sliderInfo.token;
    pairInfo.deviceId = [self deviceID];
    self.pairInfo = pairInfo;
    [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestPair:pairInfo successCallback:^(HWMSDKRequestPairResultModel * _Nonnull requestPairResult) {
        [self hideLoading];
        self.pairCodeTextField.text = @"";
        self.pairInfo = nil;
        [self showWebviewWithNonce:requestPairResult.nonce code:requestPairResult.code isForce:NO];
    } failedCallback:^(NSError * _Nullable error) {
        [self hideLoading];
        self.pairCodeTextField.text = @"";
        [self pairFailedWithError:error];
    }];
}

/// 滑块校验失败
- (void)checkSliderFailWithError:(NSError *)error {
    [self hideLoading];
    [self.sliderCodeView changeSliderViewWithSuccessViewHidden:NO sliderIsSuccess:NO sliderEnable:YES];
    if (error.code == HWMSDKUsgSliderVerifyCodeError) {
        [self requestSliderWithIsRefresh:YES]; // 校验失败再次请求滑块
    } else {
        self.pairCodeTextField.text = @"";
        [self.sliderCodeView dissmiss];
        [UIUtil showMessage:@"滑块校验失败，请重新配对" error:error];
    }
}

/// 请求滑块
/// @param isRefresh 刷新滑块
- (void)requestSliderWithIsRefresh:(BOOL)isRefresh {
    [self showLoading];
    HWMRequestControllerSliderInfoModel *model = [[HWMRequestControllerSliderInfoModel alloc] init];
    model.deviceId = [self deviceID];
    [[HWMRoomsControllerSdk getRoomsControllerOpenApi] requestSlider:model successCallback:^(HWMSDKRequestControllerSliderResultModel * _Nonnull requestControllerSliderResult) {
        [self hideLoading];
        self.sliderInfo = requestControllerSliderResult; // 缓存，校验滑块要用
        SliderCodeParam *param = [[SliderCodeParam alloc] init];
        param.shadowImage = requestControllerSliderResult.shadowImage;
        param.cutImage = requestControllerSliderResult.cutImage;
        param.pointY = requestControllerSliderResult.pointY;
        param.bgImageWidth = 280.0;
        param.bgImageRatio = 110.0/280.0;
        if (isRefresh) {
            [self.sliderCodeView updateSliderCodeView:param];
        } else {
            [self.view addSubview:self.sliderCodeView];
            [self.sliderCodeView updateSliderCodeView:param];
        }
    } failedCallback:^(NSError * _Nullable error) {
        [self hideLoading];
        [UIUtil showMessage:@"获取滑块失败" error:error];
    }];
}

- (void)moveToVerificationCode {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.sliderCodeView dissmiss];
        self.sliderCodeView = nil;
    });
}

- (void)showWebviewWithNonce:(NSString *)nonce code:(NSString *)code isForce:(BOOL)isForce {
    RemoteControlWebViewController *ctrl = [[RemoteControlWebViewController alloc] initWithNonce:nonce code:code isForce:isForce];
    [self.navigationController pushViewController:ctrl animated:YES];
}

- (SliderCodeView *)sliderCodeView {
    if (!_sliderCodeView) {
        SliderCodeParam *param = [[SliderCodeParam alloc] init];
        param.bgImageWidth = 280.0;
        param.bgImageRatio = 110.0/280.0;
        _sliderCodeView = [[SliderCodeView alloc] initWithFrame:self.view.bounds param:param];
        _sliderCodeView.delegate = self;
    }
    return _sliderCodeView;

}

- (BOOL)isLogined {
    return [[LoginManager sharedInstance] hasLogin];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSPredicate * resultStr = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[A-Z]*"];
    return [resultStr evaluateWithObject:string];
}

#pragma mark device info
- (NSString *)deviceID {
    return [UIDevice currentDevice].identifierForVendor.UUIDString;
}

- (NSString *)deviceName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
}

#pragma mark loading
- (void)showLoading {
    [self.activityIndicator startAnimating];
}

- (void)hideLoading {
    [self.activityIndicator stopAnimating];
}

@end
