//
//  EZSettingViewController.m
//  EZOpenSDKDemo
//
//  Created by DeJohn Dong on 15/11/10.
//  Copyright © 2015年 Ezviz. All rights reserved.
//

#import "EZSettingViewController.h"
#import "UIAlertController+DeviceVerifyCodeBySerial.h"
#import "MBProgressHUD.h"

#import "EZDeviceVersion.h"
#import "EZStorageInfo.h"

#import "EZDeviceTableViewController.h"
#import "EZEditViewController.h"
#import "EZDeviceUpgradeViewController.h"
#import "EZBandWidthCheckVC.h"

@interface EZSettingViewController ()

@property (nonatomic, strong) NSMutableArray *settingList;
@property (nonatomic, weak) IBOutlet UISwitch *videoSwitch;///< 视频图片加密
@property (nonatomic, weak) IBOutlet UISwitch *actionSwitch;///< 活动检测提醒
@property (weak, nonatomic) IBOutlet UISwitch *hdSwitch;///< 硬解码
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@property (nonatomic, weak) IBOutlet UILabel *serialLabel;
@property (nonatomic, weak) IBOutlet UILabel *currentVersionLabel;
@property (nonatomic, weak) IBOutlet UILabel *nVersionLabel;
@property (nonatomic, weak) IBOutlet UIImageView *updateImageView;
@property (nonatomic, strong) EZDeviceVersion *deviceVersion;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation EZSettingViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"setting_device_set_title", @"设备设置");

    if (!_settingList)
        _settingList = [NSMutableArray new];
    [_settingList addObject:@[NSLocalizedString(@"setting_device_name", @"设备名")]];
    [_settingList addObject:@[NSLocalizedString(@"setting_device_serial", @"序列号")]];
    [_settingList addObject:@[NSLocalizedString(@"setting_device_version", @"当前版本"),
                              NSLocalizedString(@"setting_device_new_version",@"最新版本")]];
    if (_deviceInfo.cameraNum == 0) {
        NSMutableString *str = [NSMutableString stringWithString:NSLocalizedString(@"setting_defense_status", @"防护状态：")];
        if (self.deviceInfo.defence == 0) {
            [str appendString:NSLocalizedString(@"setting_sleep_mode", @"睡眠模式")];
        } else if (self.deviceInfo.defence == 8) {
            [str appendString:NSLocalizedString(@"setting_home_mode", @"在家模式")];
        } else {
            [str appendString:NSLocalizedString(@"setting_out_mode", @"外出模式")];
        }
        [_settingList addObject:@[str]];
        [_settingList addObject:@[NSLocalizedString(@"setting_ignore_code", @"告警主机无视频图片加密功能")]];
        self.actionSwitch.hidden = YES;
        self.videoSwitch.hidden = YES;
    } else {
        [_settingList addObject:@[NSLocalizedString(@"setting_action_detect", @"活动检测提醒")]];
        [_settingList addObject:@[NSLocalizedString(@"setting_secure_code", @"视频图片加密")]];
        self.actionSwitch.on = self.deviceInfo.defence;
        self.videoSwitch.on = self.deviceInfo.isEncrypt;
    }
    [_settingList addObject:@[NSLocalizedString(@"setting_hardware_decoding", @"硬解码")]];
    [_settingList addObject:@[NSLocalizedString(@"setting_bandwidth_check", @"带宽检测")]];
    [_settingList addObject:@[NSLocalizedString(@"delete", @"删除")]];
    
    self.serialLabel.text = self.deviceInfo.deviceSerial;
    
    self.updateImageView.hidden = YES;
    [EZOPENSDK getDeviceVersion:self.deviceInfo.deviceSerial
                     completion:^(EZDeviceVersion *version, NSError *error) {
                         _deviceVersion = version;
                         self.currentVersionLabel.text = version.currentVersion;
                         if (version.isNeedUpgrade) {
                             self.nVersionLabel.text = version.latestVersion;
                             self.updateImageView.hidden = NO;
                         } else {
                             self.updateImageView.hidden = YES;
                             self.nVersionLabel.text = version.currentVersion;
                         }
                     }];
    
//    [EZOPENSDK getStorageStatus:self.deviceInfo.deviceSerial
//                     completion:^(NSArray *storageStatus, NSError *error) {
//                         NSLog(@"storageStatus = %@, error = %@", storageStatus, error);
//                         EZStorageInfo *info = storageStatus[0];
//                         [EZOPENSDK formatStorage:self.deviceInfo.deviceSerial
//                                     storageIndex:info.index
//                                       completion:^(NSError *error) {
//                                           NSLog(@"format command error = %@", error);
//                                           if (!error || error.code == 120016)
//                                           {
//                                               [self checkStorageStatus:nil];
//                                           }
//                                       }];
//                     }];
}

