//
//  MainViewController.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2023/12/1.
//  Copyright © 2023 hikvision. All rights reserved.
//

#import "MainViewController.h"
#import "EZAreaInfo.h"
#import "ServerAreasEnum.h"
#import "EZNavigationController.h"
#import "EZDeviceTableViewController.h"

// JuneCheng's AppKey
#define APPKEY_JC      @""
#define TOKEN_JC       @""

// 开发者账号信息
#define APPKEY_DEV     @""
#define TOKEN_DEV      @""
#define DEVICE_DEV     @""

@interface MainViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iv_logo;
@property (weak, nonatomic) IBOutlet UILabel *lab_version;///< SDK版本号
@property (weak, nonatomic) IBOutlet UILabel *lab_area;///< 服务器区域选择
@property (weak, nonatomic) IBOutlet UITextField *tf_apiUrl;///< 服务器地址
@property (weak, nonatomic) IBOutlet UITextField *tf_authUrl;///< web萤石账号登录服务器地址
@property (weak, nonatomic) IBOutlet UITextField *tf_appKey;///< appKey
@property (weak, nonatomic) IBOutlet UITextField *tf_accessToken;///< accessToken
@property (weak, nonatomic) IBOutlet UITextField *tf_specifiedDevice;///< 指定设备
@property (weak, nonatomic) IBOutlet UILabel *lab_ezvizAccountLogin;///< 萤石账号登录
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView;

@end

@implementation MainViewController

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

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self autoLogin];
    
    self.tf_appKey.text = APPKEY_DEV;
    self.tf_accessToken.text = TOKEN_DEV;
    self.tf_specifiedDevice.text = DEVICE_DEV;
}

#pragma mark - Actions

/** 开始体验 */
- (IBAction)startExperienceAction:(id)sender {
    if ([self checkLoginInfo]) {
        NSString *appKey = self.tf_appKey.text;
        NSString *token = self.tf_accessToken.text;
        NSString *apiUrl = self.tf_apiUrl.text;
        NSString *authUrl = self.tf_authUrl.text;
        NSString *specifiedDevice = self.tf_specifiedDevice.text;
        
        // 日志开启必须在initLibWithAppKey方法之前，正式发布时建议设置为NO或者删除
        [EZOPENSDK setDebugLogEnable:YES];
        // 码流缓存开关，在initLib方法之前调用；正式发布时必须设置为NO或者删除；否则本地会缓存大量的调试文件
        [EZOPENSDK setDebugStreamEnable:YES];
        // 开启p2p取流功能
        [EZOPENSDK enableP2P:YES];
        [GlobalKit shareKit].enableP2P = YES;
        // 小权限token登录，仅支持国内
#ifdef EZVIZ_OPEN_DEMO
        /**
         * 注意：Demo兼容accessToken模式和tkToken小权限模式，所以需要通过.tk进行判断
         * 开发者App只能使用一种模式，EZOpenSDK.enableSDKWithTKToken直接设置YES或NO
         */
        BOOL isEnableSDKWithTKToken = [token startsWith:@"tk."];
        [EZOpenSDK enableSDKWithTKToken:isEnableSDKWithTKToken];
#endif
        
        // 1.SDK初始化 & 设置accessToken/tkToken
        if (!kStringIsEmpty(apiUrl)) {
            [EZOPENSDK initLibWithAppKey:appKey url:apiUrl authUrl:authUrl];
        } else {
            [EZOPENSDK initLibWithAppKey:appKey];
        }
#ifdef EZVIZ_OPEN_DEMO
        isEnableSDKWithTKToken ? [EZOpenSDK setHttpToken:token] : [EZOPENSDK setAccessToken:token];
#else
        [EZOPENSDK setAccessToken:token];
#endif
        
        
        // 2.appKey & accessToken验证
        self.indicatorView.hidden = NO;
        [self.indicatorView startAnimating];
        [self checkAppKeyAndAccessTokenSuccess:^{
            // 3.验证成功后跳转设备列表页面
            [[GlobalKit shareKit] saveLastSDKInitAppkey:appKey accessToken:token apiUrl:apiUrl authUrl:authUrl specifiedDevice:specifiedDevice];
            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;
            [self toDeviceTableVC];
        }];
    }
}

