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

#import "KWMNewVC.h"
#import "KWMStringUtil.h"
#import "KWMNewTypeSelectedVC.h"
#import "KWMSearchFeedbackVC.h"
#import "KWMShopCartVC.h"
#import "KWMShopCartData.h"
#import "KWMNewGoodsModel.h"
#import "KWMLoadStatus.h"
#import "KWMSelectedGoodsVC.h"
#import "KWMBrandCaramelVC.h"
#import "UIColor+SAMAdditions.h"
#import "KWMProductDetailVC.h"


@interface KWMNewVC ()
@property (nonatomic) KWMSearchBar *searchBar;
//@property (nonatomic) KWMNewGoodsModel *goodsModel;
@end

@implementation KWMNewVC{
    NSArray *collections;
    NSArray *discountCollections;
    NSArray *newCollections;
    NSMutableDictionary *newsDict;
    NSMutableDictionary *discountDic;
    BOOL isNew;//判断当前显示的是新品还是折扣列表
}

static NSString * idStr = @"KWMNewGoodsCell";
+(NSString *)kwmTag{
    return @"KWMNewVC";
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_searchBar removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNotification];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tbvNewGoods.showsVerticalScrollIndicator = NO;
    collections = [NSArray array];
    discountCollections = [NSArray array];
    newCollections = [NSArray array];
    newsDict = [[NSMutableDictionary alloc] init];
    discountDic = [[NSMutableDictionary alloc] init];
    
    isNew = YES;
    [self initView];
    [self requestNewProductsCollection];

}

- (void)initNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onBack)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
}

-(void)removreNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)dealloc{
    [self removreNotification];
}

-(void)onBack{
    [self.tbvNewGoods reloadData];
}

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

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self initHeaderView];
    [self.navigationController setNavigationBarHidden:YES];
    [self.tabBarController setHidesBottomBarWhenPushed:NO];
    if (_searchBar) {
        NSArray *arr = [[KWMShopCartData alloc] getALLItems];
        _searchBar.count = arr.count;
    }
    [_searchBar resumeView];
    _vBackground.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_searchBar removeFromSuperview];
}


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

- (void)loadData{
    
    if (isNew) {
        [self requestNewProductsCollection];
    }else{
        [self requestDiscountCollection];
    }
}
- (void)reLoadData{
    if (isNew) {
        [self requestNewProductsCollection];
    }else{
        [self requestDiscountCollection];
    }
}

- (void)initHeaderView{
    //添加頭部header
    _searchBar = [[KWMSearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    _searchBar.delegate = self;
    
    [self.view addSubview:_searchBar];
}

- (void)initView{
    
    [self.tbvNewGoods registerClass:[KWMNewGoodsCell class] forCellReuseIdentifier:@"KWMNewGoodsCell"];
    
    //新品
    self.btnNewGoods.selected = YES;
    self.btnNewGoods.backgroundColor =  [UIColor sam_colorWithHex:@"F19291"];
    
    self.btnNewGoods.layer.borderColor = [UIColor sam_colorWithHex:@"F19291"].CGColor;
    self.btnNewGoods.layer.borderWidth = 0.5;
    //打折
    self.btnDiscount.selected = NO;
    self.btnDiscount.layer.borderWidth = 0.5;
    self.btnDiscount.layer.borderColor =  [UIColor sam_colorWithHex:@"F19291"].CGColor;
    
    self.tbvNewGoods.delegate = self;
    self.tbvNewGoods.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tbvNewGoods.backgroundColor =  [UIColor sam_colorWithHex:@"FFFFFF"];
    [self.tbvNewGoods registerNib:[UINib nibWithNibName:idStr bundle:nil] forCellReuseIdentifier:idStr];
    
    self.vLine.backgroundColor = [UIColor sam_colorWithHex:@"F5F5F5"];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBackgroundView:)];
    [self.vBackground addGestureRecognizer:tapGesture];
}

- (void)onClickBackgroundView:(UITapGestureRecognizer *)tapGesture{
    [_searchBar.tfSearch resignFirstResponder];
    _searchBar.tfSearch.text = nil;
    self.vBackground.hidden = YES;
    [_searchBar stopSearch];
}

//点击婴儿
- (IBAction)onClickBabyBtn:(id)sender {
    if([TestModel isEqualToString:@"YES"]){
        KWMSelectedGoodsVC * selectedGoodsVC = (KWMSelectedGoodsVC *)[KWMBaseVC findControllerBy:[KWMSelectedGoodsVC kwmTag] fromStoryboard:@"New"];
        [self.navigationController pushViewController:selectedGoodsVC animated:YES];
        return;
    }
    [self JumpToNewSelectedVCWith:self.btnBaby.titleLabel.text type:0];
}
//点击女孩
- (IBAction)onClickGirlBtn:(id)sender {
    [self JumpToNewSelectedVCWith:self.btnGirl.titleLabel.text type:1];
}
//点击男孩
- (IBAction)onClickBoyBtn:(id)sender {
    [self JumpToNewSelectedVCWith:self.btnBoy.titleLabel.text type:2];
}
//点击鞋类
- (IBAction)onClickShoesBtn:(id)sender {
    [self JumpToNewSelectedVCWith:self.btnShoes.titleLabel.text type:3];
}