- (IBAction)checkStorageStatus:(id)sender
{
//    [EZOPENSDK getStorageStatus:self.cameraInfo.deviceSerial
//                     completion:^(NSArray *storageStatus, NSError *error) {
//                         NSLog(@"started format, storageStatus = %@, error = %@", storageStatus, error);
//                         if (!error)
//                         {
//                             //5s获取一次升级状态
//                             if (_timer)
//                             {
//                                 [_timer invalidate];
//                                 _timer = nil;
//                             }
//                             _timer = [NSTimer scheduledTimerWithTimeInterval:5.0
//                                                                       target:self
//                                                                     selector:@selector(checkStorageStatus:)
//                                                                     userInfo:nil
//                                                                      repeats:YES];
//                         }
//                     }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }

    [super viewWillDisappear:animated];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.settingList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.settingList dd_objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EZSettingCell" forIndexPath:indexPath];
    
    // Configure the cell...
    cell.textLabel.text = [[_settingList dd_objectAtIndex:indexPath.section] dd_objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (indexPath.section == 0) {// 设备名
        [cell.contentView addSubview:self.nameLabel];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [self.nameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(@140);
            make.trailing.mas_equalTo(cell.contentView.mas_trailing);
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.height.mas_equalTo(@20);
        }];
        self.nameLabel.text = [NSString stringWithFormat:@"%@", kStringIsEmpty(self.deviceInfo.deviceName) ? [NSString stringWithFormat:@"%@(%@)", self.deviceInfo.category, self.deviceInfo.deviceSerial] : self.deviceInfo.deviceName];;
    } else if (indexPath.section == 1) {// 序列号
        [cell.contentView addSubview:self.serialLabel];
        [self.serialLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.mas_equalTo(@140);
            make.trailing.mas_equalTo(cell.contentView.mas_trailing).offset(-34);
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.height.mas_equalTo(@20);
        }];
        self.serialLabel.text = self.deviceInfo.deviceSerial;
    } else if (indexPath.section == 5) {// 硬解码
        [cell.contentView addSubview:self.hdSwitch];
        [self.hdSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(@(-17));
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.width.mas_equalTo(@51);
            make.height.mas_equalTo(@31);
        }];
        BOOL hdStatus = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"EZVideoPlayHardDecodingStatus_%@", self.deviceInfo.deviceSerial]];
        self.hdSwitch.on = hdStatus;
    } else if (indexPath.section == 6) {// 带宽检测
        
    } else if (indexPath.section == 7) {// 删除
        cell.textLabel.textColor = [UIColor redColor];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
    } else if (indexPath.section == 3) {// 活动检测提醒
        [cell.contentView addSubview:self.actionSwitch];
        [self.actionSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(@(-17));
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.width.mas_equalTo(@51);
            make.height.mas_equalTo(@31);
        }];
    } else if (indexPath.section == 4) {// 视频图片加密
        [cell.contentView addSubview:self.videoSwitch];
        [self.videoSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(@(-17));
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.width.mas_equalTo(@51);
            make.height.mas_equalTo(@31);
        }];
    } else {
        if (indexPath.row == 0) {// 当前版本
            [cell.contentView addSubview:self.currentVersionLabel];
            [self.currentVersionLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(@140);
                make.trailing.mas_equalTo(cell.contentView.mas_trailing).offset(-34);
                make.centerY.mas_equalTo(cell.contentView.mas_centerY);
                make.height.mas_equalTo(@20);
            }];
        } else { // 最新版本
            [cell.contentView addSubview:self.nVersionLabel];
            [self.nVersionLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(@140);
                make.trailing.mas_equalTo(cell.contentView.mas_trailing).offset(-34);
                make.centerY.mas_equalTo(cell.contentView.mas_centerY);
                make.height.mas_equalTo(@20);
            }];
            [cell.contentView addSubview:self.updateImageView];
            [self.updateImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.trailing.mas_equalTo(self.nVersionLabel.mas_leading).offset(5);
                make.centerY.mas_equalTo(self.nVersionLabel.mas_centerY);
            }];
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 7) {// 删除
        [self showActionSheetWithTitle:nil message:nil appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.addActionCancelTitle(NSLocalizedString(@"cancel", @"取消"));
            alertMaker.addActionDestructiveTitle(NSLocalizedString(@"delete", @"删除"));
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                __weak MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = NSLocalizedString(@"message_deleting", @"正在删除，请稍候...");
                [EZOPENSDK deleteDevice:self.deviceInfo.deviceSerial completion:^(NSError *error) {
                    [hud hide:YES];
                    if (error) {
                        if (error.code == EZ_HTTPS_USER_NOT_OWN_THIS_DEVICE) {
                            [EZToast show:NSLocalizedString(@"device_user_not_own_device", @"该用户不拥有该设备")];
                        }
                        return;
                    }
                    NSArray *viewControllers = self.navigationController.viewControllers;
                    for (UIViewController *vc in viewControllers) {
                        if ([vc isKindOfClass:[EZDeviceTableViewController class]]) {
                            ((EZDeviceTableViewController *)vc).needRefresh = YES;
                            [self.navigationController popToViewController:vc animated:YES];
                            break;
                        }
                    }
                }];
            }
        }];
    } else if (indexPath.section == 0) {// 跳转"设备名修改"页面
        [self performSegueWithIdentifier:@"go2setDeviceName" sender:nil];
    } else if (indexPath.section == 2 && indexPath.row == 1 && self.updateImageView.hidden == NO) {
        [self performSegueWithIdentifier:@"go2Upgrade" sender:nil];
    } else if (indexPath.section == 6) {// 带宽检测
        EZBandWidthCheckVC *bandWidthCheckVC = [[EZBandWidthCheckVC alloc] init];
        bandWidthCheckVC.deviceSerial = self.deviceInfo.deviceSerial;
        [self.navigationController pushViewController:bandWidthCheckVC animated:YES];
    }
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue destinationViewController] isKindOfClass:[EZEditViewController class]]) {
        ((EZEditViewController *)[segue destinationViewController]).deviceInfo = self.deviceInfo;
    } else if ([[segue destinationViewController] isKindOfClass:[EZDeviceUpgradeViewController class]]) {
        ((EZDeviceUpgradeViewController *)[segue destinationViewController]).deviceSerial = self.deviceInfo.deviceSerial;
        ((EZDeviceUpgradeViewController *)[segue destinationViewController]).version = self.deviceVersion;
    }
}

