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

#import "KWMSelectedGoodsVC.h"
#import "KWMNewProductVC.h"
#import "KWMBeforePayVC.h"
#import "KWMMineTitleView.h"
#import "MJRefresh.h"
#import "KWMFilterUtil.h"
#import "KWMStringUtil.h"
#import "KWMImageBlurUtil.h"
#import "KWMPPCacheUtil.h"

@interface KWMSelectedGoodsVC ()
@end

@implementation KWMSelectedGoodsVC{
    UIButton *rightButton;
    BOOL isSelect;
    UIView *vStopTap;
    NSInteger openPosition;//标记展开标尺的pruduct下标
}

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

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

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


static NSString *idStr = @"KWMBrandCaramelCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    
//    [self reLoadData];
}

- (void)initView{
    
    self.hasNextPage = NO;
    self.collectionSort = BUYCollectionSortCreatedDescending;
    if (self.handle && !self.title) {
        self.title = self.handle.capitalizedString;
    }
    openPosition = -1;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    isSelect = NO;
    vStopTap = [[UIView alloc] initWithFrame:CGRectMake(0, 20, UI_SCREEN_WIDTH, 44)];
    vStopTap.backgroundColor = [UIColor clearColor];
    _vHeard.backgroundColor = [UIColor sam_colorWithHex:@"F4F5F7"];
    
    self.filterView.delegate = self;
    self.filterTab.delegate = self;
    
    [self fixFilterError];
}

-(void)fixFilterError{
    NSMutableDictionary *sf = [NSMutableDictionary new];
    
    for (NSString *tag in self.ctags) {
        for (KWMFilter *kf in self.filterView.allTags) {
            NSString * key = nil;
            for (NSString *it in kf.tags) {
                if ([[KWMFilterUtil transformTag:nil tag:it] isEqualToString:tag]) {
                    key = it;
                    break;
                }
            }
            if (key) {
                if (sf[kf.group]) {
                    [sf[kf.group] addObject:key];
                }else{
                    [sf setValue:[[NSMutableArray alloc] initWithObjects:key, nil] forKey:kf.group];
                }
                break;
            }
        }
    }
    
    if ([sf count]) {
        [self.filterView setSelectedTags:[[[sf allKeys] rx_mapWithBlock:^id(id each) {
            KWMFilter *r = [[KWMFilter alloc] init];
            r.group = each;
            r.tags = sf[each];
            return r;
        }] mutableCopy]];
    }
}

-(UITableView *)targetTableView{
    return self.tbvSelectedGoods;
}

-(void)loadData{
    [self requestProductList];
}

-(void)reLoadData{
    self.currentPage = 0;
    [self requestProductList];
}


- (void)setAnimatedWith:(CGFloat)moveHeight{
    [UIImageView animateWithDuration:1.0 animations:^{
        self.vGoodsStyle.frame = CGRectMake(0, moveHeight, UI_SCREEN_WIDTH, 340);
    } completion:^(BOOL finished) {
        [vStopTap removeFromSuperview];
        if (moveHeight>0) {
            self.vBackground.hidden = NO;
        }else{
            self.vBackground.hidden = YES;
        }
    }];
}

#pragma mark -- KWMFilterDelegate
-(void)kwm_onFilterFinish:(KWMFilterView *)filterView{
    self.filterView.hidden = YES;
    [self.filterTab close];
//    [self reLoadData];
    [self.tbvSelectedGoods.mj_header beginRefreshing];
    [self.tbvSelectedGoods setContentOffset:CGPointMake(0,0) animated:YES];
}

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

#pragma mark -- KWMNormalFilterTabDelegate
-(void)kwm_onClickTab:(KWMFilterMode)filterMode isExpandView:(BOOL)isExpand{
    self.filterView.hidden = !isExpand;
    self.filterView.filterMode = filterMode;
}


#pragma mark -- KWMBrandCaramelCellDelegate

