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

#import "KWMBrandVC.h"
#import "KWMBrandCell.h"
#import "KWMBrandCaramelVC.h"
#import "KWMSearchBrandVC.h"
#import "KWMLoginVC.h"
#import "KWMShopCartVC.h"
#import "KWMShopCartData.h"
#import "KWMCarCountView.h"
#import "KWMStringUtil.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "KWMBrandsTypeModel.h"
#import "UIColor+SAMAdditions.h"
#import "KWMShoppingCart.h"
#import "KWMSearchFeedbackVC.h"


@interface KWMBrandVC ()<KWMCarCountViewDelegate>
@property (nonatomic) SFFocusViewLayout *focusViewLayout;
@property (nonatomic) KWMCarCountView *vCartCount;
@end

@implementation KWMBrandVC{
    NSIndexPath *selectPath;
    NSArray *bransType;
    NSMutableDictionary *imageDict;
    NSInteger loadNum;
    NSArray *colorArr;
}

static NSString *cellId = @"KWMBrandCell";

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
//    bransType = [NSArray array];
    imageDict = [NSMutableDictionary dictionary];
    colorArr = [NSArray arrayWithObjects:@"#D8A88D",@"#A4C8C6",@"#E6C995",@"#718473",@"#D7B48B", nil];
    // 底部背景高度 = 屏幕高 - 64 nav高度 - 最后一个cell的高度 - tabar高度44
    self.backgroundHeight.constant = UI_SCREEN_HEITHT - 64 - 280 - 44;
    self.moreBtnHeight.constant = UI_SCREEN_HEITHT - 64 - 280 - 44;
    
    [self.ctvBrand registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
    [self initView];
    [self initBrandNameAndImage];
//    [self requestBrandsType];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    [self.tabBarController setHidesBottomBarWhenPushed:NO];
    [self initHeardView];

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

- (void)initView{
    _focusViewLayout = [[SFFocusViewLayout alloc] init];
    self.ctvBrand.collectionViewLayout = _focusViewLayout;
    self.ctvBrand.delegate = self;
    self.ctvBrand.showsVerticalScrollIndicator = NO;
    [self.ctvBrand registerNib:[UINib nibWithNibName:@"KWMBrandCell" bundle:nil] forCellWithReuseIdentifier:cellId];
}

- (void) initHeardView{
    _vCartCount = [[KWMCarCountView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 64)];
    _vCartCount.count = [[KWMShoppingCart sharedInstance] count].integerValue;
    _vCartCount.delegate = self;
    [self.view addSubview:_vCartCount];
}

- (void)initBrandNameAndImage{
    bransType = [NSArray arrayWithObjects:@"Burberry",@"Caramel",@"Dolce & Gabbana",@"Fendi",@"Kenzo",@"Il Gufo",@"Stella McCartney Kids", nil];
    
    NSDictionary * dict = @{
                               @"Burberry":Burberry,
                               @"Caramel":Caramel,
                               @"Dolce & Gabbana":DolceGabbana,
                               @"Fendi":Fendi,
                               @"Kenzo":Kenzo,
                               @"Il Gufo":IlGufo,
                               @"Stella McCartney Kids":StellaMcCartneyKids,
                           };
    [imageDict addEntriesFromDictionary:dict];
}

- (void)onClickShopCart:(UIBarButtonItem *)btnRight{
    //购物车
    KWMShopCartVC *ShopCartVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:ShopCartVC animated:YES];
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.title = @"品牌";

}

-(void)onClickMoreBrand:(id)sender{
    KWMSearchBrandVC *searchBrandVC = (KWMSearchBrandVC*)[KWMBaseVC findControllerBy:[KWMSearchBrandVC kwmTag] fromStoryboard:@"Brand"];
    [self.navigationController pushViewController:searchBrandVC animated:YES];
}

#pragma mark - KWMCarCountViewDelegate
- (void)kwm_touchShopCartBtn{
    //购物车
    KWMShopCartVC *ShopCartVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:ShopCartVC animated:YES];
}

