KWMNewVC.m 15.8 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10
//
//  KWMNewVC.m
//  iCemarose
//
//  Created by 陈荣科 on 16/8/23.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMNewVC.h"
#import "KWMStringUtil.h"
houweibin committed
11
#import "KWMSelectedGoodsVC.h"
houweibin committed
12 13 14 15 16 17 18 19 20 21
#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"
lee committed
22
#import "KWMShoppingCart.h"
lee committed
23
#import <RXCollections/RXCollection.h>
houweibin committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65


@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];
lee committed
66

houweibin committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
}

- (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) {
lee committed
99 100
        NSInteger count = [[KWMShoppingCart sharedInstance] count].integerValue;
        _searchBar.count = count;
houweibin committed
101 102 103
    }
    [_searchBar resumeView];
    _vBackground.hidden = YES;
lee committed
104
    [self.tbvNewGoods reloadData];
houweibin committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}
- (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"]){
houweibin committed
176 177 178 179 180 181 182 183 184
        KWMSelectedGoodsVC * selectedGoodsVC = (KWMSelectedGoodsVC *)[KWMBaseVC findControllerBy:[KWMSelectedGoodsVC kwmTag] fromStoryboard:@"New"];
        BUYCollection *collection = [BUYCollection new];
        collection.identifier = @(441199887);
        selectedGoodsVC.collection = collection;
        [self.navigationController pushViewController:selectedGoodsVC animated:YES];
//        KWMProductDetailVC *vc = (KWMProductDetailVC *)[KWMBaseVC findControllerBy:[KWMProductDetailVC kwmTag] fromStoryboard:@"New"];
//        vc.productId = @(11406082255);
//        [self.navigationController pushViewController:vc animated:YES];
        
houweibin committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        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;
lee committed
431 432 433
        products = [products rx_filterWithBlock:^BOOL(BUYProduct *each) {
            return each.availableValue;
        }];
houweibin committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        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