//
//  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"
#import "WkWebViewViewController.h"
#import "AnnouncementContentTableViewCell.h"
#import "ForumDetailPhotoTableViewCell.h"
#import "ZJKeyBoardAccessoryView.h"
#import "ForumDetailBottomView.h"
#import "OSSHelper.h"
#import "ForumCommentListViewModel.h"
#import "UIImage+Helper.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 (nonatomic,assign) CGFloat contentHeigt;

/**
 图片附件高度
 */
@property (nonatomic,assign) CGFloat attachmentHeight;

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


/**
 底部的view
 */
@property (weak, nonatomic) IBOutlet ForumDetailBottomView *bottomView;



@end

@implementation ForumItemDetailViewController

#pragma mark - lazy
- (NSMutableArray *)commentsArray
{
    if (!_commentsArray) {
        _commentsArray = [NSMutableArray arrayWithObjects:@"",@"", nil];
    }
    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 addChildWebViewController];
    [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;
    [self.forumDetailTableView registerClass:[AnnouncementContentTableViewCell class] forCellReuseIdentifier:@"AnnouncementContentTableViewCell"];
    [self.forumDetailTableView registerClass:[ForumDetailPhotoTableViewCell class] forCellReuseIdentifier:@"ForumDetailPhotoTableViewCell"];
    [self setUpHeaderView];
    self.forumDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.commentInputTextFieldView.inputAccessoryView = self.bottomView.toolView;
    

    
}

#pragma mark - WKWebView/photoManager
- (void)addChildWebViewController
{
    WS(weakSelf);
    WkWebViewViewController *webView = [[WkWebViewViewController alloc]initWithReturnContentSize:^(CGFloat contentHeight) {
        weakSelf.contentHeigt = contentHeight;
        [weakSelf.forumDetailTableView reloadData];
    }];
    self.contentHeigt = 44;//默认值
    webView.view.frame = CGRectMake(0, 0, ScreenWidth, self.contentHeigt);
    [self addChildViewController:webView];
    //图片
    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];
    }
    self.attachmentHeight = [self calculateImageHeight];
    photoManager.view.height = self.attachmentHeight;
    photoManager.imageArray = array;
}

#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.commentsArray = nil;
            }
            weakSelf.topicReply = [[ForumReplyResponse alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            for (CustomTOForumReplyEntity *entity in weakSelf.topicReply.forumReplyEntity) {
                ForumCommentListViewModel *model = [ForumCommentListViewModel new];
                model.replyEntity = entity;
                [weakSelf.commentsArray addObject:model];
    
            }
            [weakSelf setUpCommentNumber];
            [weakSelf.forumDetailTableView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 设置HeaderView
- (void)setUpHeaderView
{
    self.postTitleLabel.text = self.topicDetail.title;
        //系统管理员
    if (self.topicDetail.backEnd) {
        self.issuerImageView.image = GuideReplaceImage;
        self.issuerNameAndDateLabel.text = [NSString stringWithFormat:@"%@  %@",self.topicDetail.posterRealName,[BaseViewController formateDate:self.topicDetail.postTime]];
    }else {
        //普通用户
        [self.issuerImageView sd_setImageWithURL:[NSURL URLWithString:self.topicDetail.posterPicture] placeholderImage:CoustomerReplaceImage];
        self.issuerNameAndDateLabel.text = [NSString stringWithFormat:@"%@:  %@  %@",self.topicDetail.posterPosition,self.topicDetail.posterRealName,[BaseViewController formateDate:self.topicDetail.postTime]];
    }
}

- (void)viewDidLayoutSubviews {
    self.tableViewHeaderView.height = 80;
    self.forumDetailTableView.tableHeaderView = self.tableViewHeaderView;
}

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

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
            case 0:
        {
            AnnouncementContentTableViewCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"AnnouncementContentTableViewCell" forIndexPath:indexPath];
            [contentCell.contentView addSubview:self.childViewControllers[0].view];
            return contentCell;
        }
            break;
            case 1:
        {
            ForumDetailPhotoTableViewCell *photoCell = [tableView dequeueReusableCellWithIdentifier:@"ForumDetailPhotoTableViewCell" forIndexPath:indexPath];
            [photoCell.contentView addSubview:self.childViewControllers[1].view];
            return photoCell;
        }
            break;

    }
    CommentListTableViewCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"CommentListTableViewCell" forIndexPath:indexPath];
    commentCell.bestView.delegate = self;
    commentCell.indexPath = indexPath;
    ForumCommentListViewModel *cellModel = self.commentsArray[indexPath.row];
    commentCell.replyEntity = cellModel.replyEntity;
    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
{
    switch (indexPath.row) {
            case 0:
        {
            return self.contentHeigt;

        }
            break;
            case 1:
        {
            return self.attachmentHeight;
        }
            break;
    }
    ForumCommentListViewModel *cellModel = self.commentsArray[indexPath.row];
    //68为上边距   10为下边距
    return cellModel.height;
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
            case 0:
            case 1:
            return;
    }
    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
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];

    if ([[self class] isBlankString:textField.text]) {
        [XBLoadingView showHUDViewWithText:@"评论内容不能为空"];
    }else {
        [self replyPostRequest];
    }
    return YES;
}

