//
//  SearchAlbumViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/7/8.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "SearchAlbumViewController.h"
#import "SearchBarView.h"
#import "UIView+frameAdjust.h"
#import "UIImageView+WebCache.h"
#import "PYSearchConst.h"
#import "XMSDK.h"

#import "KKListenSubCell.h"
#import "KKListenDetailController.h"
#import "LMHWaterFallLayout.h"

#import "EmptyCollectionViewCell.h"
#import "Recommend2ViewCell.h"



@interface SearchAlbumViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate,LMHWaterFallLayoutDeleaget,UICollectionViewDataSource>
{
    UILabel*searchLabel;
}


@property (nonatomic, strong)NSMutableArray* dataArray;

@property (nonatomic, strong)NSMutableArray* recommentDataArray;


@property (nonatomic, strong)SearchBarView* searchView;

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UICollectionView* collectionView;




@property (nonatomic, strong)UIView* headerView;

/**
 The label of popular search header
 */
@property (nonatomic, weak) UILabel *hotSearchHeader;

/**
 The view of popular search
 */
@property (nonatomic, weak) UIView *hotSearchView;

/**
 The view of search history
 */
@property (nonatomic, weak) UIView *searchHistoryView;

/**
 The records of search
 */
@property (nonatomic, strong) NSMutableArray *searchHistories;

/**
 The content view of popular search tags
 */
@property (nonatomic, weak) UIView *hotSearchTagsContentView;

@property (nonatomic, strong)UIView* footerView;


/**
 The label of search history header
 */
@property (nonatomic, weak) UILabel *searchHistoryHeader;






@end

@implementation SearchAlbumViewController
- (instancetype)init
{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
    [self.navigationController setNavigationBarHidden:YES];
    
    self.searchView.textField.placeholder = self.placeString;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar navBarAlpha:1.0 isOpaque:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"读万卷书";
    self.view.backgroundColor = [UIColor whiteColor];
    //[self navConfig];
    SearchBarView* searchView =  [[NSBundle mainBundle]loadNibNamed:@"SearchBarView" owner:nil options:nil].lastObject;
    searchView.frame = CGRectMake(0, cl_kStatusBarHeight, ScreenWidth, 40);
    [searchView.backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView.searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.searchView = searchView;
    self.searchView.textField.delegate = self;
    [self.view addSubview:searchView];
    

    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    WeakSelf
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf loadData];
    }];
    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        
        //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];

    
    [self.searchView.textField becomeFirstResponder];
    
    
    
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@0 forKey:@"category_id"];
    [params setObject:@20 forKey:@"count"];
    [params setObject:@1 forKey:@"page"];
    [params setObject:self.searchView.textField.text forKey:@"q"];
    
    WeakSelf
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_SearchAlbums params:params
    withCompletionHander:^(id result, XMErrorModel *error) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.tableView.mj_header endRefreshing];
        [strongSelf.dataArray removeAllObjects];
        NSArray* array  = [strongSelf showReceivedData:result className:@"XMAlbum" valuePath:@"albums"
    titleNeedShow:@"albumTitle"];
        
        for (XMAlbum*album in array) {
            [strongSelf.dataArray addObject:album];
        }
        
        strongSelf.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];;
        [strongSelf.tableView reloadData];
        
        if (strongSelf.dataArray.count == 0) {
            [strongSelf.recommentDataArray removeAllObjects];
            if (!self.collectionView.superview) {
                [strongSelf.view addSubview:strongSelf.collectionView];
            }
            
            [strongSelf getXMLYTuiJianRequest];
        }
    }];
    
    
}



- (NSDictionary *)getXMLYTuiJianRequestPara
{
    NSDictionary* params = @{
        @"is_paid":@0,
        @"count":@100
    };
    return params;
}
- (void)getXMLYTuiJianRequest
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipBackUrlConfig],XMLYTuiJianRequest];
    WeakSelf
    [NetworkRequest Get4:url Params:[self getXMLYTuiJianRequestPara] Success:^(id _Nonnull objc) {
         __strong typeof(self) strongSelf = weakSelf;
        strongSelf.recommentDataArray = [strongSelf showReceivedData:objc className:@"XMAlbum" valuePath:@"albums" titleNeedShow:@"albumTitle"];
        [strongSelf.collectionView reloadData];
        
        
    } Failure:^(NSError* error) {
        
    }];
    
}