#pragma mark - Action Methods

- (IBAction)actionSwitchChanged:(id)sender {
    __weak MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = NSLocalizedString(@"setting_switching", @"正在切换，请稍候...");
    /**
     *  注意；该demo只处理了IPC设备的布撤防，所有只有YES/NO，关于A系列设备请判断设备后修改枚举值再处理
     */
    [EZOPENSDK setDefence:self.actionSwitch.on
             deviceSerial:self.deviceInfo.deviceSerial
               completion:^(NSError *error) {
        [hud hide:YES];
        if (error) {
            [self.view makeToast:NSLocalizedString(@"setting_opration_fail", @"操作失败") duration:2.0 position:@"center"];
            self.actionSwitch.on = !self.actionSwitch.on;
        } else {
            self.deviceInfo.defence = self.actionSwitch.on;
        }
    }];
}

- (IBAction)HDChanged:(id)sender {
    UISwitch *hdSwitch = (UISwitch*)sender;
    BOOL status = hdSwitch.isOn;
    [[NSUserDefaults standardUserDefaults] setBool:status forKey:[NSString stringWithFormat:@"EZVideoPlayHardDecodingStatus_%@", self.deviceInfo.deviceSerial]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/** 视频图片加密开关Action */
- (IBAction)encryptChanged:(id)sender {
    if (!self.videoSwitch.on) {
        [UIAlertController showAlertWithDeviceSerial:self.deviceInfo.deviceSerial title:NSLocalizedString(@"setting_device_security_check", @"设备操作安全验证") message:NSLocalizedString(@"setting_input_code_plz",@"请输入该设备的设备验证码（设备标签上的6位字母）") confirmBlock:^(NSString * _Nonnull code) {
            [self setDeviceEncryptStatus:self.deviceInfo.deviceSerial verifyCode:code encrypt:NO];
        } cancelBlock:^{
            self.videoSwitch.on = YES;
        }];
    } else {
        [self setDeviceEncryptStatus:self.deviceInfo.deviceSerial verifyCode:nil encrypt:YES];
    }
}

#pragma mark - Request

/** 加密开关请求 */
- (void)setDeviceEncryptStatus:(NSString *)deviceSerial verifyCode:(NSString *)verifyCode encrypt:(BOOL)isEncrypt {
    self.videoSwitch.enabled = NO;
    // 此处的self需要强持有，设置成功后需要更改设备状态
    [EZOPENSDK setDeviceEncryptStatus:deviceSerial
                           verifyCode:verifyCode
                              encrypt:isEncrypt
                           completion:^(NSError *error) {
        if (error) {
            [self.view makeToast:NSLocalizedString(@"setting_opration_fail", @"操作失败") duration:2.0 position:@"center"];
            [UIView dd_showMessage:error.localizedDescription];
            self.videoSwitch.on = !isEncrypt;
        } else {
            [self.view makeToast:NSLocalizedString(@"setting_opration_success", @"操作成功") duration:2.0 position:@"center"];
            self.videoSwitch.on = isEncrypt;
            self.deviceInfo.isEncrypt = isEncrypt;
        }
        self.videoSwitch.enabled = YES;
    }];
}

@end
