//
//  KWMSearchBrandVC.m
//  iCemarose
//
//  Created by 陈荣科 on 16/8/30.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMSearchBrandVC.h"
#import "NSString+PinYin.h"
#import "KWMSearchBrandView.h"
#import "KWMStringUtil.h"
#import "KWMBrandCaramelVC.h"
#import "KWMSearchBrandsCell.h"
#import <RXCollections/RXCollection.h>



@interface KWMSearchBrandVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,KWMSearchBrandViewDelegate>
@property (nonatomic,strong)  NSMutableArray  *dataArray;
@property (nonatomic,weak)KWMSearchBrandView *searchBrandView;
@end

@implementation KWMSearchBrandVC {
    NSMutableArray *searchArr;
    NSString *searchTitle;
}

+(NSString *)kwmTag{
    return @"KWMSearchBrandVC";
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initHeaderView];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"所有品牌";
    self.vLine.backgroundColor = [UIColor colorWithRed:244.0/255 green:245.0/255 blue:247.0/255 alpha:1];
    searchArr = [NSMutableArray array];
    [self initTableView];
    [self loadStaticData];
    [self RequestBrandsAPI];
}

- (void) loadStaticData {
    NSArray *brands = @[@"Amelie Wang",@"Babywalker",@"Beau Loves",@"Billieblush",@"Billybandit",@"Bonpoint",@"Burberry",@"Caramel",@"Chloé",@"Dolce & Gabbana",@"Emile et Ida",@"Fendi",@"Givenchy",@"Gucci",@"Hucklebones",@"Il Gufo",@"Indikidual",@"Karl Lagerfeld Kids",@"Kenzo",@"Lanvin",@"Little Marc Jacobs",@"Loud Apparel",@"Louis Louise",@"Louise Misha",@"Marie-Chantal",@"Marni",@"Mini Melissa",@"Mini Rodini",@"Mischka Aoki",@"Moncler",@"MOSCHINO",@"MSGM",@"Nailmatic",@"Nana Huchy",@"Noukie's",@"Oeuf",@"Patachou",@"Paul Smith",@"PèPè",@"Sons + Daughters Eyewear",@"Stella McCartney Kids",@"Story Loris",@"Tartine et Chocolat",@"The Animals Observatory",@"Tiny Cottons",@"Tip Toey Joey",@"Veja",@"Wolf & Rita",@"Young Versace",@"Zadig & Voltaire"];
    
    NSArray  *indexArray= [[brands rx_filterWithBlock:^BOOL(id each) {
        return each && each != [NSNull null];
    }] arrayWithPinYinFirstLetterFormat];
    _dataArray =[NSMutableArray arrayWithArray:indexArray];
    [self.tbvSearchBrand reloadData];
}

- (void)initHeaderView{
    KWMSearchBrandView *searchBrandView = [[KWMSearchBrandView alloc] init];
    [self.view addSubview:searchBrandView];
    self.searchBrandView = searchBrandView;
    self.searchBrandView.delegate = self;
    [self initCustomTitleBarConstarints:self.searchBrandView];
}

static NSString *identify = @"KWMSearchBrandsCell";

- (void)initTableView{
    self.tbvSearchBrand.sectionIndexColor = [UIColor blackColor];
    self.tbvSearchBrand.sectionIndexBackgroundColor = [UIColor clearColor];
    [self.tbvSearchBrand setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tbvSearchBrand registerNib:[UINib nibWithNibName:identify bundle:nil] forCellReuseIdentifier:identify];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBackgroundView:)];
    [self.vBackground addGestureRecognizer:tapGesture];
}

- (void)onClickBackgroundView:(UITapGestureRecognizer *)tapGesture{
    
    [_searchBrandView CancelSearch];
    self.vBackground.hidden = YES;
}

#pragma merk -- KWMSearchBrandViewDelegate
- (void)kwm_GoBackLastController{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)kwm_cancelSearch{
    [searchArr removeAllObjects];
    searchTitle = nil;
    self.vBackground.hidden = YES;
    [self.tbvSearchBrand reloadData];
}

