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

#import "EZMessageListViewController.h"

#import "MJRefresh.h"
#import "MessageListCell.h"
#import "MBProgressHUD.h"
#import "EZMessagePhotoViewController.h"

#define EZMessageListPageSize 10

@interface EZMessageListViewController () {
    NSInteger currentIndex;///< 页码
    
    NSDate *beginTime;
    NSDate *endTime;
}
@property (nonatomic, strong) NSMutableArray<EZAlarmInfo *> *messageList;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<EZAlarmInfo *> *> *messageArrayList;/// < 消息二维数组
@property (nonatomic, strong) NSMutableArray<EZAlarmInfo *> *selectedMessageArray;

@property (nonatomic, weak) IBOutlet UIImageView *noMessage;
@property (nonatomic, weak) IBOutlet UILabel *noMessageLabel;
@property (nonatomic, weak) IBOutlet UIBarButtonItem *deleteSelected;
@property (nonatomic, weak) IBOutlet UIBarButtonItem *readAll;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *editButton;

@end

@implementation EZMessageListViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"dmessage_title", @"消息");
    self.navigationItem.rightBarButtonItem = nil;
    
    // 获取过去7天的告警消息，开发者可以自己设置时间范围。
    endTime = [NSDate date];
    beginTime = [endTime dateBySubtractingDays:7];
    
    self.tableView.tableFooterView = [UIView new];
    [self addRefreshKit];
    [self.tableView addSubview:self.noMessage];
    [self.tableView addSubview:self.noMessageLabel];
    self.noMessage.frame = CGRectMake((self.tableView.width - 94)/2.0, self.tableView.centerY - 150, 94, 94);
    self.noMessageLabel.frame = CGRectMake((self.tableView.width - 100)/2.0, self.noMessage.y + self.noMessage.height + 10, 100, 20.0);
    
    [self getUnreadMessageCount];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.tableView.allowsMultipleSelectionDuringEditing) {
        [self editTableView:self.navigationItem.rightBarButtonItem];
    }
}

#pragma mark - MJRefresh Methods

- (void)addRefreshKit {
    EZWeak(self);
    self.tableView.header.automaticallyChangeAlpha = YES;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        EZStrong(self);
        endTime = [NSDate date];
        beginTime = [endTime dateBySubtractingDays:7];
        strongself->currentIndex = 0;
        [strongself getAlarmList];
    }];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        EZStrong(self);
        strongself->currentIndex++;
        [strongself getAlarmList];
    }];
    [self.tableView.header beginRefreshing];
}

#pragma mark - Request

/** 获取未读消息总数 */
- (void)getUnreadMessageCount {
    [EZOPENSDK getUnreadMessageCount:self.deviceInfo.deviceSerial messageType:EZMessageTypeAlarm completion:^(NSInteger count, NSError *error) {
        self.title = [NSString stringWithFormat:@"%@（%d）",NSLocalizedString(@"dmessage_title", @"消息"), (int)count];
    }];
}

/** 获取消息列表 */
- (void)getAlarmList {
    [EZOPENSDK getAlarmList:self.deviceInfo.deviceSerial
                  pageIndex:currentIndex
                   pageSize:EZMessageListPageSize
                  beginTime:beginTime
                    endTime:endTime
                 completion:^(NSArray *alarmList, NSInteger alarmCount, NSError *error) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if (currentIndex == 0) {
            [self.messageList removeAllObjects];
        }
        [self.messageList addObjectsFromArray:alarmList];
        if (self.messageList.count > 0) {
            self.navigationItem.rightBarButtonItem = self.editButton;
        }
        if (alarmList.count < EZMessageListPageSize) {
            [self.tableView.footer endRefreshingWithNoMoreData];
        }
        [self handleMessageList];
    }];
}

