//
//  KWMCategoryVC.m
//  iCemarose
//
//  Created by HouWeiBin on 2017/6/13.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMCategoryVC.h"
#import "KWMNewProductVC.h"
#import "KWMShopCartVC.h"
#import "KWMNewProductVC.h"
#import "KWMSearchFeedbackVC.h"
#import "KWMLeftCategoryCell.h"
#import "KWMRightProductCell.h"
#import "KWMBrandsTypeModel.h"
#import "KWMStringUtil.h"
#import "KWMFilterUtil.h"
#import "MJRefresh.h"
#import "KWMShoppingCart.h"



//#import <RXCollections/RXCollection.h>

@interface KWMCategoryVC ()

@property (nonatomic,weak) IBOutlet KWMCategoryFilterTab *filterTab;

@property (nonatomic,weak) IBOutlet UITableView *tbvLeftCategory;

@property (nonatomic,weak) IBOutlet UICollectionView *cvRightProduct;

@property(nonatomic) KWMCollectionRefreshUtil *refreshUtil;

@property (nonatomic) KWMCategoryTitleView *titleView;

@property (nonatomic) NSArray *allBrands;

//@property(nonatomic) BUYCollectionSort sort;

//@property(nonatomic) NSMutableArray<KWMFilter *> *selectFilters;

//@property(nonatomic) NSString *selectBrands;

@property(nonatomic) NSArray<KWMCategoryModel *>* categories;

@property (nonatomic) KWMCategoryModel *selectedCategory;

@end

@implementation KWMCategoryVC

- (void)awakeFromNib{
    [super awakeFromNib];
    self.title = @"分类";
}

+ (NSString *)kwmBoard {
    return @"Main";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initView];
    [self requestAllBrandsApi];
//    [self.refreshUtil reLoadData];
//    [self.cvRightProduct.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    if(self.titleView){
        NSNumber *count = [[KWMShoppingCart sharedInstance] count];
        self.titleView.count = count;
    }
}

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

-(KWMCollectionRefreshUtil *)refreshUtil{
    if(!_refreshUtil){
        _refreshUtil = [KWMCollectionRefreshUtil new];
        _refreshUtil.collectionView = self.cvRightProduct;
        _refreshUtil.delegate = self;
        _refreshUtil.emptyMsg = @" ";
    }
    return _refreshUtil;
}

-(void) initData {
    self.categories = [@[
                         @{@"title":@"上装",@"collection_id":@"192437702",@"image":@"ic_type_tops"},
                         @{@"title":@"连体衣",@"collection_id":@"192438342",@"image":@"ic_type_jumpsuits"},
                         @{@"title":@"外套",@"collection_id":@"192438790",@"image":@"ic_type_coat"},
                         @{@"title":@"裙子",@"collection_id":@"191377286",@"image":@"ic_type_skirt"},
                         @{@"title":@"裤子",@"collection_id":@"333026630",@"image":@"ic_type_trousers"},
                         @{@"title":@"短裙",@"collection_id":@"192434950",@"image":@"ic_type_kilt"},
                         @{@"title":@"套装",@"collection_id":@"192438150",@"image":@"ic_type_suit"},
                         @{@"title":@"泳衣",@"collection_id":@"333026438",@"image":@"ic_type_swimsuit"},
                         @{@"title":@"连裤袜",@"collection_id":@"192437830",@"image":@"ic_type_pantyhose"},
                         @{@"title":@"打底裤",@"collection_id":@"192435334",@"image":@"ic_type_leggings"},
                         @{@"title":@"内衣",@"collection_id":@"333026694",@"image":@"ic_type_underwear"},
                         @{@"title":@"雨衣",@"collection_id":@"423509068",@"image":@"ic_type_raincoat"},
                         @{@"title":@"鞋子",@"collection_id":@"171856134",@"image":@"ic_type_shoe"},
                         @{@"title":@"玩具",@"collection_id":@"332990918",@"image":@"ic_type_toy"},
                         @{@"title":@"配件",@"collection_id":@"191376966",@"image":@"ic_type_Acc"},
                        ] rx_mapWithBlock:^id(id each) {
                            NSString *image = each[@"image"];

                            KWMCategoryModel *m = [KWMCategoryModel new];
                            m.title = each[@"title"];
                            m.collection_id = @([each[@"collection_id"] integerValue]);
                            m.image = [NSString stringWithFormat:@"%@_nor",image];
                            m.focusImage = [NSString stringWithFormat:@"%@_pre",image];
                            m.page = 1;
                            m.products = [NSMutableArray new];
                            m.sort = BUYCollectionSortCollectionDefault;
                            return m;
                        }];
    self.selectedCategory = self.categories.firstObject;
    NSIndexPath * path = [NSIndexPath indexPathForItem:0 inSection:0];
    [self.tbvLeftCategory selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionTop];
}

