//
//  MessageListViewController.m
//  GotoBus
//
//  Created by vae on 2018/5/21.
//
#import "MessageListViewController.h"
#import "SDK.h"
#import "Lang.h"
#import "CocoaUtils.h"
#import "DZNEmptyDataSetDefault.h"
#import "UIToolkit.h"
#import "AppNotification.h"
#import "Utility.h"
#import "BeanUtils.h"
#import "NotificationApi.h"
#import "MessageTableViewCell.h"
#import "MessageSetViewController.h"
#import "DrawUtils.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <YYModel/YYModel.h>
#import <MJRefresh/MJRefresh.h>
#import <libextobjc/EXTScope.h>
#import "Vars.h"
#import "NotificationApi.h"
#import "NotificationData.h"
#import "MessageResponseJsonMapper.h"
#import "AppLocalConfig.h"
#import "InterceptionManager.h"

@interface MessageListViewController () <DZNEmptyDataSetDefault,MessageTableViewCellDelegate>
@property(nonatomic, strong) NSMutableArray *messageListArray;
@property (nonatomic, strong) NSMutableArray *cellDataArray;
@property (nonatomic, strong) UIButton *messageButton;
@property(nonatomic, assign) NSInteger pageNo;
@end

@implementation MessageListViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"Notification History");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	if (self.message) {
		[self.messageListArray addObject:self.message];
	}
	[self buildCellDataSource];
	if ([AppLocalConfig sharedInstance].hasUnreadMessage) {
		[self markUnreadMessage];
	}
	@weakify(self)

	UIColor *buttonColor;
	if ([Vars is_bus_site]) {
		buttonColor = [UIColor whiteColor];
	}else{
		buttonColor = [Vars defaultTintColor];
	}
	UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeCustom];
	[messageButton setBackgroundImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome cogIconWithSize:20] fillColor:buttonColor] forState:UIControlStateNormal];
	[messageButton bk_addEventHandler:^(id  _Nonnull sender) {
		@strongify(self)
		[self performSegueWithViewControllerClass:[MessageSetViewController class]];
	} forControlEvents:UIControlEventTouchUpInside];
	[messageButton sizeToFit];
	UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:messageButton];
	self.messageButton = messageButton;
	self.navigationItem.rightBarButtonItem = rightBarButtonItem;
	
	self.tableView.emptyDataSetSource = self;
	MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadMessageList)];
	refreshHeader.automaticallyChangeAlpha = YES;
	refreshHeader.lastUpdatedTimeLabel.hidden = YES;
	self.tableView.mj_header = refreshHeader ;
	
	MJRefreshBackNormalFooter *refreshFooter =[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreMessages)];
	refreshFooter.automaticallyChangeAlpha = YES;
	self.tableView.mj_footer = refreshFooter;
	
	[self.tableView.mj_header beginRefreshing];
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MessageTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([MessageTableViewCell class])];
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
}

#pragma mark - NetWork
-(void)reloadMessageList{
	
	[self.messageListArray removeAllObjects];
	
	GetUserMessages *getUserMessages = [[GetUserMessages alloc] init];
	getUserMessages.pageNo = 1;
	getUserMessages.pageSize = 20;
	self.pageNo = 1;
	
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:getUserMessages];
	@weakify(self)
	[Utility performRESTRequestWithMethod:@"POST" url:getUserMessages.address parameters:requestDict beforeSend:nil success:^(id jsonObject) {
		@strongify(self)
		MessageResponseJsonMapper *mapper = [[MessageResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]){
			GetUserMessagesResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.errorMessage]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
				return ;
			}
			else {
				if ([AppLocalConfig sharedInstance].hasUnreadMessage) {
					[AppLocalConfig sharedInstance].hasUnreadMessage = NO;
					[[NSNotificationCenter defaultCenter] postNotificationName:UnreadMessageNotification object:nil];
				}
				[self.messageListArray addObjectsFromArray:response.messages];
				[self buildCellDataSource];
			}
		}
	} complete:^{
		[self.tableView.mj_header endRefreshing];
	}];
}

-(void)loadMoreMessages{
	GetUserMessages *getUserMessages = [[GetUserMessages alloc] init];
	getUserMessages.pageNo = ++self.pageNo;
	getUserMessages.pageSize = 20;
	@weakify(self)
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:getUserMessages];
	[Utility performRESTRequestWithMethod:@"POST" url:getUserMessages.address parameters:requestDict beforeSend:nil success:^(id jsonObject) {
		@strongify(self)
		MessageResponseJsonMapper *mapper = [[MessageResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]){
			GetUserMessagesResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.errorMessage]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
				return ;
			}
			else {
				if ([AppLocalConfig sharedInstance].hasUnreadMessage) {
					[AppLocalConfig sharedInstance].hasUnreadMessage = NO;
					[[NSNotificationCenter defaultCenter] postNotificationName:UnreadMessageNotification object:nil];
				}
				[self.messageListArray addObjectsFromArray:response.messages];
				[self buildCellDataSource];
				[self.tableView reloadData];
			}
		}
	} complete:^{
		[self.tableView.mj_footer endRefreshing];

	}];
}

