//
//  AnnounceViewController.m
//  redstar
//
//  Created by admin on 15/10/24.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "AnnounceViewController.h"
#import "AnnoTableViewCell.h"
#import "HttpClient.h"
#import "AnnounceModel.h"
#import "AnnoDetailViewController.h"

#import <MBProgressHUD.h>

#define kAnnoTableViewCell @"AnnoTableViewCell"
@interface AnnounceViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIView *bgBar;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *stateStr;
@property (nonatomic, assign) BOOL isRead;

@property (nonatomic, strong) NSMutableArray *allAnnoArray;
@end

@implementation AnnounceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    self.allAnnoArray = [NSMutableArray array];
    
    self.isRead = NO;
    self.stateStr = @"false";
    
    
    [self setNav];
    
    [self setup];
    
    [self requestAnnoList];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    
}
#pragma mark - Prative Methods

- (void)requestAnnoList
{
    
    NSString *user_uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_uuid"];
    int page_number = 0;
    int page_size = 10;
    NSString *url = [NSString stringWithFormat:@"%@%@%@?read=%@&page_number=%d&page_size=%d", kRedStarURL, kAnnounceListURL ,user_uuid ,_stateStr, page_number, page_size];
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    [httpClient getAnnounceListWithCompletion:^(id response, NSError *error) {
        NSLog(@"公告response = %@", response);
        if (response[@"success"]) {
            NSDictionary *dict = response[@"data"];
            NSArray *array = dict[@"records"];
            for (NSDictionary *annoDict in array) {
                AnnounceModel *anno = [AnnounceModel announceModelWithDict:annoDict];
                [_allAnnoArray addObject:anno];
                
                self.tableView.delegate = self;
                self.tableView.dataSource = self;
            }
            
        }
    }];
}

// 返回上一页面
- (void)doBack:(UIBarButtonItem *)sender
{
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}

- (void)setNav
{
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"公告"];
    customLab.font = [UIFont boldSystemFontOfSize:19];
    self.navigationItem.titleView = customLab;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    [backBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;

}

- (void)setup
{
    self.bgBar.backgroundColor = [UIColor whiteColor];
    [self.segmentedControl addTarget:self action:@selector(segmentChangedValue:) forControlEvents:UIControlEventValueChanged];

}

- (void)segmentChangedValue:(UISegmentedControl *)sender
{
    NSString *url;
    NSString *user_uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_uuid"];
    int page_number = 0;
    int page_size = 10;
    if (sender.selectedSegmentIndex == 0) {
        self.stateStr = @"false";
        url = [NSString stringWithFormat:@"%@%@%@?read=%@&page_number=%d&page_size=%d", kRedStarURL, kAnnounceListURL ,user_uuid ,_stateStr, page_number, page_size];
    } else if (sender.selectedSegmentIndex == 1) {
        self.stateStr = @"true";
        url = [NSString stringWithFormat:@"%@%@%@?read=%@&page_number=%d&page_size=%d", kRedStarURL, kAnnounceListURL ,user_uuid ,_stateStr, page_number, page_size];
    } else {
        self.stateStr = @"";
        url = [NSString stringWithFormat:@"%@%@%@?page_number=%d&page_size=%d", kRedStarURL, kAnnounceListURL ,user_uuid , page_number, page_size];
    }
    
    
    NSLog(@"url ==== %@", url);
    
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    [httpClient getAnnounceListWithCompletion:^(id response, NSError *error) {
        NSLog(@"segemnt 公告 = %@ error = %@", response, error);
        if (response[@"success"]) {
            NSDictionary *dict = response[@"data"];
            NSArray *array = dict[@"records"];
            NSMutableArray *annoArray = [NSMutableArray array];
            for (NSDictionary *annoDict in array) {
                AnnounceModel *anno = [AnnounceModel announceModelWithDict:annoDict];
                [annoArray addObject:anno];
            }
            _allAnnoArray = annoArray;
            [self.tableView reloadData];
        }
    }];
    

}

#pragma mark - UITableView Delegate/DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allAnnoArray.count;
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnnoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kAnnoTableViewCell];
    if (!cell) {
        cell = [[AnnoTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kAnnoTableViewCell];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.currentState = self.stateStr;
    cell.announce = _allAnnoArray[indexPath.row];
    return cell;
}

// cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AnnounceModel *announce = _allAnnoArray[indexPath.row];
    AnnoDetailViewController *detailVC = [[AnnoDetailViewController alloc] init];
    detailVC.affiche_uuid = announce.uuid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - lazy laoding
- (UIView *)bgBar
{
    if (!_bgBar) {
        _bgBar = [[UIView alloc] init];
        _bgBar.translatesAutoresizingMaskIntoConstraints = NO;
        _bgBar.layer.borderColor = kSeparateLineCGColor;
        _bgBar.layer.borderWidth = 0.5;
        [self.view addSubview:_bgBar];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_bgBar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_bgBar attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_bgBar attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableHeight = [NSLayoutConstraint constraintWithItem:_bgBar attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:60];
        [self.view addConstraint:tableHeight];
    }
    return _bgBar;
}

- (UISegmentedControl *)segmentedControl
{
    if (!_segmentedControl) {
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"未读", @"已读", @"历史", nil]];
        _segmentedControl.translatesAutoresizingMaskIntoConstraints = NO;
        _segmentedControl.selectedSegmentIndex = 0;
        UIFont *font = [UIFont systemFontOfSize:16.0f];
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                               forKey:NSFontAttributeName];
        [_segmentedControl setTitleTextAttributes:attributes
                                   forState:UIControlStateNormal];
        [self.bgBar addSubview:_segmentedControl];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_segmentedControl attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bgBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:15];
        [self.bgBar addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_segmentedControl attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.bgBar attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
        [self.bgBar addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_segmentedControl attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.bgBar attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
        [self.bgBar addConstraint:tableRight];
        
        NSLayoutConstraint *tableHeight = [NSLayoutConstraint constraintWithItem:_segmentedControl attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
        [self.bgBar addConstraint:tableHeight];
    }
    return _segmentedControl;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100.0;
        [_tableView registerClass:[AnnoTableViewCell class] forCellReuseIdentifier:kAnnoTableViewCell];
        
        [self.view addSubview:_tableView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bgBar attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableBottom = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableBottom];
    }
    return _tableView;
}

@end