- (NSMutableArray *)showReceivedData:(id)result className:(NSString*)className valuePath:(NSString *)path titleNeedShow:(NSString*)title
{
    NSMutableArray *models = [NSMutableArray array];
    Class dataClass = NSClassFromString(className);
    if([result isKindOfClass:[NSArray class]]){
        for (NSDictionary *dic in result) {
            id model = [[dataClass alloc] initWithDictionary:dic];
            [models addObject:model];
        }
    }
    else if([result isKindOfClass:[NSDictionary class]]){
        if(path.length == 0)
        {
            id model = [[dataClass alloc] initWithDictionary:result];
            [models addObject:model];
        }
        else
        {
            NSArray *paths = [path componentsSeparatedByString:@"."];
            
//            NSLog(@"paths have %lu objects inside", (unsigned long)[paths count]);
//            NSLog(@"paths last object is %@", paths.lastObject);
            
            NSDictionary *dic = result;
            for (int i=0;i<paths.count-1;i++)
            {
                NSString *subPath = paths[i];
                dic = dic[subPath];
            }
            for (NSDictionary *dict in dic[paths.lastObject])
            {
                id model = [[dataClass alloc] initWithDictionary:dict];
                [models addObject:model];
                
            }
        }
    }
    
    return models;
}


- (void)navConfig
{
    [self.navigationController setNavigationBarHidden:YES];
    
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navView];
    
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 30, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"backItemImage"] forState:UIControlStateNormal];
    //    [button_2 setBackgroundColor:[UIColor redColor]];
    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    
    
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor colorWithHex:0x333333];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
    
    
    
    
}

- (void)setup
{
    
    
    /**
    * Initialize settings
    */
    self.searchHistoriesCount = 20;
    self.searchHistoriesCachePath = PYSEARCH_SEARCH_HISTORY_CACHE_PATH;
    self.removeSpaceOnSearchString = YES;
    self.showSearchHistory = YES;
    self.dataArray = [NSMutableArray array];
    
    
    UIView *headerView = [[UIView alloc] init];
    headerView.width = ScreenWidth;
    headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UIView *hotSearchView = [[UIView alloc] init];
    hotSearchView.x = PYSEARCH_MARGIN * 1.5;
    hotSearchView.width = headerView.width - hotSearchView.x * 2;
    hotSearchView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UILabel *titleLabel = [self setupTitleLabel:@"推荐搜索"];
    self.hotSearchHeader = titleLabel;
    [hotSearchView addSubview:titleLabel];
    UIView *hotSearchTagsContentView = [[UIView alloc] init];
    hotSearchTagsContentView.width = hotSearchView.width;
    hotSearchTagsContentView.y = CGRectGetMaxY(titleLabel.frame) + PYSEARCH_MARGIN;
    hotSearchTagsContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [hotSearchView addSubview:hotSearchTagsContentView];
    [headerView addSubview:hotSearchView];
    self.hotSearchTagsContentView = hotSearchTagsContentView;
    self.hotSearchView = hotSearchView;
    self.headerView = headerView;
    
    self.tableView.tableHeaderView = headerView;
}


- (void)setupHotSearchNormalTags
{
    self.hotSearchTags = [self addAndLayoutTagsWithTagsContentView:self.hotSearchTagsContentView tagTexts:self.hotSearches];
    //[self setHotSearchStyle:self.hotSearchStyle];
}

- (NSArray *)addAndLayoutTagsWithTagsContentView:(UIView *)contentView tagTexts:(NSArray<NSString *> *)tagTexts
{
    [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSMutableArray *tagsM = [NSMutableArray array];
    for (int i = 0; i < tagTexts.count; i++) {
        UILabel *label = [self labelWithTitle:tagTexts[i]];
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagDidCLick:)]];
        [contentView addSubview:label];
        [tagsM addObject:label];
    }
    
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat countRow = 0;
    CGFloat countCol = 0;
    
    for (int i = 0; i < contentView.subviews.count; i++) {
        UILabel *subView = contentView.subviews[i];
        
        if (subView.width > contentView.width) subView.width = contentView.width;
        if (currentX + subView.width + PYSEARCH_MARGIN * countRow > contentView.width) {
            subView.x = 0;
            subView.y = (currentY += subView.height) + PYSEARCH_MARGIN * ++countCol;
            currentX = subView.width;
            countRow = 1;
        } else {
            subView.x = (currentX += subView.width) - subView.width + PYSEARCH_MARGIN * countRow;
            subView.y = currentY + PYSEARCH_MARGIN * countCol;
            countRow ++;
        }
    }
    
    contentView.height = CGRectGetMaxY(contentView.subviews.lastObject.frame);
    if (self.hotSearchTagsContentView == contentView) {
        self.hotSearchView.height = CGRectGetMaxY(contentView.frame) + PYSEARCH_MARGIN * 2;
    }else if (self.searchHistoryTagsContentView == contentView) { // search history tag
        self.searchHistoryView.height = CGRectGetMaxY(contentView.frame) + PYSEARCH_MARGIN * 2;
    }
    
    [self layoutForDemand];
    self.tableView.tableHeaderView.height = self.headerView.height = MAX(CGRectGetMaxY(self.hotSearchView.frame), CGRectGetMaxY(self.searchHistoryView.frame));
    self.tableView.tableHeaderView.hidden = NO;
    
    // Note：When the operating system for the iOS 9.x series tableHeaderView height settings are invalid, you need to reset the tableHeaderView
    [self.tableView setTableHeaderView:self.tableView.tableHeaderView];
    return [tagsM copy];
    
}

