//
//  AnnouncementViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/11/14.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "AnnouncementViewController.h"
#import "AnnouncementTableViewCell.h"
#import "ScreeningButton.h"
#import "AnnountcementDetailViewController.h"

@interface AnnouncementViewController ()<UITableViewDelegate,UITableViewDataSource,ReturnTableviewcellIndexpathdelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

/**
 公告请求
 */
@property (nonatomic,strong) AfficheCondition *afficheModel;

/**
 公告结果
 */
@property (nonatomic,strong) NSMutableArray *afficheArray;

/**
 总页数
 */
@property (nonatomic,assign) NSInteger totalPage;

/**
 时间
 */
@property (nonatomic,strong) NSMutableArray *timeArray;

/**
 类别
 */
@property (nonatomic,strong) NSMutableArray *typeArray;

@property (nonatomic,strong) ScreeningButton *dateButton;
@property (nonatomic,strong) ScreeningButton *typeButton;

@end

@implementation AnnouncementViewController

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

#pragma mark - UITableView
- (void)setUpTableView
{
    self.announcementTableView.tableFooterView = [UIView new];
    self.announcementTableView.rowHeight = 80;
}

#pragma mark - 筛选
- (void)setUpChooseView
{
    self.dateButton = [ScreeningButton buttonWithType:UIButtonTypeCustom];
    self.dateButton.frame = CGRectMake(ScreenWidth-400, 15, 150, 30);
    [self.dateButton setTitle:@"时间" forState:UIControlStateNormal];
    [self.dateButton addTarget:self action:@selector(dateChooseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.typeButton = [ScreeningButton buttonWithType:UIButtonTypeCustom];
    self.typeButton.frame = CGRectMake(ScreenWidth-200, 15, 150, 30);
    [self.typeButton setTitle:@"类别" forState:UIControlStateNormal];
    [self.typeButton addTarget:self action:@selector(typeChooseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.chooseBackgroundView addSubview:self.dateButton];
    [self.chooseBackgroundView addSubview:self.typeButton];
}


#pragma mark - 时间选择
- (void)dateChooseButtonClick:(UIButton *)sender
{
    [self showPopoverViewController:CGSizeMake(150, 200) withdatas:self.timeArray showButton:sender buttonCode:0];
}

#pragma mark - 类别选择
- (void)typeChooseButtonClick:(UIButton *)sender
{
    [self showPopoverViewController:CGSizeMake(150, 200) withdatas:self.typeArray showButton:sender buttonCode:1];
}

#pragma mark - 时间排序
- (IBAction)dateSortButtonClickAction:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    self.afficheModel.order = sender.selected?SORTDIRECTION_ASC:SORTDIRECTION_DESC;
    [self.announcementTableView.mj_header beginRefreshing];
}

#pragma mark -弹出popover视图控制器
- (void)showPopoverViewController:(CGSize)size withdatas:(NSArray *)datasArray showButton:(UIButton *)button buttonCode:(NSInteger)code
{
    PopoverViewController *popover = [[PopoverViewController alloc]init];
    popover.datasArray = datasArray;
    popover.delegate = self;
    popover.contentSize = size;
    popover.isString = YES;
    popover.selectedindex = code;
    popover.preferredContentSize = size;
    popover.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = popover.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = popover.view;
    pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [self presentViewController:popover animated:YES completion:nil];
}

#pragma mark -选中筛选条件回传typecode
- (void)returnCellindexpathwithrow:(NSString *)type withCellTitle:(NSString *)title withSelected:(NSInteger)selected
{
    //时间
    if (selected == 0) {
        self.afficheModel.dayCountEquals = [self timeString:title];
        [self.dateButton setTitle:title forState:UIControlStateNormal];
    }else
    {//类型
        self.afficheModel.afficheTypeEuals = [title isEqualToString:@"全部"]?nil:title;
        [self.typeButton setTitle:title forState:UIControlStateNormal];
    }
    [self.announcementTableView.mj_header beginRefreshing];
}

#pragma mark - 时间转换
- (NSInteger)timeString:(NSString *)string
{
    NSInteger dayCount = 0;
    if ([string isEqualToString:@"全部"]) {
        dayCount = 0;
    }
    if ([string isEqualToString:@"近三天"]) {
        dayCount = 3;;
    }
    if ([string isEqualToString:@"近一周"]) {
        dayCount = 7;
    }
    if ([string isEqualToString:@"近一个月"]) {
        dayCount = 30;
    }
    return dayCount;
}

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

#pragma mark - 公告数据
- (void)getAnnouncementDatas:(BOOL)isRemove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(AFFICHELIST) withRequestType:ZERO withParameter:self.afficheModel withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefreshingForTableView:weakSelf.announcementTableView];
        weakSelf.announcementTableView.emptyDataSetSource = weakSelf;
        weakSelf.announcementTableView.emptyDataSetDelegate = weakSelf;
        if (RESULT(returnValue)) {
            if (isRemove) {
                [weakSelf.afficheArray removeAllObjects];
            }
            AfficheResponse *respone = [[AfficheResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            weakSelf.totalPage = respone.totalpages;
            [weakSelf.afficheArray addObjectsFromArray:respone.afficheEntity];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        [weakSelf.announcementTableView reloadData];
        
    } withFailureBlock:^(NSError *error) {
        [weakSelf endRefreshingForTableView:weakSelf.announcementTableView];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

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

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnnouncementTableViewCell *announcementCell = [tableView dequeueReusableCellWithIdentifier:@"AnnouncementTableViewCell" forIndexPath:indexPath];
    TOAfficheEntity *entity = self.afficheArray[indexPath.row];
    announcementCell.afficheEntity = entity;
    announcementCell.isReadImageview.hidden = entity.readed;
    return announcementCell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AnnountcementDetailViewController *detail = [[[self class] getAnnouncementStoryboardClass]instantiateViewControllerWithIdentifier:@"AnnountcementDetailViewController"];
    detail.announcementEntity = self.afficheArray[indexPath.row];
    WS(weakSelf);
    [detail setReadBlock:^{
        TOAfficheEntity *entity = weakSelf.afficheArray[indexPath.row];
        entity.readed = YES;
        [weakSelf cornerMarkIsShow];
        [weakSelf.announcementTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self.navigationController pushViewController:detail animated:YES];
}

#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
- (AfficheCondition *)afficheModel
{
    if (!_afficheModel) {
        _afficheModel = [[AfficheCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _afficheModel.page = page;
        _afficheModel.sort = @"createDate";
        _afficheModel.order = SORTDIRECTION_DESC;
        _afficheModel.departIdEquals = [Shoppersmanager manager].shoppers.employee.departid;
        _afficheModel.employeeId = [Shoppersmanager manager].shoppers.employee.fid;
    }
    return _afficheModel;
}

- (NSMutableArray *)afficheArray
{
    if (!_afficheArray) {
        _afficheArray = [NSMutableArray array];
    }
    return _afficheArray;
}

- (NSMutableArray *)timeArray
{
    if (!_timeArray) {
        _timeArray = [NSMutableArray arrayWithObjects:@"全部",@"近三天",@"近一周",@"近一个月", nil];
        
    }
    return _timeArray;
}

- (NSMutableArray *)typeArray
{
    if (!_typeArray) {
        _typeArray = [NSMutableArray arrayWithObjects:@"全部",@"品牌资讯",@"行业动态",@"活动公告", nil];
    }
    return _typeArray;
}











@end