- (void)JumpToNewSelectedVCWith:(NSString *)title type:(NSInteger)type{
    KWMNewTypeSelectedVC *newTypeSelectedVC = (KWMNewTypeSelectedVC*)[KWMBaseVC findControllerBy:[KWMNewTypeSelectedVC kwmTag] fromStoryboard:@"New"];
    newTypeSelectedVC.navTitle = title;
    newTypeSelectedVC.pageType = type;
    [self.navigationController pushViewController:newTypeSelectedVC animated:YES];
}

//点击新品
- (IBAction)onClickNewGoodsBtn:(id)sender {
    if (!isNew) {
        isNew = YES;
        if (!newCollections || newCollections.count == 0) {
            [self requestNewProductsCollection];
        }else{
            collections = newCollections;
            [self.tbvNewGoods reloadData];
        }
    }
    self.btnNewGoods.selected = YES;
    self.btnDiscount.selected = NO;
    self.btnDiscount.backgroundColor = [UIColor clearColor];
    self.btnNewGoods.backgroundColor =  [UIColor sam_colorWithHex:@"F88C99"];
}
//点击打折
- (IBAction)onClickDiscountBtn:(id)sender {
    if (isNew) {
        isNew = NO;
        if (!discountCollections || discountCollections.count == 0) {
            collections = [NSArray array];
            [self requestDiscountCollection];
        }else{
            collections = discountCollections;
            [self.tbvNewGoods reloadData];
        }
    }
    self.btnDiscount.selected = YES;
    self.btnNewGoods.selected = NO;
    self.btnDiscount.backgroundColor =  [UIColor sam_colorWithHex:@"F88C99"];
    self.btnNewGoods.backgroundColor = [UIColor clearColor];
    
}

#pragma mark -- KWMTBVSectionHeardViewDelegate
- (void)kwm_watchMoreProductsByBrand:(KWMNewGoodsModel *)goodsModel AndTitle:(NSString *)titel{
    KWMBrandCaramelVC *brandVC = (KWMBrandCaramelVC *)[KWMBrandCaramelVC findControllerBy:[KWMBrandCaramelVC kwmTag] fromStoryboard:@"Brand"];
    brandVC.brand = titel;
    brandVC.goodModel = goodsModel;
    brandVC.isSale = !isNew;
    
    [self.navigationController pushViewController:brandVC animated:YES];
}

#pragma mark -- KWMSearchBarDelegate
- (void)kwm_tfSearchBeginEditing{
    self.vBackground.hidden = NO;
}

- (void)kwm_onCancel{
    self.vBackground.hidden = YES;
}

- (void)kwm_tfSearchFinished:(NSString *)text{
    if ([text isEqualToString:@""] || text == nil) {
        [self showToast:@"请输入需要搜索的内容"];
        return;
    }
    KWMSearchFeedbackVC *searchFBVC = (KWMSearchFeedbackVC *)[KWMBaseVC findControllerBy:[KWMSearchFeedbackVC kwmTag] fromStoryboard:@"New"];
    searchFBVC.searchText = text;
    [self.navigationController pushViewController:searchFBVC animated:YES];
}

- (void)kwm_onClickShopCar{
    
    KWMShopCartVC *contactVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:contactVC animated:YES];
    
}

