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

#import "EZDeviceTableViewController.h"
#import "EZBusinessTool.h"

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

#import "MJRefresh.h"
#import "DeviceListCell.h"
#import "EZDeviceSearchFilterView.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 50

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

@property (nonatomic, strong) NSMutableArray *deviceArray;         ///< 原始设备列表
@property (nonatomic, strong) NSMutableArray *filteredDeviceArray;  ///< 筛选后的设备列表

// 搜索筛选视图
@property (nonatomic, strong) EZDeviceSearchFilterView *searchFilterView;

@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];
    
    // 创建搜索筛选视图
    self.searchFilterView = [[EZDeviceSearchFilterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90)];
    self.searchFilterView.delegate = self;
    self.searchFilterView.layer.zPosition = 1; // 确保在cell上方
    [self.tableView addSubview:self.searchFilterView];
    
    // 用一个空的tableHeaderView占位，高度=搜索区域高度，让cell从搜索区域下方开始
    UIView *spacer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 90)];
    spacer.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = spacer;
    
    if ([EZOPENSDK isLogin]) {
        [self addRefreshKit];
    }
}

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

#pragma mark - EZDeviceSearchFilterDelegate

- (void)searchFilterView:(EZDeviceSearchFilterView *)view
      didChangeWithKeyword:(NSString *)keyword
            statusFilter:(EZStatusFilter)statusFilter
           channelFilter:(EZChannelFilter)channelFilter {
    [self applyFilterWithKeyword:keyword statusFilter:statusFilter channelFilter:channelFilter];
}

#pragma mark - Filter Logic | 筛选逻辑

- (void)applyFilterWithKeyword:(NSString *)keyword statusFilter:(EZStatusFilter)statusFilter channelFilter:(EZChannelFilter)channelFilter {
    [self.filteredDeviceArray removeAllObjects];
    for (EZDeviceInfo *device in self.deviceArray) {
        if ([self device:device matchesKeyword:keyword statusFilter:statusFilter channelFilter:channelFilter]) {
            [self.filteredDeviceArray addObject:device];
        }
    }
    [self.tableView reloadData];
}

- (BOOL)device:(EZDeviceInfo *)device matchesKeyword:(NSString *)keyword statusFilter:(EZStatusFilter)statusFilter channelFilter:(EZChannelFilter)channelFilter {
    // 关键词过滤
    if (keyword.length > 0) {
        NSString *serial = device.deviceSerial ? device.deviceSerial.lowercaseString : @"";
        NSString *name = device.deviceName ? device.deviceName.lowercaseString : @"";
        NSString *kw = keyword.lowercaseString;
        if (![serial containsString:kw] && ![name containsString:kw]) {
            return NO;
        }
    }
    // 在线状态过滤
    if (statusFilter == EZStatusFilterOnline && device.status != 1) return NO;
    if (statusFilter == EZStatusFilterOffline && device.status == 1) return NO;
    // 通道过滤
    if (channelFilter == EZChannelFilterSingle && device.cameraNum > 1) return NO;
    if (channelFilter == EZChannelFilterMulti && device.cameraNum <= 1) return NO;
    return YES;
}

/// 使用当前筛选条件刷新列表（数据请求完成后调用）
- (void)applyFilter {
    [self applyFilterWithKeyword:self.searchFilterView.searchKeyword
                    statusFilter:self.searchFilterView.statusFilter
                   channelFilter:self.searchFilterView.channelFilter];
}

#pragma mark - Refresh | 刷新

- (void)addRefreshKit {
    EZWeak(self);
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        EZStrong(self);
        if (!strongself) return;
        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);
        if (!strongself) return;
        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 applyFilter];
            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 applyFilter];
        }
    }];
}

/** 获取设备列表接口 */
- (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 applyFilter];
    if (deviceList.count < EZDeviceListPageSize) {
        [self.tableView.footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Actions | 点击事件

/** 点击列表图片进入预览页面 */
- (void)go2Play:(EZDeviceInfo *)deviceInfo {    
    if ([EZBusinessTool isHubDevice:deviceInfo.deviceType]) {// HUB设备，手动输入信息进行预览，普通开发者无视此分支
        [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 ([EZBusinessTool isHubDevice:deviceInfo.deviceType]) {
        [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];
}

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

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

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

/** 退出账号 | exit account  */
- (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.filteredDeviceArray count];
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 92.0;
}

// 搜索区域始终固定在tableView可见区域顶部
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGRect frame = self.searchFilterView.frame;
    frame.origin.y = MAX(0, offsetY);
    self.searchFilterView.frame = frame;
}

// 点击空白区域收起键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.searchFilterView resignSearchFocus];
}

#pragma mark - setter & getter

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

- (NSMutableArray *)filteredDeviceArray {
    if (!_filteredDeviceArray) {
        _filteredDeviceArray = [NSMutableArray array];
    }
    return _filteredDeviceArray;
}

@end
