//
//  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,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,TapClickImageViewDelegate,MWPhotoBrowserDelegate>

@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 = ZERO;
        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 setUpRefreshAction];
    [self uiConfigAction];
}

#pragma mark - 设置刷新
- (void)setUpRefreshAction
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        weakSelf.condition.page.page = ONE;
        [weakSelf.classificationListTableView.mj_footer resetNoMoreData];
        [weakSelf getClassificationList:weakSelf.condition isRemoveArray:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.classificationListTableView.mj_header =headerRefresh;
    [self.classificationListTableView.mj_header beginRefreshing];
    self.classificationListTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (++ weakSelf.condition.page.page > weakSelf.condition.page.total) {
            [weakSelf.classificationListTableView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getClassificationList:weakSelf.condition isRemoveArray:NO];
        }
    }];
    self.classificationListTableView.mj_footer.automaticallyHidden = YES;
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.classificationListTableView.backgroundColor = RGB(237, 238, 239, 1);
    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.category.name isEqualToString:@"欧普问问"] || self.isPosting) {
        self.postingButton.hidden = YES;
    }
}

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

#pragma mark - 发帖
- (IBAction)releaseButtonClickAction:(UIButton *)sender {
    
    ReleasePostViewController *releaseVc = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"ReleasePostViewController"];
    releaseVc.category = self.category;
    WS(weakSelf);
    [releaseVc setFinishBlock:^{
        [weakSelf.classificationListTableView.mj_header beginRefreshing];
    }];
    [self.navigationController 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 = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"ForumItemDetailViewController"];
    CustomTOForumTopicEntity *entity = self.datasArray[indexPath.row];
    postDetail.topicDetail = entity;
    postDetail.category = self.category;
    postDetail.indexPath = indexPath;
    entity.isRead = YES;
    [self.classificationListTableView 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.classificationListTableView.mj_header beginRefreshing];
            }
        }
    }];
    [self.navigationController 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:index];
    return nil;
}

#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}

@end