//点击左边商品回调
- (void)kwm_onClickLeftIamge:(KWMBrandCaramelCell *)brandCell{
    KWMNewProductVC *productDetailVC = [KWMNewProductVC getNewInstance];
    productDetailVC.product = brandCell.leftProduct;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

//点击右边商品回调
- (void)kwm_onClickRightIamge:(KWMBrandCaramelCell *)brandCell{
    KWMNewProductVC *productDetailVC = [KWMNewProductVC getNewInstance];
    productDetailVC.product = brandCell.rightProduct;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

- (void)kwm_openRule:(BUYProduct *)product Or:(KWMDataProduct *)dataProduct And:(KWMBrandCaramelCell *)brandCell{
    
    if (product == nil) {
        return;
    }
    [self.dataList enumerateObjectsUsingBlock:^(BUYProduct *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqual:product]) {
            if (openPosition != idx) {
                openPosition = idx;
                [self.tbvSelectedGoods reloadData];
            }
            *stop = YES;
        }
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (openPosition % 2 ) {
            [brandCell openRule:NO];
        }else{
            [brandCell openRule:YES];
        }
        
    });
}

#pragma mark -- UITableViewDelegateU
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.dataList == nil){
        return 0;
    }
    NSInteger count = self.dataList.count;
    if(count%2 == 0){
        return count/2;
    }else{
        return count/2+1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KWMBrandCaramelCell *brandCaramelCell = [tableView dequeueReusableCellWithIdentifier:idStr];
    if(!brandCaramelCell){
        [tableView registerNib:[UINib nibWithNibName:idStr bundle:nil] forCellReuseIdentifier:idStr];
        brandCaramelCell = [tableView dequeueReusableCellWithIdentifier:idStr];
    }
    brandCaramelCell.isShowBrandTitle = YES;
    brandCaramelCell.delegate = self;
    brandCaramelCell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger position = indexPath.row * 2;
    if(self.dataList!=nil && self.dataList.count>0){
        BUYProduct *leftProduct = [self.dataList objectAtIndex:position];
        BUYProduct *rightProduct = self.dataList.count>(position+1)?[self.dataList objectAtIndex:(position+1)]:nil;
        [brandCaramelCell setData:leftProduct rightProduct:rightProduct];
    }    
    return brandCaramelCell;
}

#pragma mark -- ITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (UI_SCREEN_WIDTH/2 - 20 + 64);
}

- (void)requestProductList{
    __weak KWMSelectedGoodsVC *weakSelf = self;
    if (self.handle) {
        [self.client getCollectionByHandle:self.handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
            NSArray * tags = [KWMFilterUtil getTagsByFilterArray:weakSelf.filterView.selectedTags];
            if ([tags count] <= 0) {
                tags = weakSelf.ctags;
            }
            if(error){
                [weakSelf showError:error];
            }
            if(collection){
                [weakSelf requestProductListApi:collection.identifier tags:tags];
            }
        }];
        return;
    }else{
        if(!self.collection){
            return;
        }
        NSNumber *collectionId = self.collection.identifier;
        //初始化tag
        NSMutableArray *tags = [KWMFilterUtil getTagsByFilterArray:self.filterView.selectedTags];
        if(collectionId == nil){
            return;
        }
        [self requestProductListApi:collectionId tags:tags];
    }
}

- (void)requestProductListApi:(NSNumber *)collectionId tags:(NSArray *)tags{
    self.isLoading = YES;
    __weak KWMSelectedGoodsVC *weakSelf = self;
    NSInteger tagetPage = self.currentPage.integerValue + 1;
    BUYCollectionSort collectionSort = self.filterView.selectedSort;
    [self.client getProductsPage:tagetPage inCollection:collectionId withTags:tags sortOrder:collectionSort completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
        [weakSelf hideLoading];
        weakSelf.isLoading = NO;

        if(tagetPage == 1){
            [weakSelf.dataList removeAllObjects];
            if(!products || products.count == 0){
                weakSelf.vNoData.hidden = NO;
                [weakSelf.tbvSelectedGoods reloadData];
                return;
            }
        }
        if (error == nil && products) {
            self.vNoData.hidden = YES;
            weakSelf.hasNextPage = !reachedEnd;
            [weakSelf appendDataList:products setPage:page];
        }
        else {
            [self showError:error];
            NSLog(@"Error fetching products: %@", error);
        }
    }];
}

@end