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

#import "RankDetailViewController.h"
#import "RankDetailTableCell.h"
#import "RankDetailHeaderView.h"

#import "RankHeadView.h"
#import "WorkModel.h"

#define kRankDetailCell @"RankDetailTableCell"

@interface RankDetailViewController () <UITableViewDataSource, UITableViewDelegate, RankHeadViewDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) RankDetailHeaderView *rankDetailHeaderView;

@property (nonatomic, strong) NSArray *workData;

@property (nonatomic, strong) NSMutableDictionary *selectedIndexes; // 存放二次展开的cell


@end

@implementation RankDetailViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    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;

    
    // 添加tableView
    [self addTableView];
    
    // 初始化容器
    self.selectedIndexes = [[NSMutableDictionary alloc] init];

}

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

#pragma mark - Private Methods
- (void)addTableView {
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"ranking.plist" withExtension:nil];
    NSArray *tempArray = [NSArray arrayWithContentsOfURL:url];
    
    NSMutableArray *workArray = [NSMutableArray array];
    for (NSDictionary *dict in tempArray) {
        WorkModel *work = [WorkModel workModelWithDict:dict];
        [workArray addObject:work];
    }
    
    _workData = workArray;
    
    self.tableView.tableHeaderView = self.rankDetailHeaderView;
    [self setupScrollView];
    // 注册cell
    [self.tableView registerClass:[RankDetailTableCell class] forCellReuseIdentifier:kRankDetailCell];
}

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

- (void)setupScrollView
{
    int imageCount = 5;
    CGFloat marginW = 5.0;
    CGFloat imageViewW = 90 + 2 * marginW;
    CGFloat imageViewH = self.rankDetailHeaderView.rankDetailView.showScrollView.bounds.size.height - 4;
    self.rankDetailHeaderView.rankDetailView.showScrollView.contentSize = CGSizeMake(imageCount *imageViewW, imageViewH + 4);
    for (int i = 0; i < imageCount; i++) {
        UIButton *button = [[UIButton alloc] init];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"0%d", i]] forState:UIControlStateNormal];
        button.frame = CGRectMake(i * imageViewW + 2, 2, imageViewW - 2 * marginW, imageViewH);
        [button addTarget:self action:@selector(ccilck) forControlEvents:UIControlEventTouchUpInside];
        [self.rankDetailHeaderView.rankDetailView.showScrollView addSubview:button];
    }
}

- (void)ccilck
{
    NSLog(@"test");
}


- (void)showScrollView:(UIButton *)sender
{
    RankDetailTableCell * cell = (RankDetailTableCell *)[[sender superview] superview];
    cell.isDrop = !cell.isDrop;
    NSIndexPath * path = [self.tableView indexPathForCell:cell];
    
    [_tableView deselectRowAtIndexPath:path animated:TRUE];
    
    BOOL isSelected = ![self cellIsSelected:path];
    
    NSNumber *selectedIndex = [NSNumber numberWithBool:isSelected];
    [_selectedIndexes setObject:selectedIndex forKey:path];
    
    if (cell.isDrop) {
        [UIView animateWithDuration:0.2 animations:^{
            cell.arrowImageView.transform = CGAffineTransformIdentity;
            cell.arrowImageView.transform = CGAffineTransformMakeRotation(M_PI / 2);
        }];
        
        cell.scrollView = [[UIScrollView alloc] init];
        cell.scrollView.backgroundColor = [UIColor lightGrayColor];
        cell.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
        [cell.contentView addSubview:cell.scrollView];
        
        NSLayoutConstraint *someoneTop = [NSLayoutConstraint constraintWithItem:cell.scrollView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:45];
        [cell.contentView addConstraint:someoneTop];
        
        NSLayoutConstraint *someoneLeft = [NSLayoutConstraint constraintWithItem:cell.scrollView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
        [cell.contentView addConstraint:someoneLeft];
        
        NSLayoutConstraint *someoneRight = [NSLayoutConstraint constraintWithItem:cell.scrollView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
        [cell.contentView addConstraint:someoneRight];
        
        NSLayoutConstraint *someoneHeight = [NSLayoutConstraint constraintWithItem:cell.scrollView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:65];
        [cell.contentView addConstraint:someoneHeight];
        
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            cell.arrowImageView.transform = CGAffineTransformIdentity;
            cell.arrowImageView.transform = CGAffineTransformMakeRotation(0);
        }];
        
        if (cell.scrollView) {
            [cell.scrollView removeFromSuperview];
            cell.scrollView = nil;
        }
    }
    
    [_tableView beginUpdates];
    [_tableView endUpdates];
}


