//
//  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 <MBProgressHUD.h>
#import "HttpClient.h"

#import "TaskGroup.h"
#import "TaskModel.h"
#import "TaskDetailModel.h"
#import "CheckPicViewController.h"
#import "CommentView.h"

#import <UIButton+WebCache.h>

#define kRankDetailCell @"RankDetailTableCell"

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

@property (nonatomic, strong) RankDetailHeaderView *rankDetailHeaderView;

@property (nonatomic, strong) NSMutableArray *taskData;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) NSMutableDictionary *selectedIndexes; // 存放二次展开的cell
@property (nonatomic, strong) UIButton *commentButton;

@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, strong) CommentView *commentView;

@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 whiteColor];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    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.selectedIndexes = [[NSMutableDictionary alloc] init];
    // 请求口碑排名详情
    [self requestRankingDetail];
    
    [self.commentButton setTitle:@"添加评论" forState:UIControlStateNormal];

}

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

#pragma mark - Private Methods

- (void)requestRankingDetail
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@/%@",kRedStarURL, kInspectDetailURL, self.uuid, self.store_uuid];
    NSLog(@"url = %@" , url);
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    
    [httpClient getPraiseDetailWithParameters:nil completion:^(id response, NSError *error) {
        NSLog(@"口碑巡检明细PraiseDetail = %@", response);
        NSDictionary *dataDict = response[@"data"];
        TaskDetailModel *taskDetail = [TaskDetailModel taskDetailModelWithDict:dataDict];
        self.rankDetailHeaderView.taskDetail = taskDetail;

        NSArray *dataArray = dataDict[@"categories"];
        
        NSMutableArray *tgArray = [NSMutableArray array];
        for (NSDictionary *dict in dataArray) {
            TaskGroup *taskGroup = [TaskGroup taskGroupWithDict:dict];
            [tgArray addObject:taskGroup];
        }
        
        _taskData = tgArray;

        
        self.tableView.tableHeaderView = self.rankDetailHeaderView;
        [self.tableView registerClass:[RankDetailTableCell class] forCellReuseIdentifier:kRankDetailCell];
        [self setupScrollView];
    }];

}
- (void)addComment:(UIButton *)sender
{
    if (!_backGroundView) {
        _backGroundView = [[UIView alloc] initWithFrame:self.view.bounds];
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeBackGroundView)];
        [_backGroundView addGestureRecognizer:tapGR];
    }
    if (!_commentView) {
        _commentView = [[CommentView alloc] init];
        _commentView.backgroundColor = [UIColor whiteColor];
    }
    _commentView.contentTextView.text = @"";
    [_commentView.quitBtn addTarget:self action:@selector(closeBackGroundView) forControlEvents:UIControlEventTouchUpInside];
    [_commentView.sureBtn addTarget:self action:@selector(submitComment:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_backGroundView aboveSubview:_tableView];
    [self.view insertSubview:_commentView aboveSubview:_backGroundView];
    
    _backGroundView.alpha = 0;
    _backGroundView.backgroundColor = [UIColor blackColor];
    
    CGRect toFrame = CGRectMake(0, self.view.frame.size.height - kCommentViewHeight, kScreenWidth, kCommentViewHeight);
    CGRect fromFrame = CGRectMake(0, kScreenHeight, kScreenWidth, kCommentViewHeight);
    
    _commentView.frame = fromFrame;
    [UIView animateWithDuration:0.3 animations:^{
        _backGroundView.alpha = 0.6;
        _commentView.frame = toFrame;
    }];
    
}


// 提交评论
- (void)submitComment:(UIButton *)sender
{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd+hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localeDate];
    
    
    NSString *operId = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_code"];
    NSString *operName = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_name"];
    
    NSString *url  = [NSString stringWithFormat:@"%@%@?time=%@&operId=%@&operName=%@", kRedStarURL, kAddCommentURL , dateString , operId, operName];
    url = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"url = %@", url);
    
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    NSDictionary *parameters = @{@"entityType":@"question",
                                 @"entityUuid":self.uuid,
                                 @"comment":_commentView.contentTextView.text};
    NSLog(@"parameters = %@", parameters);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpClient submitCommentWithParameters:parameters completion:^(id response, NSError *error) {
        NSLog(@"respo = %@, error = %@", response , error);
        if ([response[@"message"] isEqualToString:@"ok"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加评论成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            alert.delegate = self;
            [alert show];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"添加评论失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    }];
    
    [self closeBackGroundView];
}

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

// 返回上一页面
- (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(showBigPic:) forControlEvents:UIControlEventTouchUpInside];
        [self.rankDetailHeaderView.rankDetailView.showScrollView addSubview:button];
    }
}

