//
//  ICRAnnouncementViewController.m
//  XFFruit
//
//  Created by Xummer on 4/11/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#define MYANNOUNCEMENTCELL_HEIGHT (75)

#import "ICRAnnouncementViewController.h"
#import "ICRAnnouncementDetailViewController.h"
#import "ICRAnnouncement.h"
#import "ICRAnnocementContentView.h"
#import "IBTRefreshTableView.h"

static NSString *MyTableViewCell = @"IBTTableViewCell";

@interface ICRAnnouncementViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate,
    IBTScrollViewRefreshDelegate
>
@property (strong, nonatomic) IBTRefreshTableView *m_tableView;
@property (strong, nonatomic) IBTSegmentContainer *m_segContainer;
@property (weak,   nonatomic) IBTSegmentedControl *m_segmentControl;
@property (strong, nonatomic) NSArray *m_arrData;

@end

@implementation ICRAnnouncementViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = [IBTCommon localizableString:@"Announcement"];
    
    [self initSegmentConatinerFromOriginY:0];
    [self initTableView];
    //默认请求第一个
    [self fetchDataMore:NO type:kICRAnnouncementTypeUnread];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private Method
- (void)initTableView {
    CGFloat dy = CGRectGetMaxY(_m_segContainer.frame);
    CGRect frame = self.view.bounds;
    frame.origin.y = dy;
    frame.size.height -= CGRectGetMinY(frame);
    
    self.m_tableView =
    [[IBTRefreshTableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class]
         forCellReuseIdentifier:MyTableViewCell];
    [_m_tableView autoresizingWithStrechFullSize];
    _m_tableView.dataSource = self;
    _m_tableView.delegate = self;
    _m_tableView.refreshDelegate = self;
    [_m_tableView addRefreshControlWithText:[IBTCommon localizableString:@""]];
    [_m_tableView addLoadMoreFootWithText:[IBTCommon localizableString:@"Load more"]];
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    _m_tableView.tableFooterView = view;
    
    [self.view addSubview:_m_tableView];
}

- (void)initSegmentConatinerFromOriginY:(CGFloat)y {
    
    if (_m_segContainer) {
        return;
    }
    
    NSArray *arrSegments =
    @[ [IBTCommon localizableString:@"Unread"],
       [IBTCommon localizableString:@"Read"], ];
    self.m_segContainer = [[IBTSegmentContainer alloc] initWithItems:arrSegments];
    self.m_segmentControl = _m_segContainer.segmentControl;
    self.m_segmentControl.tintColor = GXF_NAVIGAYION_COLOR;
    _m_segmentControl.selectedSegmentIndex = 0;
    _m_segContainer.frame = (CGRect){
        .origin.x = 0,
        .origin.y = y,
        .size.width = CGRectGetWidth(self.view.bounds),
        .size.height = IBT_SEGMENT_CONTAINER_DEFUALT_HEIGHT
    };
    [self.view addSubview:_m_segContainer];
    
    [_m_segmentControl addTarget:self action:@selector(onSegmentsTapped:)
                forControlEvents:UIControlEventValueChanged];
}

#pragma mark - Action
- (void)onSegmentsTapped:(id)sender {
    UISegmentedControl *segmentedCtrl = sender;
    switch (segmentedCtrl.selectedSegmentIndex) {
        case 0: // 未读
        {
            [self fetchDataMore:NO type:kICRAnnouncementTypeUnread];
        }
            break;
        case 1: // 已读
        {
            [self fetchDataMore:NO type:kICRAnnouncementTypeReaded];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:MyTableViewCell
                                    forIndexPath:indexPath];
    
    [self configureCell:cell forRowAtIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    id obj = _m_arrData[ indexPath.row ];
    
    UIView *contentView = cell.contentView;
    
    ICRAnnocementContentView *aContentView = [contentView viewWithClass:
                                              [ICRAnnocementContentView class]];
    
    if (!aContentView) {
        aContentView = [[ICRAnnocementContentView alloc] initWithFrame:contentView.frame];
        [aContentView autoresizingWithStrechFullSize];
        [contentView addSubview:aContentView];
    }
    
    [aContentView updateContentWithData:obj];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ICRAnnouncement *annocement = [_m_arrData objectAtIndex:indexPath.row];
    
    ICRAnnouncementDetailViewController *dVC = [[ICRAnnouncementDetailViewController alloc] initWithAnnouncementData:annocement];
    
    [self PushViewController:dVC animated:YES];
}

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

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _m_tableView) {
        [_m_tableView tableViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    if (scrollView == _m_tableView) {
        [_m_tableView tableviewDidEndDragging:scrollView];
    }
}

#pragma mark - IBTScrollViewRefreshDelegate

- (void)startRefreshData:(UIScrollView *)scrollView {
    [self fetchDataMore:NO type:_m_segmentControl.selectedSegmentIndex];
}

- (void)endRefreshData:(UIScrollView *)scrollView {
    
}

- (void)startLoadMoreData:(UIScrollView *)scrollView {
    [self fetchDataMore:YES type:_m_segmentControl.selectedSegmentIndex];
}

- (void)endLoadMoreData:(UIScrollView *)scrollView {
    
}

#pragma mark - Data Update
- (void)fetchAnnouncementsListWithType:(ICRAnnouncementType)type {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? ", [ICRAnnouncement TableName], @"priority"];
//        , @"createTime"   ORDER BY %@ DESC
        return [db executeQuery:sql, @( type ) ];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrData = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAnnouncement class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}

#pragma mark - Get Data

- (void)fetchDataMore:(BOOL)more type:(ICRAnnouncementType)eType {
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf fetchAnnouncementsListWithType:eType];
        if (!more) {
            [_m_tableView endRefreshWithState:kRefreshStateFinished];
        }
        else {
            [_m_tableView endLoadMoreWithState:kLoadStateFinished];
        }
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
        if (!more) {
            [_m_tableView endRefreshWithState:kRefreshStateFailed];
        }
        else {
            [_m_tableView endLoadMoreWithState:kLoadStateFailed];
        }
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
   
    ICRAnnouncement *annocement = [_m_arrData lastObject];
    [httpCtrl doGetBoardListFromUpdateTime:more ? nil : annocement.lastModifyInfo[@"time"]
                                  position:0
                                      size:20
                                      type:eType
                               deleteLocal:!more
                                   success:succ
                                   failure:fail];

}
@end