- (BOOL)cellIsSelected:(NSIndexPath *)indexPath {
    // Return whether the cell at the specified index path is selected or not
    NSNumber *selectedIndex = [_selectedIndexes objectForKey:indexPath];
    return selectedIndex == nil ? FALSE : [selectedIndex boolValue];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    WorkModel *work = _workData[section];
    NSInteger count = work.isOpened ? work.Info.count : 0;
    return count;
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RankDetailTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kRankDetailCell];
    if (!cell) {
        cell = [[RankDetailTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kRankDetailCell];
    }
    
    WorkModel *workModel = _workData[indexPath.section];
    NSDictionary *dict = workModel.Info[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    [cell.mainTitleBtn setTitle:[NSString stringWithFormat:@"%d、%@", (int)(indexPath.row + 1),dict[@"titles"]] forState:UIControlStateNormal];
    cell.scoreLabel.text = [NSString stringWithFormat:@"%@分", dict[@"scroes"]];
    // 按钮点击事件
    [cell.mainTitleBtn addTarget:self action:@selector(showScrollView:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;

}

// cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self cellIsSelected:indexPath]) {
        return 130;
    }
    
    return 44;
}

// section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

// foot高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

// 自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    RankHeadView *headView = [RankHeadView headViewWithTableView:tableView];
    headView.delegate = self;
    headView.work = _workData[section];
    
    return headView;
}

- (void)clickRankHeadView
{
    [self.tableView reloadData];
}


#pragma mark - lazy Laoding
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop 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;
}


- (RankDetailHeaderView *)rankDetailHeaderView
{
    if (!_rankDetailHeaderView) {
        _rankDetailHeaderView = [[RankDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 298)];
        _rankDetailHeaderView.rankDetailView.addressLabel.text = @"上海市真北路1108号";
        _rankDetailHeaderView.rankDetailView.titleLabel.text = @"2015年8月口碑巡检";
        _rankDetailHeaderView.rankDetailView.reportTimeLabel.text = @"上报时间";
        _rankDetailHeaderView.rankDetailView.totalScoreLabel.text = @"总评分";
        _rankDetailHeaderView.rankDetailView.totalGradeLabel.text = @"总排名";
        _rankDetailHeaderView.rankDetailView.timeLabel.text = @"2015-08-15";
        _rankDetailHeaderView.rankDetailView.scoreLabel.text = @"100";
        if (self.indexRow < 3) {
            NSString *imageName = [NSString stringWithFormat:@"medal_0%ld", (long)(_indexRow + 1)];
            _rankDetailHeaderView.rankDetailView.gradeImageView.image = [UIImage imageNamed:imageName];
        } else {
            NSString *rankStr = [NSString stringWithFormat:@"第 %ld 名", (long)(_indexRow + 1)];
            NSMutableAttributedString *rankAttr = [[NSMutableAttributedString alloc] initWithString:rankStr];
            [rankAttr addAttributes:@{NSForegroundColorAttributeName:kRankHeadTitleTextColor,NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} range:NSMakeRange(0,1)];
            [rankAttr addAttributes:@{NSForegroundColorAttributeName:kGradeNumberTextColor} range:NSMakeRange(1,rankStr.length - 2)];
            [rankAttr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:18.0] range:NSMakeRange(1,rankStr.length - 2)];
            [rankAttr addAttributes:@{NSForegroundColorAttributeName:kRankHeadTitleTextColor,NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} range:NSMakeRange(rankStr.length - 1,1)];
            [_rankDetailHeaderView.rankDetailView.gradeLabel setAttributedText:rankAttr];
        }
    }
    return _rankDetailHeaderView;
}

/*
#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.
}
*/

@end