-(void)deleteMessageWithIndexPath:(NSIndexPath *)indexPath{
	DeleteMessages *deleteMessage = [[DeleteMessages alloc] init];
	Message *message = self.messageListArray[indexPath.row];
	deleteMessage.id = message.id;
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:deleteMessage];
	
	[Utility performRESTRequestWithMethod:@"POST" url:deleteMessage.address parameters:requestDict beforeSend:nil success:^(id jsonObject) {
		DeleteMessagesReponse *response = [DeleteMessagesReponse yy_modelWithJSON:jsonObject];
		if (![StringUtils isEmpty:response.errorMessage]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
			return ;
		}
	} complete:nil];
	
	[self.messageListArray removeObjectAtIndex:indexPath.row];
	[self.cellDataArray removeObjectAtIndex:indexPath.row];
	[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	
}

-(void)markUnreadMessage{
	MarkUserMessagesRead *markUserMessage = [[MarkUserMessagesRead alloc] init];
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:markUserMessage];
	[Utility performRESTRequestWithMethod:@"POST" url:markUserMessage.address parameters:requestDict beforeSend:nil success:nil complete:nil];
}

#pragma mark - property
-(NSMutableArray *)messageListArray{
	if (!_messageListArray) {
		_messageListArray = [NSMutableArray array];
	}
	return  _messageListArray;
}

#pragma mark - Private

-(void)buildCellDataSource{
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (Message *message in self.messageListArray) {
		NotificationData *notificaitonData =  message.data;
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([MessageTableViewCell class]);
		data.isCustomRegistered = YES;
		data.usesAutomaticDimension = YES;
		[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, MessageTableViewCell *cell) {
			cell.titleLabel.text = message.title;
			cell.contentLabel.text = message.content;
			cell.timeLabel.text = message.notificationTime;
			if ([StringUtils isEmpty:notificaitonData.absolute_url]){
				cell.detailView.hidden = NO;
			} else {
				cell.detailView.hidden = YES;
			}
			
			cell.delegate = self;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
		}];
		
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			if (![StringUtils isEmpty:notificaitonData.absolute_url]){
				[self performSegueForWebViewController:notificaitonData.absolute_url];
			}
		}];
		[array addObject:data];
	}
	self.cellDataArray = array;
	[self.tableView reloadData];
}


#pragma mark - Segue

- (void)performSegueForWebViewController:(NSString *)urlString{
	BOOL isHandle = [[InterceptionManager sharedManager] handleUrlString:urlString];;
	if (!isHandle) {
		IMWebViewController *webviewController =  [[IMWebViewController alloc] initWithURLString:urlString];
		webviewController.hidesBottomBarWhenPushed = YES;
		[self.navigationController pushViewController:webviewController animated:YES];
	}
}


#pragma mark - Table view methods

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

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

//iOS 11 以上
- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
	//删除
	@weakify(self)
	UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
		@strongify(self)
		[self deleteMessageWithIndexPath:indexPath];
		completionHandler (YES);
	}];
	deleteRowAction.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome trashIconWithSize:20] fillColor:[UIColor whiteColor]];
	deleteRowAction.backgroundColor = [Vars defaultTintColor];

	UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:
										   @[deleteRowAction]];
	return config;
}

// iOS 11以下
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
	if (@available(iOS 10, *)) {
		UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
		[feedBackGenertor impactOccurred];
	}
	@weakify(self)
	UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
		@strongify(self)
		[self deleteMessageWithIndexPath:indexPath];
	}];
	deleteRowAction.backgroundColor = [UIColor redColor];
	return @[deleteRowAction];
}



#pragma mark - MessageTableViewCellDelegate
-(void)detailMessagewithCell:(MessageTableViewCell *)cell{
	NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//	Message *message = self.messageListArray[indexPath.row];
//	[self performSegueForWebViewController:message.viewUrl];
}

#pragma mark -performsegue
- (void)performSegueWithViewControllerClass:(Class)class {
	UIViewController *viewController = [[class alloc] init];
	[self.navigationController pushViewController:viewController animated:YES];
}




@end
