//
//  ALHomeSearchVController.m
//  GMAlpha
//
//  Created by zhb on 2018/11/28.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALHomeSearchVController.h"
#import "ALSearchBarView.h"
#import "ALHomeTopicCardCell.h"
#import "ALHomeOperationCardCell.h"
#import "ALHomePortiraitCardCell.h"
#import "NSAttributedString+Frame.h"
#import "ALWaterFlowLayout.h"
#import "ALFaceFittingViewController.h"
#import "ALScanFaceHomeViewController.h"



@interface ALHomeSearchVController ()<ALWaterFlowLayoutDelegate, ALSearchBarViewDelegate, ALHomeTopicCardCellDelegate, ALHomeOperationCardCellDelegate, ALHomePortiraitCardCellDelegate>
@property (nonatomic, strong) ALWaterFlowLayout *waterLayout;
@property (nonatomic, strong) ALSearchBarView *searchView;


/** 用户搜索词 */
@property (nonatomic, copy) NSString *searchString;
@end


@implementation ALHomeSearchVController
@synthesize viewModel;

#pragma mark - life cycle
- (void)initController{
    [super initController];
    self.viewModel = [[ALHomeSearchViewModel alloc] init];
    _needHeaderRefresh = YES;
    _needFooterRefresh = YES;
    self.immediateLoad = NO;
    self.pageName = @"search_detail";    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor= RGBCOLOR_HEX(0xF4F3F8);
    self.navigationBar.hidden = YES;
    
    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.view addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_offset(0);
        make.height.mas_equalTo(OCNavigationBar.barHeight);
    }];
    
    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(OCNavigationBar.barHeight);
        make.left.right.bottom.mas_offset(0);
    }];
}

#pragma mark - collectionView 数据源/代理
- (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) {
            imageH = (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;
        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 - ALSearchBarView.delegate
/** delegate : 返回 */
- (void)searchViewDidBack:(ALSearchBarView *)searchView {    
    [self.navigationController popViewControllerAnimated:YES];
}

/** delegate : 搜索及退下键盘 */
- (void)searchView:(ALSearchBarView *)searchView searchString:(NSString *)searchString {
    [Phobos track:@"search_detail_click_hunt" attributes:@{@"query":searchString}];
    self.searchString = searchString;
    [self.viewModel fetchRemoteDataWithSearchString:searchString];
}
#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 *businessId = [NSString stringWithFormat:@"%zd", topicObj.topicId];
    [Phobos track:@"on_click_feed_topic_card" attributes:@{@"page_name":self.pageName,
                                                           @"position":@(cell.indexPath.row),
                                                           @"click_position":@"bottom",
                                                           @"business_id":businessId,
                                                           @"type":topicObj.portrait.type,
                                                           }];
    
    NSString *url = topicObj.portrait.url;
    [self pushScheme:url];
}

/** delegate : 帖子信息 */
- (void)homeTopicCardCellClickedTopic:(ALHomeTopicCardCell *)cell {
    
    ALHomeCardsObject *cardObj = self.viewModel.dataArray[cell.indexPath.row];
    NSString *businessId = [NSString stringWithFormat:@"%zd", cardObj.topic.topicId];

    [Phobos track:@"on_click_feed_topic_card" attributes:@{@"page_name":self.pageName,
                                                           @"position":@(cell.indexPath.row),
                                                           @"click_position":@"top",
                                                           @"business_id":businessId,
                                                           @"type":cardObj.topic.portrait.type
                                                               }];
    ALHomeTopicCardObject *topicObj = [cardObj topic];
    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 *operationObj = cardObj.operationCard;
    NSString *url = operationObj.url;
    [self pushScheme:url];
}

#pragma mark - 人脸拟合Cell.delegate
/** portiratieCardCell.delegate */
- (void)portiratieCardCellDidSelected:(ALHomePortiraitCardCell *)cell {
    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 == nil) {
        _waterLayout = [[ALWaterFlowLayout alloc] initWithDelegate:self];
    }
    return _waterLayout;
}

- (ALSearchBarView *)searchView {
    if (!_searchView) {
        _searchView = [[ALSearchBarView alloc] init];
        _searchView.delegate = self;
    }
    return _searchView;
}

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


@end
