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

#import "RankingListViewController.h"
//#import "RankingListCell.h"
#import "RankDetailViewController.h"

#import "HttpClient.h"
#import "RankListModel.h"
#import "NoDataView.h"
#import "RankCommentModel.h"
#import "RankListHeaderView.h"

#import "RankCommentCell.h"
#import "RankScreenTableViewCell.h"

#import <MBProgressHUD.h>

#import "OnLineTableViewCell.h"
#import "HomeTitleTableCell.h"

#import "SelectStoreViewController.h"
#import "RankPickView.h"
#import "TreeNodeModel.h"

#define konlineCell @"onlinesTableViewCell"
#define kRankingCell @"RankingTableViewCell"
#define kHomeTitleCellInde @"homeTitleCellInde"
#define kRankScreenTableViewCell @"rankingScreenCell"
#define kShopNameBtnTag 15000

@interface RankingListViewController () <UITableViewDataSource, UITableViewDelegate, RankListHeaderDelegate, UIPickerViewDelegate, UIPickerViewDataSource, SelectStoreDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *allRankListArray;
@property (nonatomic, strong) NoDataView *noDataView;

@property (nonatomic, strong) UILabel *shoppingLabel;
@property (nonatomic, strong) UILabel *scoreLabel;
@property (nonatomic, strong) UILabel *gradeLabel;

@property (nonatomic, strong) NSArray *rankData;
@property (nonatomic, strong) NSArray *allTitleArray;

@property (nonatomic, strong) UIButton *selectButton;

@property (nonatomic, strong) RankPickView *pickerView;
@property (nonatomic, strong) UIView *backGroundView;

@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, assign) NSInteger pickRow;
@property (nonatomic, strong) NSMutableArray *uuidArray;

@property (nonatomic, assign) NSInteger statisMode;

@property (nonatomic, strong) NSString *selectName;


@property (nonatomic) BOOL isChoose;

@end

@implementation RankingListViewController

#pragma mark - ViewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.allTitleArray = [NSArray arrayWithObjects:@"口碑巡检", @"选择范围", @"统计方式" ,nil];
    self.titleArray = [NSMutableArray array];
    self.uuidArray = [NSMutableArray array];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    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;

    self.allRankListArray = [NSMutableArray array];

    if([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    _pickRow = 0;

    
    self.shoppingLabel.text = @"商场名称";
    self.scoreLabel.text = @"总分";
    self.gradeLabel.text = @"排名";
    
    _isChoose = YES;
    _selectName = @"全部";
    _selectButton = [[UIButton alloc] init];
    _selectButton.tag = 323228;

}

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

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self requestShortPraise];

    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - Private Methods
- (void)requestRankingListWithPraiseUuid:(NSString *)praiseUuid
{
    NSString *url = [NSString stringWithFormat:@"%@%@", kRedStarURL, kRankingListURL];
    
    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:url];
    NSDictionary *parameters = @{@"praiseUuid":praiseUuid,
                                 @"statisMode":@(0),
                                 };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    __block RankingListViewController *weakSelf = self;
    [httpCilent getRankingListWithParameters:parameters completion:^(id response, NSError *error) {
        NSDictionary *dataDict = response[@"data"];
        NSArray *dataArray = dataDict[@"records"];
        
        NSMutableArray *tgArray = [NSMutableArray array];

        for (NSDictionary *ListDict in dataArray) {
            RankListModel *rankList = [RankListModel rankListModelWithDict:ListDict];
            [tgArray addObject:rankList];
        }
        _rankData = (NSMutableArray *)[self sortRankListWithRankListArray:tgArray];
        for (int i = 0 ; i < _rankData.count; i++) {
            RankListModel *rank = _rankData[i];
            if (i == 0) {
                rank.index = i + 1;
            } else {
                RankListModel *prevRank = _rankData[i-1];
                rank.index = rank.score == prevRank.score ? prevRank.index: i + 1;
            }
        }
        if (_rankData.count == 0) {
            weakSelf.noDataView.backgroundColor = [UIColor whiteColor];
            [MBProgressHUD hideHUDForView:self.view animated:YES];

        } else {
        
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];

        }
    }];
}

