//
//  ForumItemDetailViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/12/12.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ForumItemDetailViewController.h"
#import "CommentListTableViewCell.h"
#import "PostPhotoManagerViewController.h"

@interface ForumItemDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,TapClickDelegate>


@property (nonatomic,strong) ForumReplyResponse *topicReply;

/**
 评论列表
 */
@property (nonatomic,strong) NSMutableArray *commentsArray;

/**
 headerView
 */
@property (weak, nonatomic) IBOutlet UIView *tableViewHeaderView;

/**
 发贴人头像
 */
@property (weak, nonatomic) IBOutlet UIImageView *issuerImageView;

/**
 贴心标题
 */
@property (weak, nonatomic) IBOutlet UILabel *postTitleLabel;

/**
 发帖人姓名、时间
 */
@property (weak, nonatomic) IBOutlet UILabel *issuerNameAndDateLabel;

/**
 删除帖子
 */
@property (weak, nonatomic) IBOutlet UIButton *delectButton;

/**
 帖子内容
 */
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;

/**
 获取回复列表
 */
@property (nonatomic,strong) ForumReplyCondition *condition;


@end

@implementation ForumItemDetailViewController

#pragma mark - lazy
- (NSMutableArray *)commentsArray
{
    if (!_commentsArray) {
        _commentsArray = [NSMutableArray array];
    }
    return _commentsArray;
}

- (ForumReplyCondition *)condition
{
    if (!_condition) {
        _condition = [[ForumReplyCondition alloc] init];
        DataPage *page = [[DataPage alloc] init];
        page.page = ONE;
        page.rows = KROWS;
        _condition.page = page;
        _condition.topicIdEquals = self.topicDetail.fid;
    }
    return _condition;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getPostDetailAction:NO];
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.commentView.layer.borderWidth = 1.0f;
    self.commentView.layer.borderColor = RGB(237, 238, 239, 1).CGColor;
    self.commentView.layer.cornerRadius = 4;
    self.commentView.layer.masksToBounds = YES;
    self.forumDetailTableView.tableFooterView = [UIView new];
}

#pragma mark - 获取回复列表
- (void)getPostDetailAction:(BOOL)isRemove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(POSTDETAIL) WithRequestType:ZERO WithParameter:self.condition WithReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (isRemove) {
                [weakSelf.commentsArray removeAllObjects];
            }
            weakSelf.topicReply = [[ForumReplyResponse alloc] initWithDictionary:returnValue[@"data"] error:nil];
            [weakSelf.commentsArray addObjectsFromArray:weakSelf.topicReply.forumReplyEntity];
            [weakSelf setUpCommentNumber];
            [weakSelf setUpHeaderView];
            [weakSelf.forumDetailTableView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 设置HeaderView
- (void)setUpHeaderView
{
    self.postTitleLabel.text = self.topicDetail.title;
    self.contentLabel.text = self.topicDetail.content;
    self.issuerNameAndDateLabel.text = [NSString stringWithFormat:@"%@:  %@  %@",self.topicDetail.posterPosition,self.topicDetail.posterRealName,self.topicDetail.postTime];
    //图片
    PostPhotoManagerViewController *photoManager = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"PostPhotoManagerViewController"];
    [self addChildViewController:photoManager];
    NSMutableArray *array = [NSMutableArray array];
    for (TOAttachmentEntity *entity in self.topicDetail.attachments) {
        [array addObject:entity.fileUrl];
    }
    CGFloat attachment = [self calculateImageHeight];
    photoManager.imageArray = array;
    [self.tableViewHeaderView addSubview:photoManager.view];
    self.tableViewHeaderView.height = attachment + self.topicDetail.contentHeight + self.contentLabel.top + 20;
    photoManager.view.frame = CGRectMake(self.contentLabel.left, self.topicDetail.contentHeight+10+self.contentLabel.top, self.contentLabel.width, attachment);
    self.delectButton.hidden = ![self.topicDetail.posterId isEqualToString:[Shoppersmanager manager].Shoppers.employee.fid];
    self.forumDetailTableView.tableHeaderView = self.tableViewHeaderView;
}