#pragma mark -- KWMNewGoodsCellDelegate
- (void)kwm_selectCollectionCell:(BUYProduct *)product{
    if (product == nil) {
        return;
    }
    KWMProductDetailVC *goodsDetailvc = (KWMProductDetailVC *)[KWMBaseVC findControllerBy:[KWMProductDetailVC kwmTag] fromStoryboard:@"New"];
    goodsDetailvc.product = product;
    [self.navigationController pushViewController:goodsDetailvc animated:YES];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return collections?collections.count:0 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    KWMNewGoodsCell *newGoodsCell = [tableView dequeueReusableCellWithIdentifier:idStr forIndexPath:indexPath];
//    if(!newGoodsCell){
//        [tableView registerNib:[UINib nibWithNibName:idStr bundle:nil] forCellReuseIdentifier:idStr];
//        newGoodsCell = [tableView dequeueReusableCellWithIdentifier:idStr forIndexPath:indexPath];
//    }
    newGoodsCell.isDetail = NO;
    newGoodsCell.delegate = self;
    
    if(!collections || collections.count <= indexPath.section){
        return newGoodsCell;
    }
    KWMNewGoodsModel *goodsModel = [collections objectAtIndex:indexPath.section];
    if(!goodsModel){
        return newGoodsCell;
    }
    NSString *row = @(indexPath.section).stringValue;
    NSMutableDictionary *selectDict = isNew?newsDict:discountDic;
    KWMLoadStatus *loadStatus = [selectDict objectForKey:row];
    if (!loadStatus) {
        loadStatus = [[KWMLoadStatus alloc] init];
        [selectDict setObject:loadStatus forKey:row];
        //設置緩存數據
        loadStatus.cacheData = [self.userDao getCollectionCache:goodsModel.id tags:isNew?nil:[NSArray arrayWithObjects:@"sale", nil]];
    }
    //如果该行未拿到数据(包括空数据),向服务器请求数据
    if (!loadStatus.firstLoad && !loadStatus.isLoading) {
        [self requesProductList:BUYCollectionSortCreatedDescending WithCollectionId:goodsModel.id AndIndex:row];
    }
    [newGoodsCell setLoadStatusData:loadStatus];
    return newGoodsCell;
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *row = @(indexPath.section).stringValue;
    KWMLoadStatus *loadStatus = isNew ? [newsDict objectForKey:row]:[discountDic objectForKey:row];
    return [self isEmptyCollection:loadStatus]? 0.01f:173.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NSString *row = @(section).stringValue;
    KWMNewGoodsModel *goodsModel = [collections objectAtIndex:section];
    KWMTBVSectionHeardView * vTBVSectionHeard = [[KWMTBVSectionHeardView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 60)];
    vTBVSectionHeard.goodsModel = goodsModel;
    vTBVSectionHeard.delegate = self;
    vTBVSectionHeard.clipsToBounds = YES;
    vTBVSectionHeard.backgroundColor = [UIColor whiteColor];
    KWMLoadStatus *loadStatus = isNew ? [newsDict objectForKey:row]:[discountDic objectForKey:row];
    //判断该collection是否有数据来隐藏头部,如果第一次请求成功且并没有请求到数据
    vTBVSectionHeard.hidden = [self isEmptyCollection:loadStatus];
    return vTBVSectionHeard;
}

//判斷該collection是否為空
- (BOOL)isEmptyCollection:(KWMLoadStatus *)loadStatus{
    if(!loadStatus){
        return NO;
    }
    return (loadStatus.firstLoad && (!loadStatus.data || loadStatus.data.count == 0));
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    NSString * row = @(section).stringValue;
    KWMLoadStatus *loadStatus = isNew ? [newsDict objectForKey:row]:[discountDic objectForKey:row];
    return [self isEmptyCollection:loadStatus]? 0.01f:60.0f;
    return 60.0f;
}

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

//请求新品collection列表
- (void)requestNewProductsCollection{
    BOOL mIsNew = isNew;
    __weak KWMNewVC *weakSelf = self;
    [self.api getNewProducts:nil success:^(NSURLSessionDataTask *task, KWMNewProducts *result) {
        [weakSelf hideLoading];
        newCollections = result.collections;
        if(mIsNew == isNew){
            collections = newCollections;
            [self.tbvNewGoods reloadData];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf showError:error];
        NSLog(@"error");
    }];
    [self showLoading];
}

//请求打折collection列表
- (void)requestDiscountCollection{
    BOOL mIsNew = isNew;
    __weak KWMNewVC *weakSelf = self;
    [self.api getDiscountProducts:nil success:^(NSURLSessionDataTask *task, KWMNewProducts *result) {
        [weakSelf hideLoading];
        [result setCollectionsTag];
        discountCollections = result.collections;
        if(mIsNew == isNew){
            collections = discountCollections;
            [self.tbvNewGoods reloadData];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self showError:error];
        NSLog(@"error");
    }];
    [self showLoading];
}

//请求product列表
- (void)requesProductList:(BUYCollectionSort)collectionSort WithCollectionId:(NSNumber *)identify AndIndex:(NSString *)keyStr{
    BOOL mIsNew = isNew;
    KWMLoadStatus *loadStatus = isNew ? [newsDict objectForKey:keyStr]:[discountDic objectForKey:keyStr];
    if(!loadStatus){
        return;
    }
    //设置该行状态为正在加载
    loadStatus.isLoading = YES;
    __weak KWMNewVC *weakSelf = self;
    NSInteger tagetPage = 1;
    NSArray *tags = nil;
    if(!isNew){
        NSString *tag;
        tag = @"sale";
        tags = [NSArray arrayWithObjects:tag, nil];
    }
    [self.client getProductsPage:tagetPage inCollection:identify withTags:tags sortOrder:collectionSort completion:^(NSArray *products,NSUInteger page, BOOL reachedEnd, NSError *error){
        [weakSelf hideLoading];
        loadStatus.isLoading = NO;
        if (error == nil && products) {
            if(tagetPage == 1){
                [weakSelf.userDao saveCollectionCache:products collectionId:identify tags:tags];
            }
            weakSelf.hasNextPage = !reachedEnd;
            loadStatus.data = products;
            //设置第一次加载的状态为已成功加载
            loadStatus.firstLoad = YES;
            if(mIsNew == isNew ){
                if([KWMStringUtil isEmpty:keyStr]){
                    return ;
                }
                NSInteger section = keyStr.integerValue;
                if(section < (collections?collections.count:0)){
                                   [weakSelf.tbvNewGoods reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
                }
            }
        }else {
            [self showError:error];
            NSLog(@"Error fetching products: %@", error);
        }
    }];
    [self showLoading];
}



@end