- (void)requestShortPraise
{
    NSString *user_uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_uuid"];
    NSString *url = [NSString stringWithFormat:@"%@%@%@", kRedStarURL, kQueryShortPraiseURL, user_uuid];
    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:url];
    [httpCilent queryShortPraiseWithCompletion:^(id response, NSError *error) {
        NSArray *dataArray = response[@"data"];
        for (NSDictionary *dict in dataArray) {
            [_titleArray addObject:dict];
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            [self.tableView reloadData];
        }
        if (_titleArray.count == 0) {
            return ;
        } else {
            NSDictionary *paDict = _titleArray[0];
            [self requestRankingListWithPraiseUuid:paDict[@"uuid"]];
        }

    }];
}

- (void)requestPartPraise
{
    NSString *url = [NSString stringWithFormat:@"%@%@", kRedStarURL, kRankingListURL];
    _statisMode = _selectButton.tag - 323228;

    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:url];
    NSDictionary *dict = _titleArray[_pickRow];
    NSDictionary *parameters = @{@"praiseUuid":dict[@"uuid"],
                                 @"statisMode":@(_statisMode),
                                 @"orgUuids":_uuidArray,
                                 };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpCilent getRankingListWithParameters:parameters completion:^(id response, NSError *error) {

        NSDictionary *dataDict = response[@"data"];
        NSArray *dataArray = dataDict[@"records"];
        
        NSMutableArray *tgArray = [NSMutableArray array];
        
        for (NSDictionary *ListDict in dataArray) {
            RankListModel *rankList = [RankListModel rankListModelWithDict:ListDict];
            [tgArray addObject:rankList];
        }
        _rankData = (NSMutableArray *)[self sortRankListWithRankListArray:tgArray];
        
        for (int i = 0 ; i < _rankData.count; i++) {
            RankListModel *rank = _rankData[i];
            if (i == 0) {
                rank.index = i + 1;
            } else {
                RankListModel *prevRank = _rankData[i-1];
                rank.index = rank.score == prevRank.score ? prevRank.index: i + 1;
            }
        }
        
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];
}

- (NSArray *)sortRankListWithRankListArray:(NSMutableArray *)allRanking
{
    NSArray *sortedArray = [allRanking sortedArrayUsingComparator:^NSComparisonResult(RankListModel *p1, RankListModel *p2){
        return [@(p2.score) compare:@(p1.score)];
    }];
    return sortedArray;
}

-(void)doBack:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


- (void)changeDateClick:(DateButton *)sender
{
    
}

- (void)statisticsClick:(UIButton *)sender
{    
    if (sender.tag == 323228) {
        _isChoose = YES;
    } else {
        _isChoose = NO;
    }
    
    _selectButton = (UIButton *)sender;
    [self.tableView reloadData];
}

- (void)closeBackGroundView
{
    CGRect fromFrame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
    [UIView animateWithDuration:0.3 animations:^{
        _backGroundView.alpha = .0f;
        _pickerView.frame = fromFrame;
    } completion:^(BOOL finished) {
        [_backGroundView removeFromSuperview];
        [_pickerView removeFromSuperview];
    }];
}

- (void)okClick:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    OnLineTableViewCell *cell = (OnLineTableViewCell *)[_tableView cellForRowAtIndexPath:indexPath];
    _pickRow = [_pickerView.pickerView selectedRowInComponent:0];
    NSDictionary *dict = _titleArray[_pickRow];
    cell.selectLabel.text = [NSString stringWithFormat:@"%@", dict[@"name"]];
    [self closeBackGroundView];
}

#pragma mark - SelectStoreDelegate