- (void)kwm_tfSearchBeginEdit{
    self.vBackground.hidden = NO;
}

- (void)kwm_InputSpace:(NSString *)text{
    if (text.length == 0 || text == nil) {
        [self showToast:@"请输入需要搜索的内容"];
    }else{
        [_searchBrandView.tfBrand resignFirstResponder];
        self.vBackground.hidden = YES;
        [self setSearchBrandsWith:text];
    }
}

- (void)kwm_tfValueChange:(NSString *)text{

    if (text.length==0) {
        [searchArr removeAllObjects];
        searchTitle = nil;
        [self.tbvSearchBrand reloadData];
        return;
    }
    [self setSearchBrandsWith:text];
}

//搜索品牌名字判断
- (void)setSearchBrandsWith:(NSString *)text{
    
    //首字母大写
    NSString *pinYinStr = [KWMStringUtil transform:text];
    pinYinStr = [pinYinStr stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[pinYinStr substringToIndex:1] uppercaseString]];
    unichar aChar = [pinYinStr characterAtIndex:0];
    NSString *firstStr = [NSString stringWithFormat:@"%c",aChar];
    
    
    [self searchBrand:pinYinStr AndFirst:firstStr];
    [self.tbvSearchBrand reloadData];
}


- (void)searchBrand:(NSString *)brandStr AndFirst:(NSString *)firstStr{
    
    BOOL isOne = NO;
    if ([firstStr isEqualToString:[brandStr uppercaseString]]) {
        isOne = YES;
    }
    for (int i = 0; i < _dataArray.count; ++i) {
        NSDictionary *dict = self.dataArray[i];
        if (firstStr != nil) {
            searchTitle = firstStr;
            if ([firstStr isEqualToString:dict[@"firstLetter"]]) {
                [self JumpArr:dict[@"content"] Has:brandStr WithOnlyOne:isOne];
            }
        }
    }
}

- (void)JumpArr:(NSArray *)arr Has:(NSString *)str WithOnlyOne:(BOOL)isOne{
    
    if (searchArr.count > 0) {
        [searchArr removeAllObjects];
    }
    if (isOne) {//输入第一个字母的时候
        [searchArr addObjectsFromArray:arr];
        return ;
    }
    for (int i = 0; i < arr.count; ++i) {

        NSString *tempStr = arr[i];
        if ([tempStr containsString:str]) {
            [searchArr addObject:tempStr];
        }
    }
}

#pragma mark--- UITableViewDataSource and UITableViewDelegate Methods---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (searchArr.count > 0 || searchTitle != nil) {
        return 1;
    }
    return [self.dataArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (searchArr.count > 0 || searchTitle != nil) {
        return searchArr.count;
    }
    NSDictionary *dict = self.dataArray[section];
    NSMutableArray *array = dict[@"content"];
    return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWMSearchBrandsCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (searchArr.count > 0 || searchTitle != nil) {
        cell.lbBrand.text = searchArr[indexPath.row];
    }else{
        NSDictionary *dict = self.dataArray[indexPath.section];
        NSMutableArray *array = dict[@"content"];
        cell.lbBrand.text = array[indexPath.row];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //自定义Header标题
    UIView* myView = [[UIView alloc] init];
    myView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 90, 40)];
    titleLabel.textColor=[UIColor blackColor];
    NSString *title;
    if (searchTitle != nil) {
        title = searchTitle;
    }else{
       title = self.dataArray[section][@"firstLetter"];
    }
    titleLabel.text=title;
    titleLabel.font = [UIFont fontWithName:@"PingFang SC" size:24];
    UIView *vLine = [[UIView alloc] initWithFrame:CGRectMake(20, 39, UI_SCREEN_WIDTH - 40, 1)];
    vLine.backgroundColor = [UIColor colorWithRed:244.0/255 green:245.0/255 blue:247.0/255 alpha:1];
    [myView addSubview:vLine];
    [myView addSubview:titleLabel];
    
    return myView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH ,5)];
    footerView.backgroundColor = [UIColor colorWithRed:244.0/255 green:245.0/255 blue:247.0/255 alpha:1];
    return footerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *brand;
    if (searchArr.count > 0) {
        brand = searchArr[indexPath.row];
    }else{
        NSDictionary *dict = self.dataArray[indexPath.section];
        brand = [dict[@"content"] objectAtIndex:indexPath.row];
    }
    NSString *str = [KWMStringUtil deleteOtherCharExceptLetterWithLine:brand];
