//
//  EZHttpInterfaceTestVC.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2024/7/11.
//  Copyright © 2024 hikvision. All rights reserved.
//

#import "EZHttpInterfaceTestVC.h"
#import "GlobalKit.h"

#import "EZStorageInfo.h"

#import "KLCPopup.h"

@interface EZHttpInterfaceTestVC () {
    NSArray *array;
}

@end

@implementation EZHttpInterfaceTestVC

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"接口测试";
    
    array = @[@[@"获取设备列表（支持网关子设备）", @"getDeviceListEx"],
              @[@"获取设备信息（支持网关子设备）", @"getDeviceInfoEx"],
              @[@"抓图", @"captureCamera"],
              @[@"获取用户信息", @"getUserInfo"],
              @[@"SD卡格式化", @"formatStorage"],
              @[@"云台结束转动Mix", @"ptzStopMix"],
              @[@"刷新设备详情数据", @"refreshDeviceInfo"],
              @[@"获取录像列表(recType入参随机)", @"searchRecordFile"],
              @[@"获取CVR中心录像列表", @"searchCVRRecordFile"],
              ];
    [self setupDataArr:array];
}

#pragma mark - 接口方法

/** 获取设备列表（支持网关子设备） */
- (void)getDeviceListEx {
    [EZOpenSDK getDeviceListEx:0
                    pageSize:10
                  completion:^(NSArray *deviceList, NSInteger totalCount, NSError *error) {
        [self requestSuccess];
    }];
}