- (void)layoutForDemand {
    self.searchHistoryView.y = PYSEARCH_MARGIN * 2;
    
    self.hotSearchView.y = self.searchHistories.count == 0 ? PYSEARCH_MARGIN * 2 : CGRectGetMaxY(self.searchHistoryView.frame);
}



- (UILabel *)setupTitleLabel:(NSString *)title
{
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.tag = 1;
    titleLabel.textColor = RGBCOLOR(113, 113, 113);
    [titleLabel sizeToFit];
    titleLabel.x = 0;
    titleLabel.y = 0;
    return titleLabel;
}

- (UILabel *)labelWithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc] init];
    label.userInteractionEnabled = YES;
    label.font = [UIFont systemFontOfSize:14];
    label.text = title;
    label.textColor = [UIColor grayColor];
    label.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    label.clipsToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    [label sizeToFit];
    label.width += 20;
    label.height += 14;
    label.layer.cornerRadius = label.height/2;
    return label;
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.recommentDataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        EmptyCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        cell.lb_content.text = [NSString stringWithFormat:@"\"%@\"",self.searchView.textField.text];
        searchLabel = cell.lb_content;
        return cell;
    }
    Recommend2ViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    XMAlbum*model = self.recommentDataArray[indexPath.row];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.coverUrlLarge
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumTitle;
    
    cell.lb_count.text = [self getStrWithCount:model.playCount];
    return cell;
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(ScreenWidth, 132);
    }
    XMAlbum*model = self.recommentDataArray[indexPath.row];
    
    CGFloat height = [self getLabelHeightWithText:model.albumTitle width:((ScreenWidth - 40)/2 - 10) font:[UIFont boldSystemFontOfSize:15]];
    if (height > 19) {
         return CGSizeMake((ScreenWidth - 40)/2, (ScreenWidth - 40)/2 + 75);
    }else{
        return CGSizeMake((ScreenWidth - 40)/2, (ScreenWidth - 40)/2 + 57);
    }
    
}

/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return UIEdgeInsetsMake(15, 0, 20, 0);
    }
    return UIEdgeInsetsMake(0, 15, 0, 15);
}


/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.0;
    }
    return 10.0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.0;
    }
    return 10.0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
         XMAlbum*model = self.recommentDataArray[indexPath.row];
        
        KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
        
        detailVC.model = model;
        
        detailVC.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }
}

#pragma mark  - <LMHWaterFallLayoutDeleaget>
- (CGFloat)minYInwaterFallLayout:(LMHWaterFallLayout *)waterFallLayout
{
    return 183;
}
- (CGFloat)waterFallLayout:(LMHWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth{
    
    
    
    XMAlbum*model = self.recommentDataArray[indexPath];
    
    CGFloat height = [self getLabelHeightWithText:model.albumTitle width:((ScreenWidth - 40)/2 - 10) font:[UIFont boldSystemFontOfSize:15]];
    if (height > 19) {
         return (ScreenWidth - 40)/2 + 75;
    }else{
        return (ScreenWidth - 40)/2 + 57;
    }
}

- (CGFloat)rowMarginInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout{
    
    return 10;
    
}

- (CGFloat)columnMarginInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout
{
    return 10;
}

- (NSUInteger)columnCountInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout{
    
    return 2;
    
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.showSearchHistory ? 0 : self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     KKListenSubCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
     XMAlbum*model = self.dataArray[indexPath.section];
       
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.coverUrlLarge
                                     ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumTitle;
       
    cell.lb_subTitle.text = model.albumIntro;
    cell.lb_count.text = [self getStrWithCount:model.playCount];
       
       return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 106;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMAlbum*model = self.dataArray[indexPath.section];
    
    KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
    
    detailVC.model = model;
    
    detailVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.tableView.tableHeaderView = self.headerView;
    
    self.showSearchHistory = YES;
    [self refreshHistoryData];
    [self.tableView reloadData];
    
    [self.collectionView removeFromSuperview];
    
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [self searchBtnClick:nil];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect frame = CGRectMake(0, cl_kStatusBarHeight + 40, ScreenWidth, ScreenHeight - cl_kStatusBarHeight - 40 );
    self.tableView.frame = frame;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"contentOffset.y:%.2lf",scrollView.contentOffset.y);
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0);
    }
}