#pragma mark - 设置评论个数
- (void)setUpCommentNumber
{
    self.commentNumberLabel.text = [NSString stringWithFormat:@"已有%ld条评论",self.commentsArray.count];
    self.praiseButton.selected = !self.topicDetail.canLike;
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentListTableViewCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"CommentListTableViewCell" forIndexPath:indexPath];
    commentCell.bestView.delegate = self;
    commentCell.indexPath = indexPath;
    commentCell.replyEntity = self.commentsArray[indexPath.row];
    commentCell.optionButton.hidden = ![self.topicDetail.posterId isEqualToString:[Shoppersmanager manager].Shoppers.employee.fid];
    return commentCell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOForumReplyEntity *replyEntity = self.commentsArray[indexPath.row];
    //68为上边距   10为下边距
    return replyEntity.replyContentHeight + 68 + 10;
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentListTableViewCell *commentCell = (CommentListTableViewCell *)cell;
    commentCell.bestView.hidden = YES;
}

#pragma mark - 计算选中图片显示所需高度
- (CGFloat)calculateImageHeight
{
    //默认每行显示8张图片
    CGFloat height = (ScreenWidth-40-2*10)/3;
    CGFloat interval = 10;
    CGFloat allHeight = 0;
    NSInteger number = self.topicDetail.attachments.count/3;
    if (self.topicDetail.attachments.count == 0) {
        return allHeight;
    }else if (self.topicDetail.attachments.count < 3) {
        return height;
    }else if (self.topicDetail.attachments.count %3 == 0) {
        allHeight = number*height + (number-1)*interval;
    }else if (number) {
        allHeight = (number+1)*height + number*interval;
    }
    return allHeight;
}

#pragma mark - 确认回复
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([[self class] isBlankString:textField.text]) {
        [XBLoadingView showHUDViewWithText:@"评论内容不能为空"];
    }else {
        [self replyPostRequest];
    }
    return YES;
}

#pragma mark - 回复帖子
- (void)replyPostRequest
{
    [self.view endEditing:YES];
    TOForumReplyEntity *reply = [[TOForumReplyEntity alloc] init];
    reply.topicId = self.topicDetail.fid;
    reply.replyContent = self.commentInputTextFieldView.text;
    reply.replyerName = [Shoppersmanager manager].Shoppers.employee.userName;
    reply.replyerRealName = [Shoppersmanager manager].Shoppers.employee.realName;
    reply.replyerPosition = [Shoppersmanager manager].Shoppers.employee.positionsName;
    reply.replyTime = [[self class] getTimeby:0];
    reply.replyerId = [Shoppersmanager manager].Shoppers.employee.fid;
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(REPLYPOST) WithRequestType:ZERO WithParameter:reply WithReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            weakSelf.commentInputTextFieldView.text = nil;
            [XBLoadingView showHUDViewWithSuccessText:@"评论成功" completeBlock:^{
                [weakSelf getPostDetailAction:YES];
            }];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 删除帖子
- (IBAction)delecteClickPostAction:(UIButton *)sender
{
    [self promptBoxWithMessage:@"确认删除此贴吗?" cancelBlock:^{
        NSLog(@"取消");
    } sureBlock:^{
        [XBLoadingView showHUDViewWithDefault];
        WS(weakSelf);
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(DELETEPOST),self.topicDetail.fid] WithRequestType:NetworkRequestWithDELETE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            [XBLoadingView hideHUDViewWithDefault];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                [XBLoadingView showHUDViewWithSuccessText:@"删除成功" completeBlock:^{
                    if (weakSelf.delectBlock) {
                        weakSelf.delectBlock(weakSelf.topicDetail.fid);
                    }
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
            }else {
                [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
            }
            
        } WithFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    }];
}

#pragma mark - <TapClickDelegate>
#pragma mark -最佳回复
- (void)tapClickAction:(BOOL)isBest withReplyId:(NSString *)replyId withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    NSLog(@"%@",[NSString stringWithFormat:SERVERREQUESTURL(BASEREPLY),self.topicDetail.fid,replyId,isBest?@"true":@"false"]);
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(BASEREPLY),self.topicDetail.fid,replyId,isBest?@"true":@"false"] WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [weakSelf getPostDetailAction:YES];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 点赞
- (IBAction)praiseButtonClickAction:(UIButton *)sender {
    
    [XBLoadingView showHUDViewWithDefault];
    NSString *url = [NSString stringWithFormat:SERVERREQUESTURL(PRAISE),self.topicDetail.fid,!sender.selected?@"true":@"false"];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:url WithRequestType:ONE WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            sender.selected = !sender.selected;
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } WithFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


@end