#pragma mark - 上传图片附件
- (void)uploadAttachments:(void(^)(NSArray *OSSKeys))finish
{
    if (self.bottomView.toolView.arrSelectedPhotos.count == 0) {
        finish(nil);
        return;
    }
    NSMutableArray *OSSKeyArray = [NSMutableArray array];
    for (int i=0; i<self.bottomView.toolView.arrSelectedPhotos.count; i++) {
        [OSSKeyArray addObject:[OSSHelper getOSSObjectKeyWithtype:@"jpg" index:i]];
    }
    XBLoadingView *loadView = [XBLoadingView showHUDViewProgressLabel:[NSString stringWithFormat:@"图片上传中:1/%ld",self.bottomView.toolView.arrSelectedPhotos.count]];
    static NSInteger number = 0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i=0;i<self.bottomView.toolView.arrSelectedPhotos.count;i++) {
            UIImage *image = self.bottomView.toolView.arrSelectedPhotos[i];
            NSString *ossKey = OSSKeyArray[i];
            UIImage *newSizeImage = [image scaledToWidth:1024];
            NSData *data = [newSizeImage scaledToSpaceMaxSize:200];
            [OSSHelper uploadImageObjectWithKey:ossKey data:data type:OSSHelperOperationTypeSynchronous progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                CGFloat totalBytesSentFloat = totalBytesSent;
                CGFloat totalBytesExpectedToSendFloat = totalBytesExpectedToSend;
                CGFloat progress = totalBytesSentFloat / totalBytesExpectedToSendFloat;
                NSLog(@"-->进度%f", progress);
                loadView.progress = progress;
                
            } success:^id(OSSTask *task) {
                
                number ++;
                loadView.labelText = [NSString stringWithFormat:@"图片上传中:%ld/%ld",number,self.self.bottomView.toolView.arrSelectedPhotos.count];
                if (number == self.bottomView.toolView.arrSelectedPhotos.count) {
                    number = 0;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [loadView hide:YES];
                        [XBLoadingView showHUDViewWithSuccessText:@"图片上传成功" completeBlock:^{
                            finish(OSSKeyArray);
                        }];
                    });
                }
                return nil;
            } error:^(NSError *error) {
                [XBLoadingView hideHUDViewWithDefault];
                [XBLoadingView showHUDViewWithText:error.localizedDescription];
            }];
        }
    });
}



#pragma mark - 回复帖子
- (void)replyPostRequest
{
    WS(weakSelf);
    [self uploadAttachments:^(NSArray *OSSKeys) {
        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;
        reply.isAdminReply = [Shoppersmanager manager].shoppers.isAdmin;
        NSMutableArray *attachments = [NSMutableArray array];
        NSString *entityId = [OSSHelper getOSSObjectKey];
        reply.attachmentId = entityId;
        for (NSString *ossKey in OSSKeys) {
            TOAttachmentEntity *entity = [[TOAttachmentEntity alloc] init];
            entity.entityType = @"forumReply";
            entity.entityId = entityId;
            entity.fileUrl = [OSSHelper getCompleteImageURLWithOSSkey:ossKey];
            entity.fileName = ossKey;
            [attachments addObject:entity];
        }
        reply.attachments = (NSArray<TOAttachmentEntity>*)attachments;
        [weakSelf httpSubmit:reply complete:nil];
    }];
}

- (void)httpSubmit:(TOForumReplyEntity *)reply complete:(void (^)(void))complete {
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(REPLYPOST) withRequestType:ZERO withParameter:reply withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.commentInputTextFieldView.text = nil;
            [weakSelf.bottomView clearPhoto];
            [XBLoadingView showHUDViewWithSuccessText:@"评论成功" completeBlock:^{
                if (weakSelf.refreshBlock) {
                    weakSelf.refreshBlock(ONE,Comment,weakSelf.indexPath);
                }
                [weakSelf getPostDetailAction:YES];
            }];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } 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
{
    ShowAlertView(@"提示", @"确认删除此贴吗？", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
        [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:MESSAGE(returnValue)];
            }
            
        } withFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    });
}

#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:MESSAGE(returnValue)];
        }
        
    } 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:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


@end
