//
//  ALHomeFollowController.m
//  GMAlpha
//
//  Created by zhb on 2018/11/9.
//  Copyright © 2018 Gengmei. All rights reserved.
//
//  首页.关注Vc


#import "ALHomeFollowController.h"
#import "ALHomeTopicCardCell.h"
#import "ALHomeOperationCardCell.h"
#import "ALHomePortiraitCardCell.h"
#import "NSAttributedString+Frame.h"
#import "ALFaceFittingViewController.h"
#import "ALWaterFlowLayout.h"
#import "ALScanManager.h"
#import "ALScanFaceHomeViewController.h"

@interface ALHomeFollowController ()<ALWaterFlowLayoutDelegate, ALHomeTopicCardCellDelegate, ALHomeOperationCardCellDelegate, ALHomePortiraitCardCellDelegate>
/** 请求接口时的参数, 1是推荐,2是关注*/
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) ALWaterFlowLayout *waterLayout;
@end

@implementation ALHomeFollowController
@synthesize viewModel;

#pragma mark - life cycle
- (void)initController{
    [super initController];
    self.viewModel = [[ALHomeFollowViewModel alloc] init];
    self.type = 2;
    self.immediateLoad = NO;
    self.pageName = @"home";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showLoading:nil];
    self.needLogPV = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationActionUserLogin) name:LOGIN_SUCCESS_NOTIFICATION object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationActionUserLogout) name:LOGOUT_NOTIFICATION object:nil];
    self.collectionView.backgroundColor = UIColor.background;
    [self.collectionView registerClass:[ALHomeTopicCardCell class] forCellWithReuseIdentifier:NSStringFromClass([ALHomeTopicCardCell class])];
    
    [self.collectionView registerClass:[ALHomePortiraitCardCell class] forCellWithReuseIdentifier:NSStringFromClass([ALHomePortiraitCardCell class])];
    
    [self.collectionView registerClass:[ALHomeOperationCardCell class] forCellWithReuseIdentifier:NSStringFromClass([ALHomeOperationCardCell class])];
    
    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    [self hideLoading];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.viewModel.dataArray.count <= 0) {
        [self.viewModel fetchRemoteData];
    }
}

/** 通知 : 用户登录成功 */
- (void)notificationActionUserLogin {
    [self.viewModel handleHeaderRefreshing];
}

/** 通知 : 用户退出登录 */
- (void)notificationActionUserLogout {
    [self.viewModel handleHeaderRefreshing];
}
/** 下拉刷新 */
- (void)headerRereshing
{
//    [Phobos track:@"refresh_page" attributes:@{@"page_name":self.pageName,
//                                               @"tab_name":@"focus"
//                                               }];
    [super headerRereshing];
}
/** 上拉加载 */
- (void)footerRereshing
{
//    [Phobos track:@"upload_page" attributes:@{@"page_name":self.pageName,
//                                              @"tab_name":@"focus"
//                                              }];
    [super footerRereshing];
}

#pragma mark - system dataSource and delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.viewModel.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *reuseId = [self cellIdentifierAtIndexPath:indexPath];
    GMCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseId forIndexPath:indexPath];
    [self configDataForCell:cell atIndexPath:indexPath];
    return cell;
}

#pragma mark -  ALWaterFlowLayoutDelegate
/** rowHeight */
- (CGFloat)waterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout rowHeightAtIndexPath:(NSIndexPath *)indexPath {
    ALHomeCardsObject *obj = [self cardObjectAtIndexPath:indexPath];
    CGFloat cellW = waterFlowLayout.itemWidth;
    if (obj.type == 1) {
        if (obj.portraitCard.image.url.length > 0) {
            return (cellW * ceil(420 / 346));
        }else {
            return 0;
        }
    }
    else if (obj.type == 2) {
        if (obj.operationCard.image.url.length > 0) {
            return cellW;
        }else {
            return 0;
        }
    }
    else {
        CGFloat textMaxW = (cellW-[ALHomeTopicCardCell textLeftMargin] -[ALHomeTopicCardCell textRightMargin]);
        CGFloat imageH = 0;
        if ((obj.topic.image.width) < 1) {
            return 0;
        }
        imageH = ceilf((cellW * (obj.topic.image.height) / (obj.topic.image.width)));
        CGFloat textMargin = [ALHomeTopicCardCell textTopMargin];
        CGFloat lineMargin = [ALHomeTopicCardCell lineTopMargin];
        CGFloat lineH = [ALHomeTopicCardCell lineHeight];
        CGFloat userAreaH = [ALHomeTopicCardCell groupHeight];
        if (obj.topic.attrContent == nil) {
            return imageH + userAreaH;
        }
        CGFloat textH = [obj.topic.attrContent sizeForBoundingRectSize:CGSizeMake(textMaxW, 34)].height;
        CGFloat result = imageH + textMargin + textH + lineMargin + lineH + userAreaH + 10;
        return result;
    }
}
/** 头视图Size */
-(CGSize )waterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout sizeForHeaderViewInSection:(NSInteger)section {
    return CGSizeZero;
}
/** 脚视图Size */
-(CGSize )waterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout sizeForFooterViewInSection:(NSInteger)section {
    return CGSizeZero;
}
/** 列数*/
-(CGFloat)columnCountInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 2;
}
/** 列间距*/
-(CGFloat)columnMarginInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 10;
}
/** 行间距*/
-(CGFloat)rowMarginInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 10;
}
/** 边缘之间的间距*/
-(UIEdgeInsets)edgeInsetInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark - ALHomeTopicCardCellDelegate
/** topicCell.delegate : 点赞 */
- (void)homeTopicCardCellDidVote:(ALHomeTopicCardCell *)cell voteString:(NSString *)voteString{
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    [Phobos track:@"on_click_feed_topic_card_vote" attributes:@{@"page_name":self.pageName,
                                                                @"position":@(cell.indexPath.row),
                                                                @"tab_name":@"focus",
                                                                @"type":cardObj.topic.portrait.type,
                                                                @"vote":voteString,
                                                                @"business_id":@(cardObj.topic.topicId)
                                                                }];
}