#pragma mark - 键盘通知
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;   //height 就是键盘的高度
//    int width = keyboardRect.size.width;     //width  键盘宽度
    
  
    
    CGRect frame = CGRectMake(0, cl_kStatusBarHeight + 40, ScreenWidth, ScreenHeight - cl_kStatusBarHeight - 40 - height);
    self.tableView.frame = frame;
   
}
 
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    
}




#pragma mark - event response
- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBtnClick:(UIButton *)sender
{
    //[self saveSearchCacheAndRefreshView];
    
    
    searchLabel.text = [NSString stringWithFormat:@"\"%@\"",self.searchView.textField.text];
    
    [self.searchView.textField resignFirstResponder];
    UITextField*textField = self.searchView.textField;
    
    NSString *searchText = textField.text;
    
    if (self.removeSpaceOnSearchString) { // remove sapce on search string
        searchText = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    
    if (textField.text.length == 0) {
        textField.text = self.placeString;
    }
    
    if (self.showSearchHistory && searchText.length > 0) {
        [self.searchHistories removeObject:searchText];
        [self.searchHistories insertObject:searchText atIndex:0];
        
        if (self.searchHistories.count > self.searchHistoriesCount) {
            [self.searchHistories removeLastObject];
        }
        [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    }
    self.showSearchHistory = NO;
    
    [self loadData];
}

- (void)emptySearchHistoryDidClick
{
    [self.searchHistories removeAllObjects];
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    
    self.hotSearches = self.hotSearches;
    
    [self refreshHistoryData];
}

- (void)tagDidCLick:(UITapGestureRecognizer *)tap
{
    UILabel*lb = (UILabel *)tap.view;
    
    self.searchView.textField.text = lb.text;
    
    [self searchBtnClick:nil];
}


- (void)saveSearchCacheAndRefreshView
{
    [self.searchView.textField resignFirstResponder];
    UITextField*textField = self.searchView.textField;
    
    NSString *searchText = textField.text;
    if (self.removeSpaceOnSearchString) { // remove sapce on search string
        searchText = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    if (self.showSearchHistory && searchText.length > 0) {
        [self.searchHistories removeObject:searchText];
        [self.searchHistories insertObject:searchText atIndex:0];
        
        if (self.searchHistories.count > self.searchHistoriesCount) {
            [self.searchHistories removeLastObject];
        }
        [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
        
//        if (PYSearchHistoryStyleCell == self.searchHistoryStyle) {
//            [self.baseSearchTableView reloadData];
//        } else {
//            self.searchHistoryStyle = self.searchHistoryStyle;
//        }
    }
    
    //[self handleSearchResultShow];
    [self refreshHistoryData];
    
}


- (void)refreshHistoryData
{
    if (!self.searchHistories.count || !self.showSearchHistory) {
           self.searchHistoryHeader.hidden = YES;
           self.searchHistoryTagsContentView.hidden = YES;
           self.searchHistoryView.hidden = YES;
           self.emptyButton.hidden = YES;
           return;
       };
    self.searchHistoryHeader.hidden = NO;
    self.searchHistoryTagsContentView.hidden = NO;
    self.searchHistoryView.hidden = NO;
    self.emptyButton.hidden = NO;
    [self setupSearchHistoryTags];
}


#pragma mark - private methods
- (NSString *)getStrWithCount:(NSInteger)count
{
    if (count < 10000) {
        return [NSString stringWithFormat:@"%ld",count];
    }else if (count < 100000000&& count>= 10000 ){
        return [NSString stringWithFormat:@"%ld万",count/10000];
    }else{
         return [NSString stringWithFormat:@"%ld亿",count/100000000];
    }
}
//根据文本计算控件宽度
- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font:(UIFont *)font
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size.height;
}


#pragma mark -  setters
- (void)setHotSearches:(NSArray *)hotSearches
{
    _hotSearches = hotSearches;
    [self setupHotSearchNormalTags];
    [self setupSearchHistoryTags];
}

- (void)setHotSearchTags:(NSArray<UILabel *> *)hotSearchTags
{
    // popular search tagLabel's tag is 1, search history tagLabel's tag is 0.
    for (UILabel *tagLabel in hotSearchTags) {
        tagLabel.tag = 1;
    }
    _hotSearchTags = hotSearchTags;
}

- (void)setupSearchHistoryTags
{
    self.tableView.tableFooterView = nil;
    self.searchHistoryTagsContentView.y = PYSEARCH_MARGIN;
    self.emptyButton.y = self.searchHistoryHeader.y - PYSEARCH_MARGIN * 0.5;
    self.searchHistoryTagsContentView.y = CGRectGetMaxY(self.emptyButton.frame) + PYSEARCH_MARGIN;
    self.searchHistoryTags = [self addAndLayoutTagsWithTagsContentView:self.searchHistoryTagsContentView tagTexts:[self.searchHistories copy]];
}

#pragma mark - getters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kStatusBarHeight + 40, ScreenWidth, ScreenHeight - cl_kStatusBarHeight - 40) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.estimatedSectionHeaderHeight = 0.1;
        _tableView.estimatedSectionFooterHeight = 0.1;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        if ([_tableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)]) { // For the adapter iPad 解决ios9 中UITableView 的Cell 自动缩进问题
            _tableView.cellLayoutMarginsFollowReadableWidth = NO;
        }
        [_tableView registerNib:[UINib nibWithNibName:@"KKListenSubCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _scrollView.showsHorizontalScrollIndicator = NO;
        
    }
    return _scrollView;
}


- (UICollectionView *)collectionView
{
    if (!_collectionView) {
//        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
//        fl.scrollDirection = UICollectionViewScrollDirectionVertical;
//        fl.minimumLineSpacing = 10;
//        fl.minimumInteritemSpacing = 10;
        // 创建布局
        LMHWaterFallLayout * waterFallLayout = [[LMHWaterFallLayout alloc]init];
        waterFallLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, cl_kStatusBarHeight + 40, ScreenWidth, ScreenHeight - cl_kStatusBarHeight - 40) collectionViewLayout:waterFallLayout];
        //_collectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        [_collectionView registerNib:[UINib nibWithNibName:@"EmptyCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"Recommend2ViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell2"];
    }
    return _collectionView;
}

