iOS/SportsContact/UI/Info/ExploitsViewController.m
//
//  ExploitsViewController.m
//  SportsContact
//
//  Created by bobo on 14-7-24.
//  Copyright (c) 2014年 CAF. All rights reserved.
//

#import "ExploitsViewController.h"
#import "DataDef.h"
#import "DateUtil.h"
#import "Util.h"
#import "InfoEngine.h"
#import "ScoreManagerViewController.h"

@interface ExploitsViewController ()

@property (nonatomic, strong) UserInfo *userInfo;
@property (nonatomic, strong) NSArray *exploits;
@property (nonatomic, strong) NSMutableArray *exploitsGroup;
@property (nonatomic, strong) NSMutableArray *titles;
@property (nonatomic, strong) NSArray *teams;
@property (nonatomic, strong) Team *tempTeam;

@end

@implementation ExploitsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"个人战绩表";
    
    self.titles = [NSMutableArray arrayWithCapacity:0];
    self.exploitsGroup = [NSMutableArray arrayWithCapacity:0];
    [self orderData];
    [self.tableView reloadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needRefresh) name:kObserverMatchInfoChanged object:nil];
    // Do any additional setup after loading the view.
}

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

- (BOOL)hidesBottomBarWhenPushed
{
    return YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.isNeedRefresh) {
        self.isNeedRefresh = NO;
        [self loadExploitsData];
    }
}