/** 萤石账号登录 */
- (void)ezvizAccountLoginAction {
    NSString *appKey = self.tf_appKey.text;// 使用自己的AppKey，萤石账号和AppKey是绑定的
    NSString *apiUrl = self.tf_apiUrl.text;
    NSString *authUrl = self.tf_authUrl.text;
    // 日志开启必须在initLibWithAppKey方法之前，正式发布时建议设置为NO或者删除
    [EZOPENSDK setDebugLogEnable:YES];
    // 码流缓存开关，在initLib方法之前调用；正式发布时必须设置为NO或者删除；否则本地会缓存大量的调试文件
    [EZOPENSDK setDebugStreamEnable:YES];
    // 开启p2p取流功能
    [EZOPENSDK enableP2P:YES];
    [GlobalKit shareKit].enableP2P = YES;
    
#ifdef EZVIZ_GLOBAL_DEMO
    [EZOPENSDK initLibWithAppKey:appKey url:apiUrl authUrl:authUrl];
    [EZOPENSDK getAreaList:^(NSArray *areaList, NSError *error) {
        EZAreaInfo *areaInfo = areaList.firstObject;
        [EZOPENSDK openLoginPage:[NSString stringWithFormat:@"%ld",(long)areaInfo.id] completion:^(EZAccessToken *accessToken) {
            [self toDeviceTableVC];
        }];
    }];
#else
    /**
     * 国内使用萤石账号登录，一定要设置为NO
     * 本Demo是accessToken和tkToken两种模式共存的，如果第一次使用了tkToken，第二次要用accessToken模式登录，需要将enableSDKWithTKToken重置为false
     */
    [EZOPENSDK enableSDKWithTKToken:NO];
    [EZOPENSDK initLibWithAppKey:appKey url:apiUrl authUrl:authUrl];
    [EZOPENSDK openLoginPage:^(EZAccessToken *accessToken) {
        [self toDeviceTableVC];
    }];
#endif
}

/** 自动登录 */
- (void)autoLogin {
    NSString *appKey = [kUserDefaults objectForKey:UserAppKey];
    NSString *token = [kUserDefaults objectForKey:UserToken];
    if (kStringIsEmpty(appKey) || kStringIsEmpty(token)) {
        return;
    }
    self.indicatorView.hidden = NO;
    [self.indicatorView startAnimating];
    
    // 日志开启必须在initLibWithAppKey方法之前，正式发布时建议设置为NO或者删除
    [EZOPENSDK setDebugLogEnable:YES];
    // 码流缓存开关，在initLib方法之前调用；正式发布时必须设置为NO或者删除；否则本地会缓存大量的调试文件
    [EZOPENSDK setDebugStreamEnable:YES];
    // 开启p2p取流功能
    [EZOPENSDK enableP2P:YES];
    [GlobalKit shareKit].enableP2P = YES;
    // 小权限token登录，仅支持国内
    BOOL isEnableSDKWithTKToken = [token startsWith:@"tk."];
    [EZOpenSDK enableSDKWithTKToken:isEnableSDKWithTKToken];
    [EZOPENSDK initLibWithAppKey:appKey url:[kUserDefaults objectForKey:UserApiUrl] authUrl:[kUserDefaults objectForKey:UserAuthUrl]];
    isEnableSDKWithTKToken ? [EZOpenSDK setHttpToken:token] : [EZOPENSDK setAccessToken:token];
    [self checkAppKeyAndAccessTokenSuccess:^{
        [self.indicatorView stopAnimating];
        self.indicatorView.hidden = YES;
        [self toDeviceTableVC];
    }];
}

- (void)jcTestAction {
    ServerAreasEnum *serverArea = [[ServerAreasEnum sharedInstance].allServers firstObject];
    self.tf_appKey.text = APPKEY_JC;
    self.tf_accessToken.text = TOKEN_JC;
    self.tf_apiUrl.text = serverArea.apiUrl;
    self.tf_authUrl.text = serverArea.authUrl;
    self.tf_specifiedDevice.text = @"";
    [self startExperienceAction:nil];
}

