//
//  SearchTabBaseVC.m
//  smartRhino
//
//  Created by niuzhen on 2020/4/8.
//  Copyright © 2020 tederen. All rights reserved.
//

#import "SearchTabBaseVC.h"
#import "SearchTabCell.h"

@interface SearchTabBaseVC ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) UISearchBar  * searchBar;
@property (strong, nonatomic) UIView  * searchV;
@property (strong, nonatomic) UIButton  * backBtn;
@property (strong, nonatomic) UIView  * navBarV;
@property (strong, nonatomic) UILabel  * lineL;
@property (nonatomic, strong) NSMutableArray * dataDistoryArray;


@end

@implementation SearchTabBaseVC
- (UIView *)noDataView
{
    if (!_noDataView) {
        _noDataView = [UIView new];
        _noDataView.hidden = YES;
        _noDataView.backgroundColor = [UIColor whiteColor];
    }
    return _noDataView;
}
- (UILabel *)noDataL
{
    if (!_noDataL) {
        _noDataL = [UILabel new];
        _noDataL.textColor = UIColorHex(#BBBBBB);
        _noDataL.font = [UIFont systemFontOfSize:15];
    }
    return _noDataL;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton new];
        [_cancelBtn setAttributedTitle:[[NSMutableAttributedString alloc] initWithString:@"取消" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 15],NSForegroundColorAttributeName: UIColorHex(#3979D3)}] forState:UIControlStateNormal];
    }
    return _cancelBtn;
}
- (UIButton *)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton new];
        [_backBtn setImage:IMG(@"back_black_icon") forState:UIControlStateNormal];
    }
    return _backBtn;
}
- (UILabel *)lineL
{
    if (!_lineL) {
        _lineL = [UILabel new];
        _lineL.backgroundColor = LINEBGCOLOR;
    }
    return _lineL;
}
- (UIView *)navBarV
{
    if (!_navBarV) {
        _navBarV = [UIView new];
        _navBarV.backgroundColor = [UIColor whiteColor];
    }
    return _navBarV;
}
- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
    }
    return _searchBar;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
        [_collectionView registerClass:[SearchTabCell class] forCellWithReuseIdentifier:@"SearchTabCellId"];
    }
    return _collectionView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)setHistorySearchType:(HistorySearchType)historySearchType
{
    _historySearchType = historySearchType;
    self.dataDistoryArray = [[_TDFileStorage loadHistorySearchBySearchType:_historySearchType] mutableCopy];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [self setCusView];
    self.collectionView.hidden = NO;
    self.tableView.hidden = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = RGB(255, 255, 255);
    WS(weakSelf);
    [self.backBtn setAction:^{
        if (weakSelf.cancelBtn.isHidden) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else{
            weakSelf.collectionView.hidden = NO;
            weakSelf.noDataView.hidden = YES;
            weakSelf.tableView.hidden = YES;
            [weakSelf upCanCelBtnConstraits];
        }
    }];
    [self.cancelBtn setAction:^{
        weakSelf.searchBar.text = @"";
        weakSelf.collectionView.hidden = NO;
        weakSelf.noDataView.hidden = YES;
        weakSelf.tableView.hidden = YES;
        [weakSelf upCanCelBtnConstraits];
    }];
    [self.searchBar becomeFirstResponder];
}
- (void)setCusView
{
    [self.view addSubview:self.navBarV];
    [self.navBarV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.height.offset(IS_IPHONEX ? 84:64);
    }];
    [self.navBarV addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.mas_equalTo(self.navBarV);
        make.size.mas_offset(CGSizeMake(50, 44));
    }];
    [self.navBarV addSubview:self.cancelBtn];
    [self upCanCelBtnConstraits];
    [self.navBarV addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.backBtn.mas_right);
        make.centerY.mas_equalTo(self.backBtn);
        make.height.mas_offset(32);
        make.right.mas_equalTo(self.cancelBtn.mas_left).offset(-15);
    }];
    [self.navBarV addSubview:self.lineL];
    [self.lineL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.navBarV);
        make.height.mas_offset(0.5);
    }];
    self.searchBar.layer.borderWidth = 0.5f;
    self.searchBar.layer.cornerRadius = 3.f;
    self.searchBar.layer.borderColor = UIColorHex(#CCCCCC).CGColor;
    self.searchBar.layer.masksToBounds = YES;
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.tableView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navBarV.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navBarV.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    [self.view addSubview:self.noDataView];
    self.noDataView.hidden = YES;
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navBarV.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    [self.noDataView addSubview:self.noDataL];
    [self.noDataL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.noDataView);
    }];
    _searchBar.backgroundImage = [UtilsTools imageWithColor:[UIColor clearColor] size:_searchBar.bounds.size];
    
    UIImage* clearImg = [UtilsTools imageWithColor:[UIColor clearColor] andHeight:44.0f];
    [_searchBar setBackgroundImage:clearImg];
    [_searchBar setSearchFieldBackgroundImage:clearImg forState:UIControlStateNormal];
    [_searchBar setBackgroundColor:[UIColor clearColor]];

    [_searchV setBackgroundColor:[UIColor whiteColor]];
    [_searchV setRadius:4 borderColor:RGB(204, 204, 204) borderWidth:.5];
    self.searchBar.delegate = self;

    if ([UIDevice currentDevice].systemVersion.floatValue >= 13.0) {
        self.searchBar.searchTextField.font = [UIFont systemFontOfSize:14.0];
    if (!self.searchBar.searchTextField.placeholder) {
        self.searchBar.searchTextField.placeholder = @"搜索";
        }
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:self.searchBar.searchTextField.placeholder attributes: @{NSForegroundColorAttributeName:RGB(153, 153, 153), NSFontAttributeName:self.searchBar.searchTextField.font}];
        self.searchBar.searchTextField.attributedPlaceholder = attrString;
    }else{
        for (UIView *view in self.searchBar.subviews.lastObject.subviews) {
            if([view isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                UITextField *textField = (UITextField *)view;
                //设置输入框的背景颜色
                textField.clipsToBounds = YES;
                //设置输入字体颜色
                textField.textColor = [UIColor blackColor];
                //设置默认文字颜色
                textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@" 搜索" attributes:@{NSForegroundColorAttributeName:[UIColor hexStringToColor:@"999999"]}];
                textField.font = [UIFont systemFontOfSize:14];
                for (UIView * subView in view.subviews) {
                    if ([subView isKindOfClass:NSClassFromString(@"UIImageView")]) {
                        UIImageView * imageV = (UIImageView *)subView;
                        imageV.image = IMG(@"searchIcon");
                    }
                }
            }
        }
    }
}
- (NSMutableArray *)dataDistoryArray
{
    if (!_dataDistoryArray) {
        _dataDistoryArray = [NSMutableArray array];
    }
    return _dataDistoryArray;
}
/**********************************************************************/
#pragma mark -UICollectionViewDataSource
/**********************************************************************/
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.dataDistoryArray.count == 0) {
        return 0;
    }
    return 1;
}

