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

#import "ForumItemListViewController.h"
#import "ForumItemTableViewCell.h"
#import "ReleasePostViewController.h"
#import "ForumItemDetailViewController.h"
#import "MWPhotoBrowser.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "CommentTagTableViewCell.h"

static NSString *CELL_IDENTIFIER = @"ForumItemTableViewCell";
static NSString *TAGCELL_IDENTIFIER = @"CommentTagTableViewCell";


@interface ForumItemListViewController ()<UITableViewDelegate,UITableViewDataSource,TapClickImageViewDelegate,MWPhotoBrowserDelegate>


/**
 结果
 */
@property (nonatomic,strong) ForumTopicResponse *forumResult;

/**
 查询
 */
@property (nonatomic,strong) ForumTopicCondition *condition;
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 图片数组
 */
@property (nonatomic,strong) NSMutableArray *selecteImageArray;
@end

@implementation ForumItemListViewController

#pragma mark - lazy
- (ForumTopicCondition *)condition
{
    if (!_condition) {
        _condition = [[ForumTopicCondition alloc] init];
        DataPage *page = [[DataPage alloc] init];
        page.page = ONE;
        page.rows = KROWS;
        _condition.categoryEquals = self.category.fid;
        _condition.page = page;
    }
    return _condition;
}

- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

- (NSMutableArray *)selecteImageArray
{
    if (!_selecteImageArray) {
        _selecteImageArray = [NSMutableArray array];
    }
    return _selecteImageArray;
}

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


#pragma mark - UI
- (void)uiConfigAction
{
    [self.postingButton horizontalCenterImageAndTitle:5];
    self.classifyTitleLabel.text = self.category.name;
    [self.classifyImageView sd_setImageWithURL:[NSURL URLWithString:self.category.attachmentBg.fileUrl] placeholderImage:REPLACEIMAGE];
    [self.classIconImageView sd_setImageWithURL:[NSURL URLWithString:self.category.attachment.fileUrl] placeholderImage:REPLACEIMAGE];
    if (self.isPosting) {
        [self.postingButton setTitle:(self.isPosting == 1)?@"我要发帖":@"我要提问" forState:UIControlStateNormal];
    }else {
        self.postingButton.hidden = YES;
    }
}

#pragma mark -加载数据
- (void)loadWebDataSource
{
    WS(weakSelf);
    if (self.pullPageIndex == ONE) {
        [self.datasArray removeAllObjects];
    }
    self.condition.page.page = self.pullPageIndex;
    [self getClassificationList:self.condition completed:^(ForumTopicResponse *result) {
        if (weakSelf.pullPageIndex >= result.totalpages) {
            [weakSelf endRefresh:EndRefreshNotData];
        }else {
            [weakSelf endRefresh:EndRefreshDefault];
        }
    }];
}

#pragma mark - 获取分类帖子列表
- (void)getClassificationList:(ForumTopicCondition *)condtion completed:(void(^)(ForumTopicResponse *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(QUERTFORUMLIST) withRequestType:ZERO withParameter:condtion withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            ForumTopicResponse *result = [[ForumTopicResponse alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(result);
            weakSelf.forumResult = result;
            [weakSelf.datasArray addObjectsFromArray:result.forumTopicEntity];
            weakSelf.classifyListCountLabel.text = [NSString stringWithFormat:@"%ld",result.total];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        [weakSelf.tableView reloadData];
    } withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 读帖
- (void)readTopic:(NSString *)forumTopicId finish:(void(^)())block {
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(READTOPIC),forumTopicId,[Shoppersmanager manager].shoppers.employee.fid] withRequestType:POST withParameter:nil withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            if (block) {
                block();
            }
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 发帖
- (IBAction)releaseButtonClickAction:(UIButton *)sender {
    
    ReleasePostViewController *releaseVc = [ReleasePostViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
    releaseVc.category = self.category;
    WS(weakSelf);
    [releaseVc setFinishBlock:^{
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    [self pushViewController:releaseVc animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOForumTopicEntity *entity = self.datasArray[indexPath.row];
    if (entity.backEnd || entity.bestTopic || ![[self class] isBlankString:entity.top]) {
        CommentTagTableViewCell *tagCell = [tableView dequeueReusableCellWithIdentifier:TAGCELL_IDENTIFIER forIndexPath:indexPath];
        [self configTagCellAction:tagCell withIndexPath:indexPath];
        return tagCell;
    }
    ForumItemTableViewCell *commonCell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
    [self configCommonCellAction:commonCell withIndexPath:indexPath];
    return commonCell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOForumTopicEntity *entity = self.datasArray[indexPath.row];
    if (entity.backEnd || entity.bestTopic || ![[self class] isBlankString:entity.top]) {
        return 60;
    }
    //10 表示控件间隙、60 表示content  Y  150 表示图片背景框高度
    CGFloat height = entity.contentHeight + entity.titleHeight + 80 + 10;
    if (entity.attachments.count) {
        height += 150+10;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ForumItemDetailViewController *postDetail = [ForumItemDetailViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
    CustomTOForumTopicEntity *entity = self.datasArray[indexPath.row];
    postDetail.topicDetail = entity;
    postDetail.category = self.category;
    postDetail.indexPath = indexPath;
    entity.isRead = YES;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    WS(weakSelf);
    //更新点赞数、评论数
    [postDetail setRefreshBlock:^(NSInteger count,COMMENT_PRAISE type,NSIndexPath *indexPath){
        switch (type) {
            case Comment:
            {
                entity.replyCount += count;
            }
                break;
            case Praise:
            {
                entity.likeCount += count;
                entity.canLike = (count == 1)?NO:YES;
            }
                break;
                
            default:
                break;
        }
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    //删除帖子
    [postDetail setDelectBlock:^(NSString *topicId) {
        for (int i=0; i<weakSelf.datasArray.count; i++) {
            CustomTOForumTopicEntity *entity = self.datasArray[i];
            if ([entity.fid isEqualToString:topicId]) {
                [weakSelf.tableView.mj_header beginRefreshing];
            }
        }
    }];
    [self readTopic:entity.fid finish:^{
        [weakSelf pushViewController:postDetail animated:YES];
    }];
}

#pragma mark -设置普通帖子
- (void)configCommonCellAction:(ForumItemTableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    [cell refreshCell:indexPath withTopicEntity:self.datasArray[indexPath.row] withDelegate:self];
}

#pragma mark 设置带标签的帖子
- (void)configTagCellAction:(CommentTagTableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    cell.topicModel = self.datasArray[indexPath.item];
}

#pragma mark - 单击查看大图<TapClickImageViewDelegate>
- (void)tapImageViewWithIndex:(NSInteger)index withCellIndex:(NSIndexPath *)indexPath
{
    [self.selecteImageArray removeAllObjects];
    CustomTOForumTopicEntity *topicEntity = self.datasArray[indexPath.row];
    for (TOAttachmentEntity *entity in topicEntity.attachments) {
        MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:entity.fileUrl]];
        [self.selecteImageArray addObject:photo];
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    [browser setCurrentPhotoIndex:index];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:browser];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - <MWPhotoBrowserDelegate>
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.selecteImageArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.selecteImageArray.count)
        return [self.selecteImageArray objectAtIndex_opple:index];
    return nil;
}

@end