/** 区域选择 */
- (void)areaSelectAction {
    NSArray<ServerAreasEnum *> *allServers = [ServerAreasEnum sharedInstance].allServers;
    [self showActionSheetWithTitle:NSLocalizedString(@"login_server_area_select", @"请选择服务区域") message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        for (int i = 0; i < allServers.count; i ++) {
            alertMaker.addActionDefaultTitle(allServers[i].areaName);
        }
        alertMaker.addActionCancelTitle(NSLocalizedString(@"cancel", @"取消"));
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex < allServers.count) {
            [self setLoginUrls:allServers[buttonIndex]];
        }
    }];
}

/** 设置apiUrl、authUrl */
- (void)setLoginUrls:(ServerAreasEnum *)serverArea {
    self.lab_area.text = serverArea.areaName;
    self.tf_apiUrl.text = serverArea.apiUrl;
    self.tf_authUrl.text = serverArea.authUrl;
    self.lab_ezvizAccountLogin.hidden = kStringIsEmpty(serverArea.defaultOpenAuthAppKey);
}

#pragma mark - private method

/** 跳转设备列表页面 */
- (void)toDeviceTableVC {
    EZDeviceTableViewController *deviceTableVC = [[EZDeviceTableViewController alloc] init];
    EZNavigationController *nav = [[EZNavigationController alloc] initWithRootViewController:deviceTableVC];
    kKeyWindow.rootViewController = nav;
}

/** 验证是否输入 AppKey 和 AccessToken */
- (BOOL)checkLoginInfo {
    if (kStringIsEmpty(self.tf_appKey.text)) {
        [EZToast show:NSLocalizedString(@"login_empty_appkey", @"AppKey不能为空！")];
        return NO;
    }
    if (kStringIsEmpty(self.tf_accessToken.text)) {
        [EZToast show:NSLocalizedString(@"login_empty_accesstoken", @"AccessToken不能为空！")];
        return NO;
    }
    return YES;
}

/** 通过调用服务接口判断AppKey和AccessToken是否有效 */
- (void)checkAppKeyAndAccessTokenSuccess:(void (^)())success {
    [EZOPENSDK getDeviceList:0 pageSize:1 completion:^(NSArray *deviceList, NSInteger totalCount, NSError *error) {
        if (error) {
            NSString *errMsg = @"";
            switch (error.code) {
                case 400031:
                    errMsg = NSLocalizedString(@"tip_of_bad_net", @"无法连接到服务器，请检查手机网络！");
                    break;
                default:
                    errMsg = [NSString stringWithFormat:@"%@\n%@", NSLocalizedString(@"login_expire", @"无效AppKey或AccessToken，请重新登录！"), error.description];
                    break;
            }
            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;
            [EZToast show:errMsg];
        } else {
            if (success) {
                success();
            }
        }
    }];
}

#pragma mark - UI

- (void)initUI {
    self.lab_version.text = [NSString stringWithFormat:@"SDK Version：v%@", kAppVersionName];
    EZWeak(self);
    [self.lab_area addActionBlock:^(UIView * _Nullable view) {
        EZStrong(self);
        [strongself areaSelectAction];
    }];
    [self.lab_ezvizAccountLogin addActionBlock:^(UIView * _Nullable view) {
        EZStrong(self);
        [strongself ezvizAccountLoginAction];
    }];
#ifdef JCTest
    [self.iv_logo addActionBlock:^(UIView * _Nullable view) {
        EZStrong(self);
        [strongself jcTestAction];
    }];
#endif
    // 设置选中的服务器区域
    NSString *apiUrl = [kUserDefaults objectForKey:UserApiUrl];
    NSArray<ServerAreasEnum *> *allServers = [ServerAreasEnum sharedInstance].allServers;
    int position = 0;
    for (int i = 0; i < allServers.count; i ++) {
        if ([apiUrl isEqualToString:allServers[i].apiUrl]) {
            position = i;
            break;
        }
    }
    [self setLoginUrls:[ServerAreasEnum sharedInstance].allServers[position]];
}

@end