//    NSString *str = brand;
    
    NSLog(@"str: %@",str);
//    //品牌介绍
//    KWMBrandCaramelVC *brandCaramelVC = (KWMBrandCaramelVC *)[KWMBaseVC findControllerBy:[KWMBrandCaramelVC kwmTag] fromStoryboard:@"Brand"];
//    brandCaramelVC.handle = str;
//    brandCaramelVC.brand = brand;
//    brandCaramelVC.isSale = NO;
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [self.navigationController pushViewController:brandCaramelVC animated:YES];
    [self openURLWithString:[NSString stringWithFormat:@"https://www.cemarose.com/collections/%@",str]];
}

#pragma mark---tableView索引相关设置----
//添加TableView头视图标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *dict = self.dataArray[section];
    NSString *title = dict[@"firstLetter"];
    return title;
}

//添加索引栏标题数组
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //搜索品牌时
    if (searchArr.count >0 || searchTitle != nil) {
        return nil;
    }
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSDictionary *dict in self.dataArray) {
        NSString *title = dict[@"firstLetter"];
        [resultArray addObject:title];
    }
    
    return resultArray;
}

//点击索引栏标题时执行
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //这里是为了指定索引index对应的是哪个section的,默认的话直接返回index就好。其他需要定制的就针对性处理
    if ([title isEqualToString:UITableViewIndexSearch])
    {
        [tableView setContentOffset:CGPointZero animated:NO];//tabview移至顶部
        return NSNotFound;
    }
    else
    {
        return [[UILocalizedIndexedCollation currentCollation]sectionForSectionIndexTitleAtIndex:index+1] - 1; // -1 添加了搜索标识
    }
}

- (void)RequestBrandsAPI{
    __weak KWMSearchBrandVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
//        [weakSelf hideLoading];
//        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMBrandsResult *) = ^(NSURLSessionDataTask *task,KWMBrandsResult *result){
//        [weakSelf hideLoading];
        if([weakSelf hasCemaroseError:result]){
            return ;
        }
//        NSArray  *indexArray= [result.brands arrayWithPinYinFirstLetterFormat];
//        if(self.dataArray){ //如果已经从缓存拿到数据了。
//            return;
//        }
        if(result.brands){
            NSArray  *indexArray= [[result.brands rx_filterWithBlock:^BOOL(id each) {
                return each && each != [NSNull null];
            }] arrayWithPinYinFirstLetterFormat];
            _dataArray =[NSMutableArray arrayWithArray:indexArray];
            [weakSelf.tbvSearchBrand reloadData];
        }
    };
    void(^cacheCallback)(KWMBrandsResult *) = ^(KWMBrandsResult *result){
//        if([weakSelf hasCemaroseError:result]){
//            return ;
//        }
        if(result && result.brands){
            NSArray *indexArray= [[result.brands rx_filterWithBlock:^BOOL(id each) {
                return each && each != [NSNull null];
            }] arrayWithPinYinFirstLetterFormat];
            _dataArray =[NSMutableArray arrayWithArray:indexArray];
            [weakSelf.tbvSearchBrand reloadData];
        }
    };
    [self.api getAllBrand:nil cacheCallback:cacheCallback success:success failure:failure];
//    [self showLoading];
}

@end