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

#define MYANNOUNCEMENTCELL_HEIGHT (75)
#import "ICRAnnouncementViewController.h"
#import "ICRAnnouncement.h"
#import "ICRAnnocementContentView.h"
#import "IBTRefreshTableView.h"
#import "GTOPaging.h"
#import "MJRefresh.h"
#import "IBTSegmentContainer.h"
#import "IBTCommon.h"
#import "IBTTableViewCell.h"
#import "UIView+FindUIViewController.h"
#import "AnnouncementDetailViewController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "VankeAppBoard_iPhone.h"
static NSString *MyTableViewCell = @"IBTTableViewCell";

@interface ICRAnnouncementViewController ()
<
UITableViewDataSource,
UITableViewDelegate,
//IBTScrollViewRefreshDelegate,
UITableViewDataSource,UITableViewDelegate,
DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic,strong)UITableView *m_tableView;
@property (strong, nonatomic) IBTSegmentContainer *m_segContainer;
@property (weak,   nonatomic) IBTSegmentedControl *m_segmentControl;
@property (strong, nonatomic) NSMutableArray *m_arrUnReadData;
@property (strong, nonatomic) NSMutableArray *m_arrReadData;
@property (assign, nonatomic) NSUInteger m_unReadCurrentPage;
@property (assign, nonatomic) NSUInteger m_readedCurrentPage;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, assign) BOOL isLoadMore;


//@property (assign, nonatomic) BOOL m_isClickeUnread;
@end

@implementation ICRAnnouncementViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"公告";
    self.navigationController.navigationBar.barTintColor = kMainBlueColor;
    [self initSegmentConatinerFromOriginY:0];
    [self initTableView];
    [self createRefresh];
    [self fetchDataMore:NO type:_m_segmentControl.selectedSegmentIndex];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[VankeAppBoard_iPhone sharedInstance] hideMenu];
    if (!_m_segmentControl) {
        return;
    }
    [self.m_tableView.mj_header beginRefreshing];

}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 10) {
        self.view.superview.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    }

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

#pragma mark - empty state
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_data"];
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"transform"];
    
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0)];
    
    animation.duration = 1;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}