/** 获取设备信息（支持网关子设备） */
- (void)getDeviceInfoEx {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    [EZOpenSDK getDeviceInfoEx:deviceSerial completion:^(EZDeviceInfo * _Nonnull deviceInfo, NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

/** 抓图 */
- (void)captureCamera {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    [EZOPENSDK captureCamera:deviceSerial cameraNo:1 completion:^(NSString *url, NSError *error) {
        [self showCapturePicture:url];
    }];
}

/** 获取用户信息 */
- (void)getUserInfo {
    [EZOpenSDK getUserInfo:^(EZUserInfo * _Nonnull userInfo, NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

/** SD卡格式化 */
- (void)formatStorage {
    if (![self isExistDeviceSerial]) return;
    [self showAlertWithTitle:@"确认要格式化吗" message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.addActionCancelTitle(@"取消");
        alertMaker.addActionDefaultTitle(@"确定");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 1) {
            NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
            [EZOPENSDK getStorageStatus:deviceSerial completion:^(NSArray * _Nonnull storageStatus, NSError * _Nullable error) {
                NSLog(@"storageStatus = %@, error = %@", storageStatus, error);
                EZStorageInfo *info = storageStatus[0];
                [EZOPENSDK formatStorage:deviceSerial storageIndex:info.index completion:^(NSError * _Nullable error) {
                    [self requestSuccess];
                    NSLog(@"format command error = %@", error);
                    if (!error || error.code == 120016) {
                        
                    }
                }];
            }];
        }
    }];
}

/** 云台结束转动Mix */
- (void)ptzStopMix {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    [EZOPENSDK controlPTZMix:deviceSerial cameraNo:1 command:EZPTZCommandUp action:EZPTZActionStop newSpeed:2 result:^(NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

/** 刷新设备详情数据 */
- (void)refreshDeviceInfo {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    [EZOPENSDK refreshDeviceDetailInfo:deviceSerial cameraNo:1 completion:^(NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

/** 获取录像列表 */
- (void)searchRecordFile {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    
    // iOS15.4 + 设置-通用-日期与时间-24小时制关闭情况下，需要设置NSDateFormatter的local为zh_CN，否则转换有问题。本demo已在分类里做了统一设置
    NSString *beginTimeString = [NSString stringWithFormat:@"%@ 00:00:00", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    NSDate *beginTime = [NSDate dateWithString:beginTimeString formatString:yMdHmsFormat];
    NSString *endTimeString = [NSString stringWithFormat:@"%@ 23:59:59", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    NSDate *endTime = [NSDate dateWithString:endTimeString formatString:yMdHmsFormat];
    [EZOPENSDK searchRecordFile:deviceSerial cameraNo:@"1" beginTime:beginTime endTime:endTime recType:arc4random()%3 bizType:@"" platFormId:@"" completion:^(id  _Nonnull records, NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

/** 获取CVR中心录像列表 */
- (void)searchCVRRecordFile {
    if (![self isExistDeviceSerial]) return;
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    
    // iOS15.4 + 设置-通用-日期与时间-24小时制关闭情况下，需要设置NSDateFormatter的local为zh_CN，否则转换有问题。本demo已在分类里做了统一设置
    NSString *beginTimeString = [NSString stringWithFormat:@"%@ 00:00:00", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    NSDate *beginTime = [NSDate dateWithString:beginTimeString formatString:yMdHmsFormat];
    NSString *endTimeString = [NSString stringWithFormat:@"%@ 23:59:59", [[NSDate date] formattedDateWithFormat:yMdFormat]];
    NSDate *endTime = [NSDate dateWithString:endTimeString formatString:yMdHmsFormat];
    [EZOPENSDK searchRecordFileFromCVR:deviceSerial cameraNo:1 beginTime:beginTime endTime:endTime completion:^(NSArray * _Nonnull cvrRecords, NSError * _Nullable error) {
        [self requestSuccess];
    }];
}

#pragma mark - 其他自定义方法

/** 设备序列号验证是否输入 */
- (BOOL)isExistDeviceSerial {
    NSString *deviceSerial = [kUserDefaults objectForKey:UserDevSerial];
    if (kStringIsEmpty(deviceSerial)) {
        [EZToast show:NSLocalizedString(@"test_specify_device_tip", @"请先在登录页面指定设备序列号")];
        return NO;
    }
    return YES;
}

/** 接口调用完成提示 */
- (void)requestSuccess {
    [EZToast show:NSLocalizedString(@"test_request_success_tip", @"请求成功，请查看日志打印")];
}

/** 显示抓图图片 */
- (void)showCapturePicture:(NSString *)url {
    UIView *contentView = [[UIView alloc] init];
    contentView.translatesAutoresizingMaskIntoConstraints = NO;
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.layer.cornerRadius = 12.0;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImageScale:nil];
    [contentView addSubview:imageView];
    
    UIButton *dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
    dismissButton.backgroundColor = HEXColor(0x1B9EE2);
    [dismissButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [dismissButton setTitle:@"关闭" forState:UIControlStateNormal];
    dismissButton.layer.cornerRadius = 20.0;
    [dismissButton addTarget:self action:@selector(dismissButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:dismissButton];
    
    // layoutSubviews
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(kScreenWidth*0.8, kScreenWidth*0.5+100)));
    }];
    CGFloat imageW = kScreenWidth*0.8-20;
    CGFloat imageH = imageW * 9 / 16;
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(imageW, imageH));
        make.centerX.equalTo(contentView);
        make.centerY.equalTo(contentView).offset(-20);
    }];
    [dismissButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(kScreenWidth*0.6, 40)));
        make.centerX.equalTo(contentView);
        make.bottom.equalTo(contentView).offset(-20);
    }];
    
    // Show in popup
    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutCenter);
    KLCPopup *popup = [KLCPopup popupWithContentView:contentView
                                            showType:KLCPopupShowTypeFadeIn
                                         dismissType:KLCPopupDismissTypeFadeOut
                                            maskType:KLCPopupMaskTypeDimmed
                            dismissOnBackgroundTouch:YES
                               dismissOnContentTouch:NO];
    
    [popup showWithLayout:layout];
}

/** 关闭KLCPopup */
- (void)dismissButtonPressed:(id)sender {
    if ([sender isKindOfClass:[UIView class]]) {
        [(UIView *)sender dismissPresentingPopup];
    }
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *methodName = self.classNames[indexPath.row];
    SEL selecotor = NSSelectorFromString(methodName);
    if ([self respondsToSelector:selecotor]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self performSelector:selecotor];
#pragma clang diagnostic pop
    }
}

@end