#pragma mark - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageCell" forIndexPath:indexPath];
    cell.deviceSerial = self.deviceInfo.deviceSerial;
    EZAlarmInfo *info = self.messageArrayList[indexPath.section][indexPath.row];
    [cell setAlarmInfo:info];
    if (tableView.allowsMultipleSelectionDuringEditing) {
        if ([self.selectedMessageArray containsObject:info]) {
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        } else {
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
        }
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EZAlarmInfo *info = self.messageArrayList[indexPath.section][indexPath.row];
    if (tableView.allowsMultipleSelectionDuringEditing) {// 编辑状态下
        [self refreshBottomToolbarDuringEditing:info];
    } else {// 不在编辑状态下
        MessageListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [self performSegueWithIdentifier:@"go2MessagePhoto" sender:@{@"image":cell.actionImageView.image?:[UIImage new], @"alarmInfo":info}];
        [self getUnreadMessageCount];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.allowsMultipleSelectionDuringEditing) {
        EZAlarmInfo *info = self.messageArrayList[indexPath.section][indexPath.row];
        [self refreshBottomToolbarDuringEditing:info];
    }
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSMutableArray<EZAlarmInfo *> *messages = [self.messageArrayList dd_objectAtIndex:section];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
    NSString *key = [messages.lastObject.alarmStartTime formattedDateWithFormat:MdFormat];
    headerLabel.text = [NSString stringWithFormat:@"  %@",key];
    headerLabel.font = [UIFont systemFontOfSize:14.0f];
    headerLabel.backgroundColor = [UIColor dd_hexStringToColor:@"0xf0f0f3"];
    return headerLabel;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EZAlarmInfo *info = self.messageArrayList[indexPath.section][indexPath.row];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = NSLocalizedString(@"message_deleting", @"正在删除，请稍候...");
        [EZOPENSDK deleteAlarm:@[info.alarmId] completion:^(NSError *error) {
            [hud hide:YES];
            [self.messageList removeObject:info];
            [self handleMessageList];
        }];
    }
}

#pragma mark - Action Methods

/** 右上角编辑/取消Action */
- (IBAction)editTableView:(id)sender {
    if (self.tableView.editing) {
        self.tableView.allowsMultipleSelectionDuringEditing = NO;
        [self.tableView setEditing:NO animated:YES];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editTableView:)];
        [self.navigationController setToolbarHidden:YES animated:YES];
        self.deleteSelected.title = NSLocalizedString(@"delete", @"删除");
        self.deleteSelected.enabled = NO;
        self.readAll.title = NSLocalizedString(@"message_read", @"标记已读");
        self.readAll.enabled = NO;
        [self.selectedMessageArray removeAllObjects];
        self.tableView.header.hidden = NO;
        self.tableView.footer.hidden = NO;
    } else {
        self.tableView.allowsMultipleSelectionDuringEditing = YES;
        [self.tableView setEditing:YES animated:YES];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(editTableView:)];
        [self.navigationController setToolbarHidden:NO animated:YES];
        self.tableView.header.hidden = YES;
        self.tableView.footer.hidden = YES;
        self.deleteSelected.enabled = NO;
        self.readAll.enabled = NO;
    }
}

/** 删除Action */
- (IBAction)deleteMessage:(id)sender {
    if (self.selectedMessageArray.count >= 10) {
        [EZToast show:NSLocalizedString(@"message_count_limit", @"数量不能超过10")];
        return;
    }
    [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", @"正在删除，请稍候...");
            NSMutableArray *alarmIds = [NSMutableArray new];
            for (int i = 0; i < self.selectedMessageArray.count; i++) {
                EZAlarmInfo *info = [self.selectedMessageArray dd_objectAtIndex:i];
                [alarmIds addObject:info.alarmId];
            }
            [EZOPENSDK deleteAlarm:alarmIds completion:^(NSError *error) {
                if (error) {
                    hud.labelText = error.localizedDescription;
                    hud.mode = MBProgressHUDModeText;
                    [hud hide:YES afterDelay:1.2];
                } else {
                    [hud hide:YES];
                }
                [self.messageList removeObjectsInArray:self.selectedMessageArray];
                [self editTableView:self.navigationItem.rightBarButtonItem];
                if (self.messageList.count > 0) {
                    [self handleMessageList];
                } else {
                    [self.tableView.header beginRefreshing];
                }
            }];
        }
    }];
}