- (void)deliverWithArray:(NSMutableArray *)array
{
    NSString *nameStr = @"";
    self.uuidArray = [NSMutableArray array];
    if (array.count == 0) {
        _selectName = @"全部";
    } else {
        for (TreeNodeModel *model in array) {
            nameStr = [nameStr stringByAppendingString:[NSString stringWithFormat:@"%@,", model.name]];
            [_uuidArray addObject:model.uuid];
        }
        _selectName = nameStr;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - UITableView DataSource/Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _rankData.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    } else {
        RankListModel *rankList = _rankData[section - 1];
        NSInteger count = rankList.isOpened ? rankList.comments.count: 0;
        return count;
    }
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row < 3) {
            OnLineTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:konlineCell];
            if (!cell) {
                cell = [[OnLineTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:konlineCell];
            }
            cell.titleLabel.text = _allTitleArray[indexPath.row];
            if (indexPath.row < 2) {
                if (indexPath.row == 0) {
                    if (_titleArray.count == 0) {
                        cell.selectLabel.text = @"";
                    } else {
                        NSDictionary *dict = _titleArray[_pickRow];
                        cell.selectLabel.text = [NSString stringWithFormat:@"%@", dict[@"name"]];
                    }
                } else {
                    cell.selectLabel.text = _selectName;
                }
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            } else {
                [cell.storeBtn addTarget:self action:@selector(statisticsClick:) forControlEvents:UIControlEventTouchUpInside];
                [cell.averageBtn addTarget:self action:@selector(statisticsClick:) forControlEvents:UIControlEventTouchUpInside];
                cell.storeBtn.selected = _isChoose;
                cell.averageBtn.selected = !_isChoose;
            }
            
            return cell;
        } else if (indexPath.row == 3){
            RankScreenTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kRankScreenTableViewCell];
            if (!cell) {
                cell = [[RankScreenTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kRankScreenTableViewCell];
            }
            NSString *queryStr = [NSString stringWithFormat:@"查询结果共计 %ld 家", (unsigned long)_rankData.count];
            NSMutableAttributedString *queryAttr = [[NSMutableAttributedString alloc] initWithString:queryStr];

            [queryAttr addAttributes:@{NSForegroundColorAttributeName:kLightGray,NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} range:NSMakeRange(0,7)];
            [queryAttr addAttributes:@{NSForegroundColorAttributeName:kNavigationBarColor,NSFontAttributeName:[UIFont systemFontOfSize:20.0f]} range:NSMakeRange(7,queryStr.length - 9)];
            [queryAttr addAttributes:@{NSForegroundColorAttributeName:kLightGray,NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} range:NSMakeRange(queryStr.length - 1,1)];
            [cell.queryLabel setAttributedText:queryAttr];
            [cell.screenButton addTarget:self action:@selector(requestPartPraise) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        } else {
            HomeTitleTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kHomeTitleCellInde];
            if (!cell) {
                cell = [[HomeTitleTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kHomeTitleCellInde];
            }
            cell.contentView.backgroundColor = kSectionBackGroundColor;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    } else {
        RankCommentCell *cell=[tableView dequeueReusableCellWithIdentifier:kRankingCell];
        if (!cell) {
            cell = [[RankCommentCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kRankingCell];
        }
        RankListModel *rankListModel = _rankData[indexPath.section - 1];
        NSDictionary *dict = rankListModel.comments[indexPath.row];
        RankCommentModel *commentModel = [[RankCommentModel alloc] init];
        [commentModel setValuesForKeysWithDictionary:dict];
        cell.rankComment = commentModel;
        return cell;
    }
}

// cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            if (!_backGroundView) {
                _backGroundView = [[UIView alloc] initWithFrame:self.view.bounds];
                UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBackGroundView)];
                [_backGroundView addGestureRecognizer:tapGR];
            }
            if (!_pickerView) {
                _pickerView = [[RankPickView alloc] init];
                _pickerView.backgroundColor = [UIColor whiteColor];
                _pickerView.pickerView.delegate = self;
                _pickerView.pickerView.dataSource = self;
                _pickerView.pickerView.showsSelectionIndicator = YES;
            }
            _backGroundView.alpha = 0;
            _backGroundView.backgroundColor = [UIColor blackColor];
            [self.view insertSubview:_backGroundView aboveSubview:_tableView];
            [self.view insertSubview:_pickerView aboveSubview:_backGroundView];
            
            _pickerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 200);
            [_pickerView.okButton addTarget:self action:@selector(okClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [UIView animateWithDuration:0.3 animations:^{
                _backGroundView.alpha = 0.6;
                _pickerView.frame = CGRectMake(0, kScreenHeight - 200, kScreenWidth, 200);
            }];
            
            
        } else if (indexPath.row == 1) {
            SelectStoreViewController *select = [[SelectStoreViewController alloc] init];
            select.delegate = self;
            [self.navigationController pushViewController:select animated:YES];
        } else {
            return;
        }
    } else {
        RankListModel *rankList = _rankData[indexPath.section - 1];
        RankDetailViewController *rankDetailVC = [[RankDetailViewController alloc] init];
        rankDetailVC.indexRow = rankList.index;
        rankDetailVC.uuid = rankList.uuid;
        rankDetailVC.commentId = rankList.commentId;
        rankDetailVC.store_uuid = rankList.store_uuid;
        rankDetailVC.storeAddress = rankList.storeAddress;
        rankDetailVC.storePictures = rankList.storePictures;
        [self.navigationController pushViewController:rankDetailVC animated:YES];
    }
}

