//
//  ALPersonViewController.m
//  GMAlpha
//
//  Created by zhouLiang on 2018/12/4.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALPersonViewController.h"
#import "ALPersonCollectionHeader.h"
#import "ALMyCenterViewModel.h"
#import "ALMyCenterObject.h"
#import "ALHomeTopicCardCell.h"
#import "ALHomeOperationCardCell.h"
#import "ALHomePortiraitCardCell.h"
#import "NSAttributedString+Frame.h"
#import "ALHomeCardsObject.h"
#import "ALWaterFlowLayout.h"
#import "ALHomeCardsObject.h"
#import "ALFaceSDK.h"
#import "ALFaceFittingViewController.h"
#import "ALScanFaceHomeViewController.h"

@interface ALPersonViewController ()<ALPersonCollectionHeaderDelegate, ALHomeTopicCardCellDelegate, ALWaterFlowLayoutDelegate, ALHomePortiraitCardCellDelegate, ALHomeOperationCardCellDelegate>
@property (nonatomic, strong) GMView *headerView;
@property (nonatomic, strong) ALMyCenterViewModel *viewModel;
@property (nonatomic, strong) ALWaterFlowLayout *waterLayout;
@property (nonatomic, strong) ALFaceSDK *faceSDK;

@end

@implementation ALPersonViewController
@synthesize viewModel;

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

- (instancetype)initWithUserId:(NSInteger)userId
{
    if(self = [super init]){
        self.userId = userId;
        [self initController];
    }
    return self;
}

- (void)initController {
    [super initController];
    self.immediateLoad = NO;
    self.viewModel = [[ALMyCenterViewModel alloc]initWithUserId:self.userId];
    self.pageName = @"other_person_home";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    if(@available(iOS 11.0, *)) {
//        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }
//
    [GMHudModule showLoading:nil];
    self.navigationBar.isShowShadow = NO;
    self.view.backgroundColor = UIColor.whiteColor;
    self.collectionView.backgroundColor = UIColor.background;
    [_collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(OCNavigationBar.barHeight);
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    [_collectionView registerClass:[ALPersonCollectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ALPersonCollectionHeader class])];

    [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.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelFollowMethod) name:CANCEL_FOLLOW_NAME object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAttentionMethod:) name:OTHERPERSON_ATTENTION_PERSON object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickPersonAvatarMethod:) name:OTHERPERSON_CLICK_PERSONAVATAR object:nil];
    
    [self.viewModel fetchRemoteData];

}


#pragma mark - cust delegate

- (void)updateOtherUIData
{
    [super updateOtherUIData];
    self.collectionView.hidden = NO;
    [GMHudModule hideLoading];
    [self hideLoading];
}

//取消关注的更新
- (void)cancelFollowMethod
{
    [self showLoading:nil];
    [self.viewModel fetchRemoteData];
}
//点击下面关注按钮
- (void)addAttentionMethod:(NSNotification *)notification
{
    NSString *strId = notification.object;
    
    [Phobos track:@"other_person_home_click_attention_recommend_person" attributes:@{@"person_id":@(self.userId),
                                                                                     @"attention_recommend_person_ids":strId
                                                                                     }];
}
//点击头像的通知方法
- (void)clickPersonAvatarMethod:(NSNotification *)notific
{
    NSString *userId = notific.object;
    [Phobos track:@"other_person_home_click_recommend_person_avatar" attributes:@{@"person_id":@(self.userId),
                                                                                  @"recommend_person_id":userId
                                                                                  }];
}
//关注的更新
- (void)refreshHeaderViewMethod
{
    [Phobos track:@"other_person_home_click_attention" attributes:@{@"person_id":@(self.userId)}];
    [self showLoading:nil];
    [self.viewModel fetchRemoteData];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    self.title = self.viewModel.contentObject.userInfo.name;
    [self hideEmptyView];
}
#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;
}

//这个也是最重要的方法 获取Header的 方法。
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    //    if(kind == UICollectionElementKindSectionHeader)
    //    {
    //从缓存中获取 Headercell
    ALPersonCollectionHeader *cell = (ALPersonCollectionHeader *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ALPersonCollectionHeader class]) forIndexPath:indexPath];
    cell.delegate = self;
    cell.modelObject = self.viewModel.contentObject;
    return cell;
    //    }
    //    else{
    //        ALMeCollectionFootterView *cell = (ALMeCollectionFootterView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([ALMeCollectionFootterView class]) forIndexPath: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;
        CGFloat imageTH = obj.topic.image.width;
        if (imageTH > 1) {
            imageH = cellW * (obj.topic.image.height) / imageTH;
        }
        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;
        return result;
    }
}
/** 头视图Size */
-(CGSize )waterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout sizeForHeaderViewInSection:(NSInteger)section {
    return [ALPersonCollectionHeader headerHeight:self.viewModel.contentObject];
}
/** 脚视图Size */
-(CGSize )waterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout sizeForFooterViewInSection:(NSInteger)section {
    return CGSizeMake(MAINSCREEN_WIDTH, 0);
}
/** 列数*/
-(CGFloat)columnCountInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 2;
}
/** 列间距*/
-(CGFloat)columnMarginInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 10;
}
/** 行间距*/
-(CGFloat)rowMarginInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return 10;
}
/** 边缘之间的间距*/
-(UIEdgeInsets)edgeInsetInWaterFlowLayout:(ALWaterFlowLayout *)waterFlowLayout {
    return UIEdgeInsetsMake(0, 10, 10, 10);
}


#pragma mark - ALHomeTopicCardCellDelegate
/** topicCell.delegate : 点赞 */
- (void)homeTopicCardCellDidVote:(ALHomeTopicCardCell *)cell voteString:(NSString *)voteString{
    
}

/** topicCell.delegate : 作者 或 组信息 */
- (void)homeTopicCardCellClickedPortirait:(ALHomeTopicCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeTopicCardObject *topicObj = [cardObj topic];
    NSString *url = topicObj.portrait.url;
    [self pushScheme:url];
}

/** delegate : 帖子信息 */
- (void)homeTopicCardCellClickedTopic:(ALHomeTopicCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeTopicCardObject *topicObj = [cardObj topic];
    NSString *url = topicObj.url;
    [self pushScheme:url];
}
- (void)portiratieCardCellDidSelected:(ALHomePortiraitCardCell *)cell {
    if (ALScanManager.shareInstance.show3DInfo || ALScanManager.shareInstance.show2DPathInfo) {
        [self pushViewController:[ALFaceFittingViewController new]];
    } else {
        [self pushViewController:[ALScanFaceHomeViewController new]];
    }
}

- (void)operationCardCellDidSelected:(ALHomeOperationCardCell *)cell {
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    ALHomeOperationObject *obj = cardObj.operationCard;
    NSString *url = obj.url;
    [self pushScheme:url];
}
#pragma mark - 私有方法
- (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;
    }
}

- (ALFaceSDK *)faceSDK
{
    if(!_faceSDK)
    {
        _faceSDK = [[ALFaceSDK alloc]init];
    }
    return _faceSDK;
}
#pragma mark - setter
- (void)setIsHideNavBar:(BOOL)isHideNavBar {
    if (isHideNavBar == YES) {
        [self hideNavigationBar];
    }
}
#pragma mark - getters
- (UICollectionViewLayout *)collectionViewLayout {
    _collectionViewLayout = self.waterLayout;
    return _collectionViewLayout;
}

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