#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 =
    [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class]
         forCellReuseIdentifier:MyTableViewCell];
    [_m_tableView autoresizingWithStrechFullSize];
    _m_tableView.dataSource = self;
    _m_tableView.delegate = self;
    self.m_tableView.emptyDataSetSource = self;
    self.m_tableView.emptyDataSetDelegate = self;
    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 =
    @[ @"未读",
       @"已读", ];
    self.m_segContainer = [[IBTSegmentContainer alloc] initWithItems:arrSegments];
    self.m_segmentControl = _m_segContainer.segmentControl;
    _m_segmentControl.selectedSegmentIndex = 0;
    //    _m_segContainer.segmentControl.tintColor = GTO_BLUE_DEEP_COLOR;
    _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_segmentControl.selectedSegmentIndex == 0 ? _m_arrUnReadData.count : _m_arrReadData.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 ;
    if (!_m_segmentControl.selectedSegmentIndex) {
        obj = _m_arrUnReadData[indexPath.row];
    }else {
        obj = _m_arrReadData[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 ;
    if (_m_segmentControl.selectedSegmentIndex == 0) { //未读
        annocement = _m_arrUnReadData[indexPath.row];
        // [self httpReadBoardWithAnnouncement:annocement];
    } else {
        annocement = _m_arrReadData[indexPath.row];
    }
    AnnouncementDetailViewController *detailVC = [self getMainVCWithIdentifier:@"AnnouncementDetailViewController"];
    detailVC.announcement = annocement;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

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

//
- (void)httpReadBoardWithAnnouncement: (ICRAnnouncement *)annocement{
    
    //    void(^succ)(id) = ^(id data) {
    //        CLog(@"%@",data);
    //        if ([data[@"success"] integerValue] == 1) {
    //           // self.m_isClickeUnread = YES;
    //            ICRAnnouncementDetailViewController *dVC = [[ICRAnnouncementDetailViewController alloc]
    //                                                        initWithAnnouncementData:annocement];
    ////            [self PushViewController:dVC animated:YES];
    //        }
    //    };
    //    void(^fail)(id) = ^(id data) {
    //        CLog(@"%@",data);
    //    };
    //
    //    //[IBTLoadingView showProgressLabel:@""];
    //    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    //    [httpCtrl doReadBoardWithID:annocement.uuid success:succ failure:fail];
}

#pragma mark - Get Data

- (void)fetchDataMore:(BOOL)more type:(ICRAnnouncementReadType)eType {
    
    NSUInteger pageNu;
    if (eType > 0) {
        pageNu = _m_readedCurrentPage;
    } else  {
        pageNu = _m_unReadCurrentPage;
    }
    NSString *type;
    if (eType) {
        type = @"true";
    } else {
        type = @"false";
    }
    WS(weakSelf);
    [[ICRHTTPController sharedController] postUrl:[NSString stringWithFormat:@"affiche/download/%@?read=%@&page_number=%@&page_size=%@", [VankeCommonModel sharedInstance].currentUser.uuid,type,@(pageNu),@20] params:nil success:^(id data) {
        [weakSelf endRefreshing];
        if ([data[@"success"] integerValue] == 1) {
            NSDictionary *dictData = data[@"data"];
            [weakSelf fetchArrDataMore:more type:eType data:dictData];
        }else{
            
        }
    } failure:^(id data) {
        
    }];
}

- (void)fetchArrDataMore: (BOOL)more type:(ICRAnnouncementReadType)eType data: (NSDictionary *)data {
    GTOPaging *paging = [GTOPaging DBObject];
    [paging praseFromJsonDict:data[@"paging"]];
    NSMutableArray *records = [@[]mutableCopy] ;
    for(NSDictionary *dict in data[@"records"]) {
        ICRAnnouncement *announcemet = [ICRAnnouncement DBObject];
        [announcemet praseFromLocalDict:dict];
        announcemet.readType = eType;
        
        //处理一下字符串，去除html标记
        if ([announcemet.content hasPrefix:@"<p>"]) {
            NSRange lastRange = [announcemet.content rangeOfString:@"</p>"];
            NSString *cutString = [announcemet.content substringWithRange:NSMakeRange(3, lastRange.location - 3)];
            announcemet.content = cutString;
        }
        [records addObject:announcemet];
    }
    
    if (!_m_arrUnReadData) {
        self.m_arrUnReadData = [@[]mutableCopy] ;
    }
    if (!_m_arrReadData) {
        self.m_arrReadData = [@[]mutableCopy] ;
    }
    
    
    if (!more) {
        switch (eType) {
            case kICRAnnouncementTypeUnread: {
                 self.m_unReadCurrentPage = 0;
                [self.m_arrUnReadData removeAllObjects];
                [self.m_arrUnReadData addObjectsFromArray:records];
            }
                
                break;
            case kICRAnnouncementTypeReaded: {
                 self.m_readedCurrentPage = 0;
                [self.m_arrReadData removeAllObjects];
                [self.m_arrReadData addObjectsFromArray:records];
            }
                
            default:
                break;
        }
    } else {
        switch (eType) {
            case kICRAnnouncementTypeUnread:
            {
                if (paging.pageCount > _m_unReadCurrentPage) {
//                      self.m_unReadCurrentPage ++ ;
                    [self.m_arrUnReadData addObjectsFromArray:records];
                } else {
                    [self.m_tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }
                break;
            case kICRAnnouncementTypeReaded:
            {
                if (paging.pageCount > _m_readedCurrentPage) {
//                     self.m_unReadCurrentPage ++ ;
                    [self.m_arrReadData addObjectsFromArray:records];
                }else {
                    [self.m_tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            default:
                break;
        }
        
    }
    [self.m_tableView reloadData];
}


- (void)createRefresh{
    WS(weakSelf);
    self.m_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.m_unReadCurrentPage = 0;
        weakSelf.m_readedCurrentPage = 0;
        weakSelf.isRefresh = YES;
        [weakSelf fetchDataMore:NO type:weakSelf.m_segmentControl.selectedSegmentIndex];
    }];
    // self.tableView.header.lastUpdatedTimeKey = GTO_REPAIR_UPDATEDATE;
    
    self.m_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.isLoadMore = YES;
        weakSelf.m_unReadCurrentPage ++ ;
        weakSelf.m_readedCurrentPage ++ ;
        [weakSelf fetchDataMore:YES type:weakSelf.m_segmentControl.selectedSegmentIndex];
    } ];
}
#pragma mark - 结束刷新
- (void)endRefreshing{
    _isLoadMore = NO;
    _isRefresh = NO;
    [self.m_tableView.mj_header endRefreshing];
    [self.m_tableView.mj_footer endRefreshing];
}
@end
