//
//  MessageViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2017/2/16.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageTableViewCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


/**
 查询对象
 */
@property (nonatomic,strong) NoticeCondition *messageModel;

/**
 结果对象
 */
@property (nonatomic,strong) NoticeResponse *resultModel;

/**
 数据源
 */
@property (nonatomic,strong) NSMutableArray *messageArray;

@end

@implementation MessageViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    [self.meesageTableView.mj_header beginRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self setUpRefreshAction];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.meesageTableView.tableFooterView = [UIView new];
    [self.timeOrderButton addTarget:self action:@selector(timeOrderClickAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Refresh
- (void)setUpRefreshAction
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        [weakSelf.meesageTableView.mj_footer resetNoMoreData];
        weakSelf.messageModel.page.page = ONE;
        [weakSelf getAllMessageDatas:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.meesageTableView.mj_header = headerRefresh;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (++ weakSelf.messageModel.page.page > weakSelf.resultModel.totalpages) {
            [weakSelf.meesageTableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [weakSelf getAllMessageDatas:NO];
        }
    }];
    footer.automaticallyHidden = YES;
    self.meesageTableView.mj_footer = footer;
}

#pragma mark -获取数据
- (void)getAllMessageDatas:(BOOL)isRemove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
   [HTTP networkRequestWithURL:SERVERREQUESTURL(MESSAGELIST) withRequestType:0 withParameter:self.messageModel withReturnValueBlock:^(id returnValue) {
       
       [XBLoadingView hideHUDViewWithDefault];
       weakSelf.meesageTableView.emptyDataSetSource = weakSelf;
       weakSelf.meesageTableView.emptyDataSetDelegate = weakSelf;
       [weakSelf endRefreshingForTableView:weakSelf.meesageTableView];
       if (RESULT(returnValue)) {
           if (isRemove) {
               [weakSelf.messageArray removeAllObjects];
           }
           weakSelf.resultModel = [[NoticeResponse alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
           [weakSelf.messageArray addObjectsFromArray:weakSelf.resultModel.noticeEntity];
           [weakSelf.meesageTableView reloadData];
       }else {
           [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
       }
       
   } withFailureBlock:^(NSError *error) {
       [XBLoadingView showHUDViewWithText:error.localizedDescription];
   }];
}

#pragma mark -设为已读
- (void)readedMessage:(NSString *)messageId withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(MESSAGE_READ),messageId,[Shoppersmanager manager].shoppers.employee.fid] withRequestType:0 withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            TONoticeEntity *entity = weakSelf.messageArray[indexPath.row];
            entity.readed = YES;
            [weakSelf cornerMarkIsShow];
            [weakSelf configCell:[weakSelf.meesageTableView cellForRowAtIndexPath:indexPath] withIndexPath:indexPath];
            [weakSelf.meesageTableView reloadData];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageTableViewCell *messageCell = [tableView dequeueReusableCellWithIdentifier:@"MessageTableViewCell" forIndexPath:indexPath];
    [self configCell:messageCell withIndexPath:indexPath];
    return messageCell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WS(weakSelf);
    TONoticeEntity *entity = self.messageArray[indexPath.row];
    if (!entity.readed) {
        ShowAlertView(@"提示", @"是否设置为已读", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ONE) {
                return;
            }
            TONoticeEntity *entity = weakSelf.messageArray[indexPath.row];
            [weakSelf readedMessage:entity.fid withIndexPath:indexPath];
        });
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return [tableView fd_heightForCellWithIdentifier:@"MessageTableViewCell" cacheByIndexPath:indexPath configuration:^(id cell) {
        [self configCell:cell withIndexPath:indexPath];
    }];
}


#pragma mark -cell赋值
- (void)configCell:(MessageTableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    TONoticeEntity *entity = self.messageArray[indexPath.row];
    cell.isReadedImageView.hidden = entity.readed;
    cell.messageLabel.text = entity.message;
    cell.releaseTimeLabel.text = entity.createDate;
}

#pragma mark --设置已读，未读个数减一
- (void)cornerMarkIsShow
{
    [Notification postNotificationName:MESSAGE_COUNT object:@1];
}


#pragma mark -时间排序
- (void)timeOrderClickAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.messageModel.order = sender.selected?SORTDIRECTION_ASC:SORTDIRECTION_DESC;
    [self.meesageTableView.mj_header beginRefreshing];
}

#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}

#pragma mark -lazy
- (NoticeCondition *)messageModel
{
    if (!_messageModel) {
        _messageModel = [[NoticeCondition alloc] init];
        DataPage *page = [[DataPage alloc] init];
        page.page = ZERO;
        page.rows = KROWS;
        _messageModel.sort = @"createDate";
        _messageModel.order = SORTDIRECTION_DESC;
        _messageModel.page = page;
        _messageModel.employeeId = [Shoppersmanager manager].shoppers.employee.fid;
    }
    return _messageModel;
}

- (NSMutableArray *)messageArray
{
    if (!_messageArray) {
        _messageArray = [NSMutableArray array];
    }
    return _messageArray;
}

@end