- (UIView *)searchHistoryTagsContentView
{
    if (!_searchHistoryTagsContentView) {
        UIView *searchHistoryTagsContentView = [[UIView alloc] init];
        searchHistoryTagsContentView.width = self.searchHistoryView.width;
        searchHistoryTagsContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        searchHistoryTagsContentView.y = CGRectGetMaxY(self.hotSearchTagsContentView.frame) + PYSEARCH_MARGIN;
        [self.searchHistoryView addSubview:searchHistoryTagsContentView];
        _searchHistoryTagsContentView = searchHistoryTagsContentView;
    }
    return _searchHistoryTagsContentView;
}

- (UILabel *)searchHistoryHeader
{
    if (!_searchHistoryHeader) {
        UILabel *titleLabel = [self setupTitleLabel:@"搜索历史"];
        [self.searchHistoryView addSubview:titleLabel];
        _searchHistoryHeader = titleLabel;
    }
    return _searchHistoryHeader;
}

- (UIView *)searchHistoryView
{
    if (!_searchHistoryView) {
        UIView *searchHistoryView = [[UIView alloc] init];
        searchHistoryView.x = self.hotSearchView.x;
        searchHistoryView.y = self.hotSearchView.y;
        searchHistoryView.width = self.headerView.width - searchHistoryView.x * 2;
        searchHistoryView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self.headerView addSubview:searchHistoryView];
        _searchHistoryView = searchHistoryView;
    }
    return _searchHistoryView;
}


- (NSMutableArray *)searchHistories
{
    if (!_searchHistories) {
        _searchHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchHistories;
}

- (UIButton *)emptyButton
{
    if (!_emptyButton) {
        UIButton *emptyButton = [[UIButton alloc] init];
        emptyButton.titleLabel.font = self.searchHistoryHeader.font;
        [emptyButton setImage:[UIImage imageNamed:@"empty"] forState:UIControlStateNormal];
        [emptyButton addTarget:self action:@selector(emptySearchHistoryDidClick) forControlEvents:UIControlEventTouchUpInside];
        [emptyButton sizeToFit];
        emptyButton.width += PYSEARCH_MARGIN;
        emptyButton.height += PYSEARCH_MARGIN;
        emptyButton.centerY = self.searchHistoryHeader.y;
        emptyButton.x = self.searchHistoryView.width - emptyButton.width;
        emptyButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [self.searchHistoryView addSubview:emptyButton];
        _emptyButton = emptyButton;
    }
    return _emptyButton;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
