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

#import "KWMBrandCaramelVC.h"
#import "KWMBrandCaramelCell.h"
#import "KWMBarandSelectView.h"
#import "KWMProductDetailVC.h"
#import "KWMShopCartVC.h"
#import "KWMShopCartData.h"
#import "UIImageView+WebCache.h"
#import "KWMImageUtil.h"
#import "KWMStringUtil.h"
#import "KWMFilterUtil.h"
#import "UIColor+SAMAdditions.h"
#import "MJRefresh.h"
#import "KWMFilterVC.h"
#import "KWMShoppingCart.h"
#import <RXCollections/RXCollection.h>

@interface KWMBrandCaramelVC ()<UITableViewDelegate,UITableViewDataSource,KWMBrandCaramelCellDelegate>
@property (nonatomic) KWMBarandSelectView *barandSelectView;
@property (nonatomic) NSArray<BUYProduct *> *productArr;

@end

@implementation KWMBrandCaramelVC{
    UIButton *rightButton;
    BOOL isUp;
    NSInteger backgroundTop;//品牌背景上间距
    NSInteger tvTop;//品牌描述上间距
    BOOL isHasGoods;//是否有商品
    NSInteger mark;//标记展开标尺的pruduct下标
    NSArray *colorArr;
    __weak KWMFilterVC *filterVC;
}

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

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

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initView];
    [self getCollection:_handle];
    if(self.goodModel){
        [self initCacheData];
    }
}

-(void)initCacheData{
    if(self.goodModel){
        NSArray *products =  [self.userDao getCollectionCache:self.goodModel.id tags:_isSale?[NSArray arrayWithObjects:@"sale", nil]:nil];
        if(products && products.count>0){
            [self appendDataList:products setPage:1];
            self.currentPage = 0;
        }
    }else if(self.collection!=nil && self.collection.identifier!=nil){
        NSArray *products =  [self.userDao getCollectionCache:self.collection.identifier tags:_isSale?[NSArray arrayWithObjects:@"sale", nil]:nil];
        if(products && products.count>0){
            [self appendDataList:products setPage:1];
            self.currentPage = 0;
        }
    }
}



- (void)setBackColor{
       colorArr = [NSArray arrayWithObjects:@"#D8A88D",@"#A4C8C6",@"#E6C995",@"#718473",@"#D7B48B", nil];
    int num = arc4random_uniform(10);
    NSString *colorStr = [colorArr objectAtIndex:num/(colorArr.count)];
    _ivBrand.backgroundColor = [UIColor sam_colorWithHex:colorStr];
}

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

-(void)loadData{
    if(self.collection!=nil && self.collection.identifier!=nil){
        [self getProcduct:self.collection.identifier];
    }
}

-(void)reLoadData{
    self.currentPage = 0;
    if(self.collection!=nil && self.collection.identifier!=nil){
        [self getProcduct:self.collection.identifier];
    }}

- (void)initHeaderView{
    
    _barandSelectView = [[KWMBarandSelectView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 64)];
    _barandSelectView.count = [[KWMShoppingCart sharedInstance] count].integerValue;
    _barandSelectView.lbBrand.text = [_brand uppercaseString];
    
    [self.view addSubview:_barandSelectView];
    _barandSelectView.delegate = self;
}