- (void)kwm_touchSearchBtn {
    KWMSearchFeedbackVC *vc = (KWMSearchFeedbackVC *)[KWMBaseVC findControllerBy:[KWMSearchFeedbackVC kwmTag] fromStoryboard:@"New"];
//    vc.searchText = @"";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (bransType.count > 0) {
        return bransType.count + 1;
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    KWMBrandCell *brandCell = (KWMBrandCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    selectPath = [collectionView indexPathsForSelectedItems].lastObject;
    if (indexPath.row == 0) {
        brandCell.lbTitle.text = @"所有品牌";
        brandCell.ivBackground.image = [UIImage imageNamed:@"shore_im_brands"];
    }else{
        NSString *brand = [bransType objectAtIndex:indexPath.row - 1];
        brandCell.lbTitle.text = brand;
//        KWMBrandsTypeModel *brands = [bransType objectAtIndex:indexPath.row - 1];
//        brandCell.lbTitle.text = brands.designers;
        if (imageDict.count > 0) {
            
            brandCell.ivBackground.image = nil;
//            [brandCell.ivBackground sd_setImageWithURL:[imageDict objectForKey:brands.designers] placeholderImage:[UIImage imageNamed:@"ic_loading"]];

            NSString *colorStr = [colorArr objectAtIndex:(indexPath.row)%(colorArr.count)];
            brandCell.ivBackground.backgroundColor = [UIColor sam_colorWithHex:colorStr];
            [brandCell.ivBackground sd_setImageWithURL:[imageDict objectForKey:brand] placeholderImage:nil];
        }
    }
    return brandCell;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    cell = nil;
}
#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row) {
//        KWMBrandsTypeModel *brands = [bransType objectAtIndex:indexPath.row - 1];
        //品牌介绍
        KWMBrandCaramelVC *brandCaramelVC = (KWMBrandCaramelVC *)[KWMBaseVC findControllerBy:[KWMBrandCaramelVC kwmTag] fromStoryboard:@"Brand"];
        brandCaramelVC.isSale = NO;
//        brandCaramelVC.handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:brands.designers];
//        brandCaramelVC.brand = brands.designers;
        
        NSString *brand = [bransType objectAtIndex:indexPath.row - 1];
        brandCaramelVC.handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:brand];
        brandCaramelVC.brand = brand;
        
        NSString *colorStr = [colorArr objectAtIndex:(indexPath.row)%(colorArr.count)];
        brandCaramelVC.backColor = [UIColor sam_colorWithHex:colorStr];
        
        [self.navigationController pushViewController:brandCaramelVC animated:YES];
    }else{
        //品牌搜索
        KWMSearchBrandVC *searchBrandVC = (KWMSearchBrandVC*)[KWMBaseVC findControllerBy:[KWMSearchBrandVC kwmTag] fromStoryboard:@"Brand"];
        [self.navigationController pushViewController:searchBrandVC animated:YES];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        reusableView = header;
    }
    reusableView.backgroundColor = [UIColor greenColor];
    if (kind == UICollectionElementKindSectionFooter)
    {
        UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
        footerview.backgroundColor = [UIColor purpleColor];
        reusableView = footerview;
    }
    return reusableView;
}

- (void)requestBrandsType{
    __weak KWMBrandVC *weakSelf = self;
    [weakSelf.api getBrandsType:nil success:^(NSURLSessionDataTask *task, KWMBrandsTypeResult *result) {
        NSString *handle;
        bransType = result.brandsType;
        loadNum = 0;
        for (int i = 0; i < bransType.count; ++i) {
            KWMBrandsTypeModel *brandsType = [bransType objectAtIndex:i];
            handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:brandsType.designers];
            [weakSelf requestBrandsdetail:handle With:brandsType.designers];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf hideLoading];
        [self showError:error];
    }];
    [self showLoading];
}

- (void)requestBrandsdetail:(NSString *)handle With:(NSString *)key{
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if (error == nil && collection) {
             [self hideLoading];
            loadNum++;
            [imageDict setObject:collection.image.sourceURL forKey:key];
            [self hideLoading];
            if (loadNum == bransType.count) {
                [self.ctvBrand reloadData];
            }
        }else{
             [self hideLoading];
            NSLog(@"error : %@",error);
        }
    }];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSIndexPath *path =  [self.ctvBrand indexPathForItemAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
    if(path.row == 7){
        self.btnMore.userInteractionEnabled = YES;
    }else{
        self.btnMore.userInteractionEnabled = NO;
    }
}


@end