-(void)initView{
    [self initTitleView];
    [self initTbvLeft];
    [self initCvRight];
    
//    self.sort = BUYCollectionSortCollectionDefault;
//    self.selectBrands = @"";
}

-(void)initTbvLeft{
    self.cvRightProduct.mj_footer.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tbvLeftCategory registerNib:[UINib nibWithNibName:NSStringFromClass([KWMLeftCategoryCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([KWMLeftCategoryCell class])];
}

-(void)initCvRight{
    [self.cvRightProduct registerNib:[UINib nibWithNibName:NSStringFromClass([KWMRightProductCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([KWMRightProductCell class])];
    self.filterTab.delegate = self;
}

- (void)initTitleView{
    [self.navigationController setNavigationBarHidden:YES];
    NSNumber *count = [[KWMShoppingCart sharedInstance] count];
    
    self.titleView = [[KWMCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    self.titleView.delegate = self;
    self.titleView.count = count;
    [self.view addSubview:self.titleView];
}

#pragma mark -- KWMCategoryTitleDelegate
-(void)kwm_onClickShopCart{
    KWMShopCartVC * shopCartVC = (KWMShopCartVC*)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:shopCartVC animated:YES];
}

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

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWMLeftCategoryCell *categoryCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([KWMLeftCategoryCell class]) forIndexPath:indexPath];
    [categoryCell fillData:self.categories[indexPath.item]];
    return categoryCell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.categories.count;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedCategory = self.categories[indexPath.row];
}

#pragma mark - UICollectionViewDataSource
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KWMRightProductCell *productCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([KWMRightProductCell class]) forIndexPath:indexPath];
    productCell.product = (BUYProduct *)[self.refreshUtil.dataList objectAtIndex:indexPath.row];
    return productCell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger width = ( (UI_SCREEN_WIDTH - 90) - 8*2)/2;
    NSInteger height = width * 160 / 114 ;
    CGSize size = CGSizeMake(width, height);
    return size;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.refreshUtil.dataList.count;
}

#pragma mark - UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    KWMNewProductVC *productDetailVC = (KWMNewProductVC *)[KWMNewProductVC findControllerBy:[KWMNewProductVC kwmTag] fromStoryboard:@"NewProduct"];
    BUYProduct *product = (BUYProduct *)[self.refreshUtil.dataList objectAtIndex:indexPath.row];
    productDetailVC.product = product;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

#pragma mark - KWMCollectionRefreshDelegate
-(void)refreshUtil:(KWMCollectionRefreshUtil *)util onLoad:(NSInteger)page{
    if (page == 0) {
        [self requestProducts:1];
    }else{
        [self requestProducts:self.selectedCategory.page + 1];
    }
}

#pragma mark - CategoryFilterTabDelegate
-(void)kwm_onClickTab:(KWMFilterMode)filterMode isExpandView:(BOOL)isExpand{
    KWMBaseVC *tragetVC;
    if(filterMode == ModeBrand){
        KWMBrandFilterVC *brandFilterVC = (KWMBrandFilterVC *)[KWMBaseVC findControllerBy:[KWMBrandFilterVC kwmTag] fromStoryboard:@"Category"];
        brandFilterVC.brandArray = self.allBrands;
        brandFilterVC.delegate = self;
        brandFilterVC.selectBrand = self.selectedCategory.brand;
        tragetVC = brandFilterVC;
    }else{
        KWMProductFilterVC *productFilterVC = (KWMProductFilterVC *)[KWMBaseVC findControllerBy:[KWMProductFilterVC kwmTag] fromStoryboard:@"Category"];
        productFilterVC.filterMode = filterMode;
        productFilterVC.delegate = self;
        productFilterVC.selectedSort = self.selectedCategory.sort;
        productFilterVC.selectedTags = self.selectedCategory.filters;
        tragetVC = productFilterVC;
    }
    CGSize size = [UIScreen mainScreen].bounds.size;
    [self showPresentation:tragetVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
}

#pragma mark -
-(void)kwm_onCompleProductFilter:(KWMFilterView *)filterView{
//    self.selectFilters = filterView.selectedTags;
    self.selectedCategory.filters = filterView.selectedTags;
    self.selectedCategory.sort = filterView.selectedSort;
    [self.filterTab close];
    [self.refreshUtil reLoadData];
    [self.cvRightProduct.mj_header beginRefreshing];
    [self.cvRightProduct setContentOffset:CGPointMake(0,0) animated:YES];
}

-(void)kwm_onCancelProductFilter:(KWMFilterView *)filterView{
    [self.filterTab close];
}

#pragma mark - 
-(void)kwm_onCompleteBrandFilter:(NSString *)selectBrand{
//    self.selectBrands = selectBrand;
    self.selectedCategory.brand = selectBrand;
    [self.filterTab close];
    [self.refreshUtil reLoadData];
    [self.cvRightProduct.mj_header beginRefreshing];
    [self.cvRightProduct setContentOffset:CGPointMake(0,0) animated:YES];
}

-(void)kwm_onCancelBrandFilter{
    [self.filterTab close];
}

#pragma mark - API KWMAPIManager.h
-(void)requestAllBrandsApi{
    __weak KWMCategoryVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMBrandsResult *) = ^(NSURLSessionDataTask *task,KWMBrandsResult *result){
        if([weakSelf hasCemaroseError:result]){
            return ;
        }
        self.allBrands = result.brands;
    };
    [self.api getAllBrand:nil success:success failure:failure];
}

#pragma mark - API BUYClient+Storefront.h
-(void)requestProducts:(NSInteger)cpage{
    __weak KWMCategoryVC *weakSelf = self;
    self.filterTab.userInteractionEnabled = false;
    
    KWMCategoryModel *cmodel = self.selectedCategory;
    NSMutableArray *tags = [KWMFilterUtil getTagsByFilterArray:cmodel.filters];
    if(cmodel.brand){
        [tags addObject:cmodel.brand];
    }
    [self.client getProductsPage:cpage inCollection:cmodel.collection_id withTags:tags sortOrder:cmodel.sort completion:^(NSArray *products,NSUInteger page, BOOL reachedEnd, NSError *error){
        weakSelf.cvRightProduct.mj_footer.hidden = false;
        if (cmodel == self.selectedCategory) {
            [weakSelf.refreshUtil hideLoading];
        }
        if(reachedEnd){
            [weakSelf.cvRightProduct.mj_footer endRefreshingWithNoMoreData];
        }
        weakSelf.filterTab.userInteractionEnabled = true;

        if(error){
            [weakSelf showError:error];
        }
        else{
//            weakSelf.refreshUtil.page = page;
            cmodel.page = page;
//            weakSelf.refreshUtil.hasNextPage = !reachedEnd;
//            [weakSelf.refreshUtil appendDataList:products];
            if (cpage == 1) {
                [cmodel.products removeAllObjects];
            }
            [cmodel.products addObjectsFromArray:products];
            if (cmodel == weakSelf.selectedCategory) {
                [weakSelf.cvRightProduct reloadData];
            }
        }
    }];
}

#pragma mark - setter

- (void)setSelectedCategory:(KWMCategoryModel *)selectedCategory {
    _selectedCategory = selectedCategory;
    [self.cvRightProduct.mj_footer resetNoMoreData];
    self.refreshUtil.page = _selectedCategory.page;
    self.refreshUtil.hasNextPage = YES;
    self.refreshUtil.dataList = _selectedCategory.products;
    [self.cvRightProduct reloadData];
    if (_selectedCategory.products.count == 0) {
//        [self requestProducts:1];
//        [self.refreshUtil reLoadData];
        if ([self.cvRightProduct.mj_header isRefreshing]) {
            [self requestProducts:1];
        }else{
            [self.cvRightProduct.mj_header beginRefreshing];
        }
    }else if([self.cvRightProduct.mj_header isRefreshing]) {
        [self.cvRightProduct.mj_header endRefreshing];
    }
//    [self.cvRightProduct reloadData];
}

@end