/**********************************************************************/
#pragma mark -GHRefreshCollectionView的section的Count
/**********************************************************************/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataDistoryArray.count;
}

#pragma mark - UICollectionViewDelegate
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    SearchTabCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchTabCellId" forIndexPath:indexPath];
    cell.titleL.text = [self.dataDistoryArray objectAtIndex:indexPath.row];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    UILabel * label = [UILabel new];
    label.font = [UIFont systemFontOfSize:13];
    label.text = [self.dataDistoryArray objectAtIndex:indexPath.row];
    CGFloat width = [label sizeThatFits:CGSizeMake(SCREEN_WIDTH, 25)].width;
    if (width > SCREEN_WIDTH * 0.7) {
        width = SCREEN_WIDTH * 0.7;
    }
    return CGSizeMake(width + 22, 25);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    [self selectIndexText:[self.dataDistoryArray objectAtIndex:indexPath.row]];
    [self showCancelBtn];
}

//footer的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(0, 0);
}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 44);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 11.f;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 9.f;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView" forIndexPath:indexPath];
        [headerView removeAllSubviews];
        UILabel *label = [[UILabel alloc] init];
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.left.equalTo(@(15));
        }];
        label.text = @"搜索历史";
        label.font = [UIFont systemFontOfSize:16];
        label.textColor = UIColorHex(#333333);
        
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [headerView addSubview:closeBtn];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.right.equalTo(@(-15));
        }];
        [closeBtn setTitle:@"清空" forState:UIControlStateNormal];
        [closeBtn setTitleColor:UIColorHex(#278BDD) forState:UIControlStateNormal];
        closeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        WS(weakSelf);
        [closeBtn setAction:^{
            [weakSelf.dataDistoryArray removeAllObjects];
            [_TDFileStorage saveHistorySearchBySearchType:self.historySearchType WithArr:@[]];
            [weakSelf.collectionView reloadData];
        }];
        headerView.backgroundColor = [UIColor whiteColor];
        return headerView;
    }
    return nil;
}

- (void)selectIndexText:(NSString *)text
{
    self.tableView.hidden = NO;
    self.collectionView.hidden = YES;
    self.searchBar.text = text;
    self.searchText = self.searchBar.text;
}

- (void)checkRepeatString:(NSString *)string {
    for (NSString *cache in self.dataDistoryArray) {
        if ([cache isEqualToString:string]) {
            return;
        }
    }
    [self.dataDistoryArray insertObject:string atIndex:0];
    [_TDFileStorage saveHistorySearchBySearchType:self.historySearchType WithArr:self.dataDistoryArray];
    [self.collectionView reloadData];
}
/**********************************************************************/
#pragma mark - UISearchBarDelegate
/**********************************************************************/
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    if (searchBar.text.length > 0) {
        [self selectIndexText:searchBar.text];
        [self checkRepeatString:searchBar.text];
        [self showCancelBtn];
    }
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

}
- (void)searchBarTextDidBeginEditing:(UISearchBar *) searchBar{
    UITextField *searchBarTextField = nil;
    NSArray *views = ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) ? searchBar.subviews : [[searchBar.subviews objectAtIndex:0] subviews];
    
    for (UIView *subview in views){
        if ([subview isKindOfClass:[UITextField class]]){
            searchBarTextField = (UITextField *)subview;
            break;
        }
    }
    searchBarTextField.enablesReturnKeyAutomatically = NO;
}
- (void)showCancelBtn
{
    if (self.cancelBtn.hidden) {
        self.cancelBtn.hidden = NO;
        [self.cancelBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.navBarV.mas_right).offset(-15);
            make.centerY.mas_equalTo(self.backBtn);
        }];
    }
}
- (void)upCanCelBtnConstraits
{
    self.cancelBtn.hidden = YES;
    [self.cancelBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.navBarV.mas_right);
        make.centerY.mas_equalTo(self.backBtn);
        make.width.mas_offset(0);
    }];
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
        NSLog(@"%@1",searchBar.text);
}

@end