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

#import "EZDeviceTableViewController.h"

#import "EZAccessToken.h"
#import "EZAreaInfo.h"
#import "EZDeviceInfo.h"
#import "EZCameraInfo.h"

#import "MJRefresh.h"
#import "DeviceListCell.h"

#import "EZRealPlayViewController.h"
#import "EZPlaybackViewController.h"
#import "EZMessageListViewController.h"
#import "EZSettingViewController.h"
#import "EZJoinMeetingViewController.h"
#import "EZCameraTableViewController.h"
#import "EZMultiChannelRealPlayVC.h"
#import "EZHubDebugViewController.h"
#import "EZAddByQRCodeViewController.h"
#import "MainViewController.h"
#import "EZTestVC.h"

#define EZDeviceListPageSize 10

@interface EZDeviceTableViewController () {
    BOOL isSharedDevice; ///< 是否是分享设备的segmented档选中
    NSInteger currentPageIndex;///< 分页
}
@property (nonatomic, weak) IBOutlet UIBarButtonItem *addButton;
@property (nonatomic, weak) IBOutlet UISegmentedControl *segmentedControl;

@property (nonatomic, strong) NSMutableArray *deviceArray;///< 设备列表

@end

@implementation EZDeviceTableViewController

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

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // 判断本地保存的accessToken
    if ([EZOPENSDK isLogin]) {
        [self addRefreshKit];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_needRefresh) {
        _needRefresh = NO;
        [self.tableView.header beginRefreshing];
    }
}

#pragma mark - Custom Methods

- (void)addRefreshKit {
    EZWeak(self);
    self.tableView.header.automaticallyChangeAlpha = YES;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        EZStrong(self);
        strongself->currentPageIndex = 0;
        if (strongself->isSharedDevice) {
            [strongself getSharedDeviceList];
        } else {
            // 调试单设备
            if (!kStringIsEmpty([kUserDefaults objectForKey:UserDevSerial])) {
                [strongself getDeviceInfo];
            } else {
                [strongself getDeviceList];
            }
        }
    }];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        EZStrong(self);
        strongself->currentPageIndex ++;
        strongself->isSharedDevice ? [strongself getSharedDeviceList] : [strongself getDeviceList];
    }];
    [self.tableView.header beginRefreshing];
}

#pragma mark - Request

/** 根据序列号获取设备信息接口 */
- (void)getDeviceInfo {
    // 如果设备是网关-门铃类子设备，请将getDeviceInfo替换为getDeviceInfoEx方法
    [EZOPENSDK getDeviceInfo:[kUserDefaults objectForKey:UserDevSerial] completion:^(EZDeviceInfo *deviceInfo, NSError *error) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshingWithNoMoreData];
        if (error) {
            [self.deviceArray removeAllObjects];
            [self.tableView reloadData];
            if (error.code == EZ_HTTPS_USER_NOT_OWN_THIS_DEVICE) {
                [EZToast show:NSLocalizedString(@"device_user_not_own_device", @"该用户不拥有该设备")];
            }
            return;
        }
        if (deviceInfo) {
            [self.deviceArray removeAllObjects];
            [self.deviceArray addObject:deviceInfo];
            [self.tableView reloadData];
        }
    }];
}

/** 获取设备列表接口 */
- (void)getDeviceList {
    // 如果设备是网关-门铃类子设备，请将getDeviceList替换为getDeviceListEx方法
    [EZOPENSDK getDeviceList:currentPageIndex
                    pageSize:EZDeviceListPageSize
                  completion:^(NSArray *deviceList, NSInteger totalCount, NSError *error) {
        [self refreshTableViewWithDeviceList:deviceList error:error];
    }];
}

/** 获取分享设备列表接口 */
- (void)getSharedDeviceList {
    [EZOPENSDK getSharedDeviceList:currentPageIndex
                          pageSize:EZDeviceListPageSize
                        completion:^(NSArray *deviceList, NSInteger totalCount, NSError *error) {
        [self refreshTableViewWithDeviceList:deviceList error:error];
    }];
}

