//
//  GMMeViewController.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/5.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "GMMeController.h"
#import "ALMeCollectionHeader.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 "ALMeSettingsController.h"
#import "ALFaceFittingViewController.h"
#import "ALScanFaceHomeViewController.h"

@interface GMMeController ()<ALMeCollectionHeaderDelegate, 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 GMMeController
@synthesize viewModel;

- (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:[GMLoginManager shareInstance].user.userId];
    self.pageName = @"personal_home";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(@available(iOS 11.0, *)) {
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self hideNavigationBar];

    [GMHudModule showLoading:nil];
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.collectionView.backgroundColor = UIColor.background;
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_collectionView registerClass:[ALMeCollectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ALMeCollectionHeader 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(refreshInfoMethod) name:LOGIN_SUCCESS_NOTIFICATION object:nil];
    
    /**
     增加这个逻辑的目的是因为在切换账号的时候此控制器会被移除，所以利用登录成功的通知这个控制器也不会接收到通知
     但是self.userId还会存在，然后[GMLoginManager shareInstance].user.userId并不会在此控制器的生命周期
     方法执行完成的时候一定存在，所以要执行以下延时方法，此处后期会进行优化
     */
    NSLog(@"-------%ld",[GMLoginManager shareInstance].user.userId);
//    if (self.userId && ([GMLoginManager shareInstance].user.userId == 0))
//    {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//            if (self.userId != [GMLoginManager shareInstance].user.userId)
//            {
//                self.userId = [GMLoginManager shareInstance].user.userId;
//                self.viewModel.userId = [GMLoginManager shareInstance].user.userId;
//                [self refreshList];
//            }
//        });
//    }
//    else
//    {
        [self.viewModel fetchRemoteData];
//    }
}

- (void)refreshInfoMethod
{
//    NSLog(@"~~~%ld",[GMLoginManager shareInstance].user.userId);
//    NSLog(@"---%ld",self.userId);
    //    if (self.userId != [GMLoginManager shareInstance].user.userId)
    //    {
    [GMHudModule showLoading:nil];
    self.collectionView.hidden = YES;
    self.userId = [GMLoginManager shareInstance].user.userId;
    self.viewModel.userId = [GMLoginManager shareInstance].user.userId;
    [self refreshList];
    //    }
}
#pragma mark - cust delegate
- (void)updateOtherUIData
{
    [super updateOtherUIData];
    [GMHudModule hideLoading];
    self.collectionView.hidden = NO;
}

- (void)refreshHeaderViewMethod
{
    self.viewModel.contentObject.userInfo.isBindPhone = YES;
    [self.collectionView reloadData];
}
//点击设置按钮
- (void)clickSetBtnMethod
{
    [Phobos track:@"personal_home_click_more" attributes:@{@"business_id":@([GMLoginManager shareInstance].user.userId)}];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    [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 {
    //从缓存中获取 Headercell
    ALMeCollectionHeader *cell = (ALMeCollectionHeader *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ALMeCollectionHeader class]) forIndexPath:indexPath];
    cell.delegate = self;
    cell.modelObject = self.viewModel.contentObject;
    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 [ALMeCollectionHeader 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