// cell的高度

// section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGFLOAT_MIN;
    } else {
        return 50;
    }
}

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

// 自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    } else {
        RankListModel *rankList = _rankData[section - 1];
        RankListHeaderView *headView = [RankListHeaderView headViewWithTableView:tableView section:section - 1 index:rankList.index];
        headView.delegate = self;
        
        if (_statisMode == 1) {
            [headView.pushButton removeTarget:self action:@selector(pushclick:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [headView.pushButton addTarget:self action:@selector(pushclick:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        headView.rankListModel = rankList;
        return headView;
    }
}

- (void)pushclick:(UIButton *)sender
{
    NSInteger section = sender.tag - kPushTag;
    RankListModel *rankList = _rankData[section];
    
    RankDetailViewController *rankDetailVC = [[RankDetailViewController alloc] init];
    rankDetailVC.indexRow = rankList.index;
    rankDetailVC.uuid = rankList.uuid;
    rankDetailVC.store_uuid = rankList.store_uuid;
    rankDetailVC.commentId = rankList.commentId;
    rankDetailVC.storeAddress = rankList.storeAddress;
    rankDetailVC.storePictures = rankList.storePictures;
    [self.navigationController pushViewController:rankDetailVC animated:YES];
}

#pragma mark - PickViewDelegate/DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _titleArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSDictionary *dict = _titleArray[row];
    NSString *title = [NSString stringWithFormat:@"%@", dict[@"name"]];
    return title;
}



#pragma mark - lazy loading

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 100.0;
        [_tableView registerClass:[RankCommentCell class] forCellReuseIdentifier:kRankingCell];
        [_tableView registerClass:[OnLineTableViewCell class] forCellReuseIdentifier:konlineCell];
        [_tableView registerClass:[RankScreenTableViewCell class] forCellReuseIdentifier:kRankScreenTableViewCell];
        [_tableView registerClass:[HomeTitleTableCell class] forCellReuseIdentifier:kHomeTitleCellInde];

        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, CGFLOAT_MIN)];
        [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;
}

- (NoDataView *)noDataView
{
    if (!_noDataView) {
        _noDataView = [[NoDataView alloc] init];
        _noDataView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:_noDataView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_noDataView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_noDataView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_noDataView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableBottom = [NSLayoutConstraint constraintWithItem:_noDataView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableBottom];
    }
    return _noDataView;
}

- (void)clickHeadView
{
    [_tableView reloadData];
}


@end
