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

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

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


@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 *shareButton;

/**
 删除
 */
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;

/**
 帖子内容
 */
@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];
    BOOL boolValue = ![self.topicDetail.posterId isEqualToString:[Shoppersmanager manager].Shoppers.employee.fid];
    self.deleteButton.hidden = boolValue;
}

#pragma mark - 获取回复列表
- (void)getPostDetailAction:(BOOL)isRemove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(POSTDETAIL) withRequestType:ZERO withParameter:self.condition withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            if (isRemove) {
                [weakSelf.commentsArray removeAllObjects];
            }
            weakSelf.topicReply = [[ForumReplyResponse alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.commentsArray addObjectsFromArray:weakSelf.topicReply.forumReplyEntity];
            [weakSelf setUpCommentNumber];
            [weakSelf setUpHeaderView];
            [weakSelf.forumDetailTableView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
    } withFailureBlock:^(NSError *error) {
        [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,[BaseViewController formateDate:self.topicDetail.postTime]];
    NSString *headerurl = [Shoppersmanager manager].Shoppers.employee.picture;
    [self.issuerImageView sd_setImageWithURL:[NSURL URLWithString:headerurl] placeholderImage:ReplaceImage];
    if (self.topicDetail.backEnd) {
        self.issuerImageView.image = TCImage(@"Icon-83.5");
    }else {
        [self.issuerImageView sd_setImageWithURL:[NSURL URLWithString:self.topicDetail.posterPicture] placeholderImage:ReplaceImage];
    }
    //图片
    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 + 10;
    photoManager.view.frame = CGRectMake(self.contentLabel.left, self.topicDetail.contentHeight+10+self.contentLabel.top, self.contentLabel.width, attachment);
    self.forumDetailTableView.tableHeaderView = self.tableViewHeaderView;
}

#pragma mark - 设置评论个数
- (void)setUpCommentNumber
{
    self.commentNumberLabel.text = [NSString stringWithFormat:@"已有%ld条评论",(unsigned long)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];
    BOOL boolValue = ([self.topicDetail.posterId isEqualToString:[Shoppersmanager manager].Shoppers.employee.fid] && [self.category.name isEqualToString:OPPLE_ASK]);
    commentCell.optionButton.hidden = !boolValue;
    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.width = ZERO;
    commentCell.bestView.x = commentCell.optionButton.x;
}

#pragma mark - 计算选中图片显示所需高度
- (CGFloat)calculateImageHeight
{
    //默认每行显示3张图片
    CGFloat height = (ScreenWidth-60-2*10)/3.0;
    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);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(REPLYPOST) withRequestType:ZERO withParameter:reply withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.commentInputTextFieldView.text = nil;
            [XBLoadingView showHUDViewWithSuccessText:@"评论成功" completeBlock:^{
                if (weakSelf.refreshBlock) {
                    weakSelf.refreshBlock(ONE,Comment,weakSelf.indexPath);
                }
                [weakSelf getPostDetailAction:YES];
            }];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -删除
- (IBAction)deleteButtonClickAction:(UIButton *)sender {
    [self delecteClickPostAction];
}

#pragma mark -分享
- (IBAction)shareButtonClickAction:(UIButton *)sender {
    [self sharePostClickAction];
}

#pragma mark - 删除帖子
- (void)delecteClickPostAction
{
    ShowDefaultAlertView(self, nil, @"确认删除此贴吗?", UIAlertControllerStyleActionSheet, ^{
        [XBLoadingView showHUDViewWithDefault];
        WS(weakSelf);
        [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(DELETEPOST),self.topicDetail.fid] withRequestType:NetworkRequestWithDELETE withParameter:nil withReturnValueBlock:^(id returnValue) {
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                [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];
        }];
    }, nil);
}

#pragma mark -分享帖子
- (void)sharePostClickAction
{
    ShareGoodsViewController *shareController = [[ShareGoodsViewController alloc]init];
    shareController.type = SHARE_INVITATION;
    shareController.shareID = self.topicDetail.fid;
    shareController.shareImage = [UIImage imageNamed:@"Icon-83.5"];
    [self popoverPresentationController:shareController withPreferredContentSize:CGSizeMake(290, 120) withBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:self.shareButton]];
}


#pragma mark - <TapClickDelegate>
#pragma mark -最佳回复
- (void)tapClickAction:(BOOL)isBest withReplyId:(NSString *)replyId withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(BASEREPLY),self.topicDetail.fid,replyId,isBest?@"true":@"false"] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf getPostDetailAction:YES];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } withFailureBlock:^(NSError *error) {
        [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"];
    WS(weakSelf);
    [HTTP networkWithDictionaryRequestWithURL:url withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            sender.selected = !sender.selected;
            //刷新列表
            if (weakSelf.refreshBlock) {
                weakSelf.refreshBlock(sender.selected?ONE:-ONE,Praise,weakSelf.indexPath);
            }
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


@end