/** 获取到设备列表数据后再刷新 */
- (void)refreshTableViewWithDeviceList:(NSArray *)deviceList error:(NSError *)error {
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    if (error) {
        return;
    }
    if (currentPageIndex == 0) {
        [self.deviceArray removeAllObjects];
    }
    [self.deviceArray addObjectsFromArray:deviceList];
    [self.tableView reloadData];
    if (deviceList.count < EZDeviceListPageSize) {
        [self.tableView.footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Actions

/** 点击列表图片进入预览页面 */
- (void)go2Play:(EZDeviceInfo *)deviceInfo {    
    if ([deviceInfo.deviceType containsString:@"CAS"]) {// 兼容demo之前的业务逻辑，可无视此分支
        [self go2HubDebugWith:EZPlayTypeLive deviceInfo:deviceInfo];
    } else if (deviceInfo.cameraNum == 1) {// 单通道设备(普通单镜头IPC)，直接跳转预览页面
        EZRealPlayViewController *livePlayVC = [[EZRealPlayViewController alloc] init];
        livePlayVC.deviceInfo = deviceInfo;
        [self.navigationController pushViewController:livePlayVC animated:YES];
    } else if (deviceInfo.cameraNum > 1) {// 多通道设备，跳转通道列表进行选择
        if (deviceInfo.isSupportMultiChannel) {// 双目设备(双镜头或多镜头设备)
            EZRealPlayViewController *livePlayVC = [[EZRealPlayViewController alloc] init];
            livePlayVC.deviceInfo = deviceInfo;
            [self.navigationController pushViewController:livePlayVC animated:YES];
        } else {// NVR设备，要选通道
            EZCameraTableViewController *cameraListVC = [[EZCameraTableViewController alloc] init];
            cameraListVC.deviceInfo = deviceInfo;
            cameraListVC.playType = EZPlayTypeLive;
            [self.navigationController pushViewController:cameraListVC animated:YES];
        }
    } else if (deviceInfo.subDeviceInfo.count > 0) {// 子设备(挂载下网关下)
        EZCameraTableViewController *cameraListVC = [[EZCameraTableViewController alloc] init];
        cameraListVC.deviceInfo = deviceInfo;
        cameraListVC.playType = EZPlayTypeLive;
        [self.navigationController pushViewController:cameraListVC animated:YES];
    }
}

/** 回放 */
- (void)go2Record:(EZDeviceInfo *)deviceInfo {
    if ([deviceInfo.deviceType containsString:@"CAS"]) {// 兼容demo之前的业务逻辑，可无视此分支
        [self go2HubDebugWith:EZPlayTypePlayBack deviceInfo:deviceInfo];
    } else if (deviceInfo.cameraNum == 1) {
        EZPlaybackViewController *playbackVC = [[EZPlaybackViewController alloc] init];
        playbackVC.deviceInfo = deviceInfo;
        [self.navigationController pushViewController:playbackVC animated:YES];
    } else if(deviceInfo.cameraNum > 1) {
        if (deviceInfo.isSupportMultiChannel) {// 双目设备
            EZPlaybackViewController *playbackVC = [[EZPlaybackViewController alloc] init];
            playbackVC.deviceInfo = deviceInfo;
            [self.navigationController pushViewController:playbackVC animated:YES];
        } else {
            EZCameraTableViewController *cameraListVC = [[EZCameraTableViewController alloc] init];
            cameraListVC.deviceInfo = deviceInfo;
            cameraListVC.playType = EZPlayTypePlayBack;
            [self.navigationController pushViewController:cameraListVC animated:YES];
        }
    } else if (deviceInfo.subDeviceInfo.count > 0) {// 子设备
        EZCameraTableViewController *cameraListVC = [[EZCameraTableViewController alloc] init];
        cameraListVC.deviceInfo = deviceInfo;
        cameraListVC.playType = EZPlayTypePlayBack;
        [self.navigationController pushViewController:cameraListVC animated:YES];
    }
}

/** 消息 */
- (void)go2Message:(EZDeviceInfo *)deviceInfo {
    EZMessageListViewController *messageVC = [[EZMessageListViewController alloc] init];
    messageVC.deviceInfo = deviceInfo;
    [self.navigationController pushViewController:messageVC animated:YES];
}

/** 设置 */
- (void)go2Setting:(EZDeviceInfo *)deviceInfo {
    EZSettingViewController *settingVC = [[EZSettingViewController alloc] init];
    settingVC.deviceInfo = deviceInfo;
    [self.navigationController pushViewController:settingVC animated:YES];
}

/** 视频通话 */
- (void)go2VideoTalk:(EZDeviceInfo *)deviceInfo {
    EZJoinMeetingViewController *joinMeetingVC = [[EZJoinMeetingViewController alloc] init];
    joinMeetingVC.cameraInfo = [deviceInfo.cameraInfo dd_objectAtIndex:0];
    [self.navigationController pushViewController:joinMeetingVC animated:YES];
}

- (void)go2HubDebugWith:(EZPlayType)playType deviceInfo:(EZDeviceInfo *)deviceInfo {
    EZHubDebugViewController *hubDebugVC = [[EZHubDebugViewController alloc] init];
    hubDebugVC.playType = playType;
    hubDebugVC.deviceInfo = deviceInfo;
    [self.navigationController pushViewController:hubDebugVC animated:YES];
}

/** 我的/分享Tab 切换 */
- (IBAction)segmentControl:(id)sender {
    isSharedDevice = self.segmentedControl.selectedSegmentIndex == 1;
    [self.tableView.header beginRefreshing];
}

/** 新增设备 */
- (IBAction)go2AddDevice:(id)sender {
    EZAddByQRCodeViewController *qrCodeVC = [[EZAddByQRCodeViewController alloc] init];
    [self.navigationController pushViewController:qrCodeVC animated:YES];
}

/** 多通道预览 */
- (IBAction)go2MultiPlay:(id)sender {
    EZMultiChannelRealPlayVC *vc = [[EZMultiChannelRealPlayVC alloc] initWithDevices:self.deviceArray];
    [self.navigationController pushViewController:vc animated:YES];
}

/** 测试页面 */
- (IBAction)go2TestVC:(id)sender {
    EZTestVC *testVC = [[EZTestVC alloc] init];
    testVC.deviceArray = self.deviceArray;
    [self.navigationController pushViewController:testVC animated:YES];
}

/** 退出 */
- (IBAction)exitAction:(id)sender {
    [self showAlertWithTitle:NSLocalizedString(@"login_exit", @"确定退出登录")
                     message:nil
           appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.addActionCancelTitle(NSLocalizedString(@"cancel", @"取消") );
        alertMaker.addActionDefaultTitle(NSLocalizedString(@"done", @"确定") );
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 1) {
            // 自动化测试的时候不响应。
            if ([kUserDefaults boolForKey:EZAutoTest]) {
                return;
            }
            [EZOPENSDK logout:^(NSError *error) {
                
            }];
            [[GlobalKit shareKit] removeLastSDKInitParams];
            
            MainViewController *mainVC = [[MainViewController alloc] init];
            kKeyWindow.rootViewController = mainVC;
        }
    }];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EZDeviceCell" forIndexPath:indexPath];
    
    EZDeviceInfo *info = [self.deviceArray dd_objectAtIndex:indexPath.row];
    cell.deviceInfo = info;
    cell.parentViewController = self;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 73.0 * [UIScreen mainScreen].bounds.size.width/320.0f;
}

#pragma mark - setter & getter

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

@end