- (void)showBigPic:(UIButton *)btn
{
    CheckPicViewController *checkVC = [[CheckPicViewController alloc] init];
    checkVC.checkImage = btn.imageView.image;
    [self.navigationController pushViewController:checkVC animated:YES];
}


- (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);
        }];
        NSArray *imgaeUrlArray = cell.task.answerAttachments;
        NSMutableArray *urlArray = [NSMutableArray array];
        for (NSDictionary *imageUrlDict in imgaeUrlArray) {
            NSString *urlStr = [NSString stringWithFormat:@"%@%@", kRedStarURL, imageUrlDict[@"fileUrl"]];
            [urlArray addObject:urlStr];
        }
        
        CGFloat marginW = 5.0;
        CGFloat imageViewW = 90 + 2 * marginW;
        
        cell.scrollView = [[UIScrollView alloc] init];
        cell.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
        cell.scrollView.contentSize = CGSizeMake((urlArray.count - 1) * imageViewW, 65);
        [cell.contentView addSubview:cell.scrollView];
        
        
        for (int i = 0; i < urlArray.count; i++) {
            UIButton *button = [[UIButton alloc] init];
            button.translatesAutoresizingMaskIntoConstraints = NO;
            NSString *urlStr = [NSString stringWithFormat:@"%@", urlArray[i]];
            NSURL *url = [NSURL URLWithString:urlStr];
            [button sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"default_pic"]];
            [button addTarget:self action:@selector(showBigPic:) forControlEvents:UIControlEventTouchUpInside];
            [cell.scrollView addSubview:button];
            
            
            NSLayoutConstraint *urlTop = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.scrollView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
            [cell.scrollView addConstraint:urlTop];
            
            NSLayoutConstraint *urlLeft = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell.scrollView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:i * imageViewW];
            [cell.scrollView addConstraint:urlLeft];
            
            NSLayoutConstraint *urlWidth = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:imageViewW];
            [cell.scrollView  addConstraint:urlWidth];
            
            NSLayoutConstraint *urlHeight = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:65];
            [cell.scrollView addConstraint:urlHeight];
        }
        
        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 _taskData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    TaskGroup *taskGroup = _taskData[section];
    NSInteger count = taskGroup.isOpened ? taskGroup.answers.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];
    }
    
    TaskGroup *taskGroup = _taskData[indexPath.section];
    TaskModel *task = taskGroup.answers[indexPath.row];
    
    cell.task = task;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    [cell.mainTitleBtn setTitle:[NSString stringWithFormat:@"%d、%@", (int)(indexPath.row + 1) ,task.title] forState:UIControlStateNormal];
    if (task.score == NULL || task.score == nil) {
        cell.scoreLabel.text = [NSString stringWithFormat:@"0分"];
    } else {
        cell.scoreLabel.text = [NSString stringWithFormat:@"%@分", task.score];
    }
    // 按钮点击事件
    [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.taskGroup = _taskData[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;
        _tableView.tableFooterView = self.footerView;
        [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)];
        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;
}

- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
        
    }
    return _footerView;
}

- (UIButton *)commentButton
{
    if (!_commentButton) {
        _commentButton = [[UIButton alloc] init];
        // 设置圆角
        _commentButton.layer.cornerRadius = 5;
        _commentButton.translatesAutoresizingMaskIntoConstraints = NO;
        _commentButton.backgroundColor = kLoginButtonBackGroundColor;
        [_commentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_commentButton addTarget:self action:@selector(addComment:) forControlEvents:UIControlEventTouchUpInside];
        _commentButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
        [self.footerView addSubview:_commentButton];
        
        // 顶端
        NSLayoutConstraint *loginTop = [NSLayoutConstraint constraintWithItem:_commentButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:20];
        [self.footerView addConstraint:loginTop];
        
        // 左边
        NSLayoutConstraint *loginLeft = [NSLayoutConstraint constraintWithItem:_commentButton attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
        [self.footerView addConstraint:loginLeft];
        
        // 右边
        NSLayoutConstraint *loginRight = [NSLayoutConstraint constraintWithItem:_commentButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.footerView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-20];
        [self.footerView addConstraint:loginRight];
        
        // 高度
        NSLayoutConstraint *loginHeight = [NSLayoutConstraint constraintWithItem:_commentButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40];
        [self.footerView addConstraint:loginHeight];
    }
    return _commentButton;
}
/*
#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