/** 已读Action */
- (IBAction)readMessage:(id)sender {
    if (self.selectedMessageArray.count > 10) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.userInteractionEnabled = NO;
        hud.labelText = NSLocalizedString(@"message_count_limit", @"数量不能超过10");
        [hud show:YES];
        [hud hide:YES afterDelay:1.0f];
        return;
    }
    __weak MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.userInteractionEnabled = NO;
    hud.labelText = NSLocalizedString(@"message_setting", @"正在设置已读，请稍候...");
    NSMutableArray *alarmIds = [NSMutableArray new];
    for (int i = 0; i < self.selectedMessageArray.count; i++) {
        EZAlarmInfo *info = [self.selectedMessageArray dd_objectAtIndex:i];
        [alarmIds addObject:info.alarmId];
    }
    [EZOPENSDK setAlarmStatus:alarmIds
                  alarmStatus:EZMessageStatusRead
                   completion:^(NSError *error) {
                       if (error) {
                           hud.labelText = error.localizedDescription;
                           hud.mode = MBProgressHUDModeText;
                           [hud hide:YES afterDelay:1.2];
                       } else {
                           [hud hide:YES];
                       }
                       if (!error) {
                           for (int i = 0; i < self.selectedMessageArray.count; i++) {
                               EZAlarmInfo *info = [self.selectedMessageArray dd_objectAtIndex:i];
                               info.isRead = YES;
                           }
                           [self editTableView:self.navigationItem.rightBarButtonItem];
                           [self.tableView reloadData];
                           [self getUnreadMessageCount];
                       }
    }];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSDictionary *dict = sender;
    EZAlarmInfo *info = dict[@"alarmInfo"];
    if (!info.isRead){
        [EZOPENSDK setAlarmStatus:@[info.alarmId] alarmStatus:EZMessageStatusRead completion:^(NSError *error) {
            if (!error) {
                info.isRead = YES;
                [self.tableView reloadData];
            }
        }];
    }
    EZMessagePhotoViewController *nextVC = [segue destinationViewController];
    nextVC.image = dict[@"image"];
    nextVC.info = info;
    nextVC.deviceInfo = self.deviceInfo;
}

#pragma mark - Custom Methods

/** 数据组装 */
- (void)handleMessageList {
    NSMutableArray *sectionArray = [NSMutableArray array];
    for (int i = 0; i < self.messageList.count; i++) {
        EZAlarmInfo *info = [self.messageList dd_objectAtIndex:i];
        NSMutableArray<EZAlarmInfo *> *lastArrayM = [sectionArray lastObject];
        if (lastArrayM == nil) {
            lastArrayM = [NSMutableArray array];
            [sectionArray addObject:lastArrayM];
        }
        if (kArrayIsEmpty(lastArrayM)) {// 如果数组未空，说明是第一个数据，直接添加到数组中即可
            [lastArrayM addObject:info];
        } else if ([[info.alarmStartTime formattedDateWithFormat:yMdFormat] isEqualToString:[[lastArrayM lastObject].alarmStartTime formattedDateWithFormat:yMdFormat]]) {// 与最后一个元素日期相同
            [lastArrayM addObject:info];
        } else {// 与最后一个元素日期不同，创建一个新数组
            NSMutableArray<EZAlarmInfo *> *arrayM = [NSMutableArray array];
            [arrayM addObject:info];
            [sectionArray addObject:arrayM];
        }
    }
    self.messageArrayList = sectionArray;
    [self.tableView reloadData];
    self.noMessage.hidden = self.messageList.count > 0;
    self.noMessageLabel.hidden = self.noMessage.hidden;
}

/** 刷新底部工具栏 */
- (void)refreshBottomToolbarDuringEditing:(EZAlarmInfo *)info {
    if ([self.selectedMessageArray containsObject:info]) {
        [self.selectedMessageArray removeObject:info];
    } else {
        [self.selectedMessageArray addObject:info];
    }
    if (self.selectedMessageArray.count > 0) {
        self.deleteSelected.title = [NSString stringWithFormat:@"%@(%d)",NSLocalizedString(@"delete", @"删除"),(int)[self.selectedMessageArray count]];
        self.deleteSelected.enabled = YES;
        self.readAll.title = [NSString stringWithFormat:@"%@(%d)",NSLocalizedString(@"message_read", @"标记已读"),(int)[self.selectedMessageArray count]];
        self.readAll.enabled = YES;
    } else {
        self.deleteSelected.title = NSLocalizedString(@"delete", @"删除");
        self.deleteSelected.enabled = NO;
        self.readAll.title = NSLocalizedString(@"message_read", @"标记已读");
        self.readAll.enabled = NO;
    }
}

#pragma mark - getter & setter

- (NSMutableArray *)messageList {
    if (!_messageList) {
        _messageList = [NSMutableArray array];
    }
    return _messageList;
}

- (NSMutableArray *)selectedMessageArray {
    if (!_selectedMessageArray) {
        _selectedMessageArray = [NSMutableArray array];
    }
    return _selectedMessageArray;
}

@end