- (void)loadExploitsData
{
    [self showLoadingView];
    [InfoEngine getPlayerScoreWithUserId:self.userInfo.objectId block:^(id result, NSError *error)
     {
         [self hideLoadingView];
         if (error)
         {
             [self showMessage:[Util errorStringWithCode:error.code]];
         }else
         {
             self.exploits = result;
             [self orderData];
             [self.tableView reloadData];
         }
     }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)orderData
{
    if (!self.exploits || [self.exploits count] == 0)
    {
        return ;
    }
    self.titles = [NSMutableArray arrayWithCapacity:0];
    self.exploitsGroup = [NSMutableArray arrayWithCapacity:0];
    NSString *tempTitle = nil;
    NSMutableArray *tempArray = nil;
    for (PlayerScore *score in self.exploits)
    {
        if (score.competition.start_time == nil) {
            continue ;
        }
        NSString *title =  [NSString stringWithFormat:@"%ld年", (long)score.competition.start_time.year];
        if (tempTitle == nil)
        {
            tempTitle = title;
            tempArray = [NSMutableArray arrayWithCapacity:0];
            [self.exploitsGroup addObject:tempArray];
            [self.titles  addObject:tempTitle];
            [tempArray addObject:score];
        }else if ([tempTitle isEqualToString:title])
        {
            [tempArray addObject:score];
        }else
        {
            tempArray = [NSMutableArray arrayWithCapacity:0];
            tempTitle = title;
            [self.exploitsGroup addObject:tempArray];
            [self.titles  addObject:tempTitle];
            [tempArray addObject:score];
        }
    }
}

- (void)transformNextWithMatch:(Tournament *)match
{
    
    if ([self.teams count] == 0)
    {
        [self showMessage:@"无所属球队！"];
    }else
    {
        Team *matchTeam = nil;
        if([self.teams count] == 1)
        {
            matchTeam = [self.teams firstObject];
        }else
        {
            for (Team *team in self.teams)
            {
                if([team.objectId isEqualToString:match.home_court.objectId] || [team.objectId isEqualToString:match.opponent.objectId])
                {
                    matchTeam = team;
                    break ;
                }
            }
        }
        if (matchTeam)
        {
            UIStoryboard *centerStoryboard = [UIStoryboard storyboardWithName:@"Center" bundle:[NSBundle mainBundle]];
            ScoreManagerViewController *scoreViewController = [centerStoryboard instantiateViewControllerWithIdentifier:@"ScoreManagerViewController"];
            scoreViewController.match = match;
            scoreViewController.team = matchTeam;
            scoreViewController.canEdit = YES;
            scoreViewController.userInfo = self.userInfo;
            [self.navigationController pushViewController:scoreViewController animated:YES];
        }else
        {
            UIStoryboard *centerStoryboard = [UIStoryboard storyboardWithName:@"Center" bundle:[NSBundle mainBundle]];
            ScoreManagerViewController *scoreViewController = [centerStoryboard instantiateViewControllerWithIdentifier:@"ScoreManagerViewController"];
            scoreViewController.match = match;
            scoreViewController.team = match.home_court;
            scoreViewController.canEdit = NO;
            scoreViewController.userInfo = self.userInfo;
            [self.navigationController pushViewController:scoreViewController animated:YES];
        }
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.titles count];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320.0, 22.0f)];
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:headerView.bounds];
    bgView.image = [UIImage imageNamed:@"cell_title_bg"];
    [headerView addSubview:bgView];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 300.0, 22.0f)];
    titleLabel.text = [self.titles objectAtIndex:section];
    titleLabel.textColor = UIColorFromRGB(0x898989);
    titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [headerView addSubview:titleLabel];
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"exploits_cell"];
    PlayerScore *score = [[self.exploitsGroup objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
//    NSString *dateTotal=[NSString stringWithFormat:@"%@",score.competition.start_time];

    UILabel *dayLabel = (id)[cell.contentView viewWithTag:0xF0];
    dayLabel.text = [DateUtil formatedDate:score.competition.start_time byDateFormat:@"MM月dd"];
//    dayLabel.text = [NSString stringWithFormat:@"%@月%@日",[dateTotal substringWithRange:NSMakeRange(5,2)],[dateTotal substringWithRange:NSMakeRange(8,2)]];

    UILabel *timeLabel = (id)[cell.contentView viewWithTag:0xF1];
    timeLabel.text = [DateUtil formatedDate:score.competition.start_time byDateFormat:@"HH:mm"];
//    timeLabel.text = [NSString stringWithFormat:@"%@",[dateTotal substringWithRange:NSMakeRange(11,5)]];

    
    UILabel *peopleLabel = (id)[cell.contentView viewWithTag:0xF2];
    peopleLabel.text = @"";
    UILabel *leagueNameLabel = (id)[cell.contentView viewWithTag:0xF3];
    leagueNameLabel.text = score.league.name ? score.league.name : tournamentTypeStringFromEnum([score.competition.nature integerValue]);
    UILabel *homeCourtNameLabel = (id)[cell.contentView viewWithTag:0xF4];
    homeCourtNameLabel.text = score.competition.home_court.name;
    Tournament *match = score.competition;
    UILabel *scoreLabel = (id)[cell.contentView viewWithTag:0xF8];
    BOOL isHomeCourt = score.competition.score_h && score.competition.score_h2;
    for (Team *team in self.teams)
    {
        if([team.objectId isEqualToString:match.home_court.objectId])
        {
            isHomeCourt = YES;
            break ;
        }else if([team.objectId isEqualToString:match.opponent.objectId])
        {
            isHomeCourt = NO;
            break ;
        }
    }
    
    if (isHomeCourt)
    {
        scoreLabel.text = [NSString stringWithFormat:@"%d - %d", [score.competition.score_h intValue], [score.competition.score_h2 intValue]];
    }else
    {
        scoreLabel.text = [NSString stringWithFormat:@"%d - %d", [score.competition.score_o2 intValue], [score.competition.score_o intValue]];
    }
    
    UILabel *opponentNameLabel = (id)[cell.contentView viewWithTag:0xF9];
    opponentNameLabel.text = score.competition.opponent.name;
    
    UILabel *goalsLabel = (id)[cell.contentView viewWithTag:0xFA];
    goalsLabel.text = [NSString stringWithFormat:@"%@", score.goals];
    
    if (score.goals) {
        goalsLabel.text = [NSString stringWithFormat:@"%@", score.goals];
    }else{
        goalsLabel.text = [NSString stringWithFormat:@"%@", @"0"];
    }
    
    
    UILabel *assistsLabel = (id)[cell.contentView viewWithTag:0xFB];
    if (score.assists) {
        assistsLabel.text = [NSString stringWithFormat:@"%@", score.assists];
    }else{
        assistsLabel.text = [NSString stringWithFormat:@"%@", @"0"];
    }
    
    
    UILabel *authorizedView = (id)[cell.contentView viewWithTag:0xFC];
    authorizedView.hidden = !score.competition.isVerify;
    
    UIImageView *line1 = (id)[cell.contentView viewWithTag:0xF6];
    line1.hidden = indexPath.row == 0;
    UIImageView *line2 = (id)[cell.contentView viewWithTag:0xF7];
    line2.hidden = indexPath.row == [(NSArray*)[self.exploitsGroup objectAtIndex:indexPath.section] count] - 1;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [(NSArray*)[self.exploitsGroup objectAtIndex:section] count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayerScore *score = [[self.exploitsGroup objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [self transformNextWithMatch:score.competition];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