/** topicCell.delegate : 作者 或 组信息 */
- (void)homeTopicCardCellClickedPortirait:(ALHomeTopicCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeTopicCardObject *obj = [cardObj topic];
    
    [Phobos track:@"on_click_feed_topic_card" attributes:@{@"page_name":self.pageName,
                                                           @"position":@(cell.indexPath.row),
                                                           @"tab_name":@"focus",
                                                           @"type":cardObj.topic.portrait.type,
                                                           @"click_position":@"bottom",
                                                           @"business_id":@(obj.topicId)
                                                           }];
    
    NSString *url = obj.portrait.url;
    [self pushScheme:url];
}

/** topicCell.delegate : 帖子信息 */
- (void)homeTopicCardCellClickedTopic:(ALHomeTopicCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeTopicCardObject *topicObj = [cardObj topic];
    
    [Phobos track:@"on_click_feed_topic_card" attributes:@{@"page_name":self.pageName,
                                                           @"position":@(cell.indexPath.row),
                                                           @"tab_name":@"focus",
                                                           @"type":cardObj.topic.portrait.type,
                                                           @"click_position":@"top",
                                                           @"business_id":@(topicObj.topicId)
                                                           }];
    
    NSString *url = topicObj.url;
    [self pushScheme:url];
}

#pragma mark - 运营位Cell.delegate
/** operationCardCell.delegate : 点击了图片 */
- (void)operationCardCellDidSelected:(ALHomeOperationCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeOperationObject *obj = cardObj.operationCard;
    
    [Phobos track:@"on_click_pick_card" attributes:@{@"page_name":self.pageName,
                                                     @"position":@(cell.indexPath.row),
                                                     @"tab_name":@"focus",
                                                     @"business_id":@(0)
                                                     }];
    
    NSString *url = obj.url;
    [self pushScheme:url];
}

#pragma mark - 人脸拟合Cell.delegate
/** portiratieCardCell.delegate */
- (void)portiratieCardCellDidSelected:(ALHomePortiraitCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomePortiraitObject *obj = cardObj.portraitCard;
    [Phobos track:@"on_click_fit_card" attributes:@{@"page_name":self.pageName,
                                                    @"position":@(cell.indexPath.row),
                                                    @"tab_name":@"focus",
                                                    @"business_id":@(0)
                                                    }];
    
    if (ALScanManager.shareInstance.show3DInfo || ALScanManager.shareInstance.show2DPathInfo) {
        [self pushViewController:[ALFaceFittingViewController new]];
    } else {
        [self pushViewController:[ALScanFaceHomeViewController new]];
    }
}


#pragma mark - private methods
- (NSString *)cellIdentifierAtIndexPath:(NSIndexPath *)indexPath {
    ALHomeCardsObject *obj = [self cardObjectAtIndexPath:indexPath];
    if (obj.type == 1) {
        return NSStringFromClass([ALHomePortiraitCardCell class]);
    }
    else if (obj.type == 2) {
        return NSStringFromClass([ALHomeOperationCardCell class]);
    }
    else {
        return NSStringFromClass([ALHomeTopicCardCell class]);
    }
}

- (ALHomeCardsObject *)cardObjectAtIndexPath:(NSIndexPath *)indexPath {
    return (self.viewModel.dataArray[indexPath.row]);
}

- (void)configDataForCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    ALHomeCardsObject *obj = [self cardObjectAtIndexPath:indexPath];
    if (obj.type == 1) {
        ALHomePortiraitCardCell *tempCell = (ALHomePortiraitCardCell *)cell;
        tempCell.indexPath = indexPath;
        tempCell.delegate = self;
        tempCell.cardObj = obj.portraitCard;
    }
    else if (obj.type == 2) {
        ALHomeOperationCardCell *tempCell = (ALHomeOperationCardCell *)cell;
        tempCell.indexPath = indexPath;
        tempCell.delegate = self;
        tempCell.cardObj = obj.operationCard;
    }
    else {
        ALHomeTopicCardCell *tempCell = (ALHomeTopicCardCell *)cell;
        tempCell.indexPath = indexPath;
        tempCell.delegate = self;
        tempCell.cardObj = obj.topic;
    }
}


#pragma mark - getters and setters
- (UICollectionViewLayout *)collectionViewLayout {
    _collectionViewLayout = self.waterLayout;
    return _collectionViewLayout;
}

- (ALWaterFlowLayout *)waterLayout {
    if (!_waterLayout) {
        _waterLayout = [[ALWaterFlowLayout alloc] initWithDelegate:self];
    }
    return _waterLayout;
}

- (ALHomeFollowViewModel *)viewModel {
    if (_viewModel == nil) {
        _viewModel = [[ALHomeFollowViewModel alloc] init];
    }
    return _viewModel;
}
@end