static NSString *idStr = @"KWMBrandCaramelCell";
- (void)initView{

    isUp = NO;
    backgroundTop = 210;
    tvTop = 255;
    mark = -1;

    self.automaticallyAdjustsScrollViewInsets = NO;
    self.hasNextPage = NO;
    self.tbvBrandCaramel.delegate = self;
    self.tbvBrandCaramel.showsVerticalScrollIndicator = NO;
    [self.tbvBrandCaramel registerNib:[UINib nibWithNibName:idStr bundle:nil] forCellReuseIdentifier:idStr];
    
    //从新品/折扣跳转过来的非品牌页面
    if(self.goodModel!=nil && self.goodModel.comments!=nil && ![self.goodModel.comments isEqualToString:@"品牌"]){
        self.tbvBrandCaramel.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    
    if (_backColor) {
        _ivBrand.backgroundColor = _backColor;
    }else{
        [self setBackColor];
    }
    
    self.filterView.delegate = self;
    self.filterTab.delegate = self;
}


- (void)beackLastController:(UIBarButtonItem *)leftBtn{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onClickBotomBtn:(id)sender {
    
    self.tvDescription.scrollEnabled = NO;
    self.btnBottom.userInteractionEnabled = NO;
    //下划
    if (isUp) {
        _btnBottom.backgroundColor = [UIColor blackColor];
        [self changeFrameBy:+210 WithImageName:@"button_ brand_pull-up" AndShowView:2];
    }else{//上划
        _btnBottom.backgroundColor = [UIColor clearColor];
        [self changeFrameBy:-210 WithImageName:@"button_brand_pull-down" AndShowView:2];
    }
    isUp = !isUp;
}

//动画 筛选显示:0:不显示   1:显示   2:没有
- (void)changeFrameBy:(NSInteger)value WithImageName:(NSString *)imageStr AndShowView:(NSInteger)showNum{
    
    [UIImageView animateWithDuration:1.0 animations:^{
        //heardView动画
        self.vBackground.frame = CGRectMake(0, backgroundTop + value, UI_SCREEN_WIDTH, 210);
        self.tvDescription.frame = CGRectMake(0, tvTop + value, UI_SCREEN_WIDTH, 128);
        
        [self.btnBottom setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
    } completion:^(BOOL finished) {
       //heardView动画
        backgroundTop = backgroundTop + value;
        tvTop = tvTop + value;
        self.tvDescription.scrollEnabled = YES;
        self.btnBottom.userInteractionEnabled = YES;
    }];
}



#pragma mark -- KWMBarandSelectViewDelegate
//点击返回按钮回调
- (void)kwm_clickBackBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
//点击购物车回调
- (void)kwm_HitShopCartBtn{

//    self.vNoneGoods.hidden = !self.vNoneGoods.hidden;
    KWMShopCartVC * shopCartVC = (KWMShopCartVC*)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:shopCartVC animated:YES];
}

#pragma mark -- KWMFilterDelegate
-(void)kwm_onFilterFinish:(KWMFilterView *)filterView{
    self.filterView.hidden = YES;
    [self.filterTab close];
    [self reLoadData];
    [self.tbvBrandCaramel.mj_header beginRefreshing];
    [self.tbvBrandCaramel 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.filterMode = filterMode;
    if(isExpand){
        [self.filterView show];
    }
    self.filterView.hidden = !isExpand;
}

#pragma mark -- KWMBrandCaramelCellDelegate

//点击左边商品回调
- (void)kwm_onClickLeftIamge:(KWMBrandCaramelCell *)brandCell{
    KWMProductDetailVC *productDetailVC = (KWMProductDetailVC*)[KWMBaseVC findControllerBy:[KWMProductDetailVC kwmTag] fromStoryboard:@"New"];
    productDetailVC.product = brandCell.leftProduct;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

//点击右边商品回调
- (void)kwm_onClickRightIamge:(KWMBrandCaramelCell *)brandCell{
    KWMProductDetailVC *productDetailVC = (KWMProductDetailVC*)[KWMBaseVC findControllerBy:[KWMProductDetailVC kwmTag] fromStoryboard:@"New"];
    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 (mark != idx) {
                mark = idx;
                [self.tbvBrandCaramel reloadData];
            }
            *stop = YES;
        }
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (mark % 2 ) {
            [brandCell openRule:NO];
        }else{
            [brandCell openRule:YES];
        }
       
    });
    
}

#pragma mark -- UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count%2 == 0 ? self.dataList.count/2 : self.dataList.count/2 + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWMBrandCaramelCell *brandCaramelCell = [tableView dequeueReusableCellWithIdentifier:idStr forIndexPath:indexPath];
    
    brandCaramelCell.selectionStyle = UITableViewCellSelectionStyleNone;
    brandCaramelCell.delegate = self;
    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;
        
        //如果该页面来自新品/折扣 且不为品牌页面,则,cell标题显示品牌
        if(self.goodModel!=nil && self.goodModel.comments!=nil && ![self.goodModel.comments isEqualToString:@"品牌"]){
            brandCaramelCell.isShowBrandTitle = YES;
        }
        [brandCaramelCell setData:leftProduct rightProduct:rightProduct];
    }
    return brandCaramelCell;
}

#pragma mark -- UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [self tableView:tableView didDeselectRowAtIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 244;
}

-(void)getCollection:(NSString *)collectionHandle{
    NSString *handle = collectionHandle;
    if(self.goodModel!=nil && ![KWMStringUtil isEmpty:self.goodModel.handle]){
        handle = self.goodModel.handle;
    }else if([KWMStringUtil isEmpty:collectionHandle]){
        return;
    }
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if(collection && !error){
            self.collection = collection;
            [self setBrandData];
            [self getProcduct:collection.identifier];
            if(!self.goodModel){
                [self initCacheData];
            }
        }else if(error != nil){
            [self showError:error];
        }
    }];
}

- (void)setBrandData{
    //图片
    if(_collection!=nil && _collection.image!=nil){
        NSURL *url =  [_collection.image sourceURL];
        [_ivBrand sd_setImageWithURL:url placeholderImage:nil];
    }

    if(_collection!=nil && ![KWMStringUtil isEmpty:_collection.stringDescription]){
        //文字介绍
        _tvDescription.text = _collection.stringDescription;
        _tvDescription.hidden = NO;
        _btnBottom.hidden = NO;
    }else{
        _tvDescription.hidden = YES;
        _btnBottom.hidden = YES;
    }
}

- (void)getProcduct:(NSNumber *)collectionId{
    
    if(collectionId == nil){
        return;
    }
    __weak KWMBrandCaramelVC *weakSelf = self;
    //初始化排序及筛选tag
    BUYCollectionSort collectionSort = self.filterView.selectedSort;
    NSMutableArray *tags = [KWMFilterUtil getTagsByFilterArray:self.filterView.selectedTags];
    if(self.isSale){
        [tags addObject:@"sale"];
    }
    
    NSInteger tagetPage = self.currentPage.integerValue + 1;
    [self.client getProductsPage:tagetPage inCollection:collectionId withTags:tags sortOrder:collectionSort completion:^(NSArray *products,NSUInteger page, BOOL reachedEnd, NSError *error){
        products = [products rx_filterWithBlock:^BOOL(BUYProduct *each) {
            return each.availableValue;
        }];
        if (error) {
            [self showError:error];
            NSLog(@"Error fetching products: %@", error);
        }else if (products.count == 0 && tagetPage == 1){
            weakSelf.vNoneGoods.hidden = NO;
            [weakSelf.dataList removeAllObjects];
            [self.tbvBrandCaramel reloadData];
        }else if (error == nil && products) {
            
            if(tagetPage == 1 && (tags.count == 0 || (tags.count == 1 && weakSelf.isSale)) ){
                [weakSelf.userDao saveCollectionCache:products collectionId:collectionId tags:tags];
            }
            
            weakSelf.hasNextPage = !reachedEnd;
            [weakSelf appendDataList:products setPage:page];
            weakSelf.vNoneGoods.hidden = YES;
            [self.tbvBrandCaramel reloadData];
        }
        [weakSelf hideLoading];
    }];
}

@end