//
//  KWMNewHomeVC.m
//  iCemarose
//
//  Created by HouWeiBin on 2017/7/10.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMNewHomeVC.h"
#import "KWMShopCartVC.h"
#import "KWMSearchFeedbackVC.h"
#import "KWMNewHomeCell.h"
#import "KWMSearchBar.h"
#import "KWMHomeData.h"
#import "KWMShoppingCart.h"
#import <RegexKitLite/RegexKitLite.h>
#import <RXCollections/RXCollection.h>
#import "KWMHomeVC.h"
#import "KWMWishListVC.h"
#import <MJRefresh.h>
#import "KWMStringUtil.h"

typedef enum{
    
    HeaderAd=0,
    
    HeaderMenu=1,
    
    HeaderRecommend=2,
    
    HeaderClothingSets=3,

    HeaderHotSales=4,
    
}Header;


@interface KWMNewHomeVC ()

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

@property(nonatomic,strong) KWMAdHeader *adHeader;

@property(nonatomic,strong) KWMMenuHeader *menuHeader;

@property(nonatomic,strong) KWMRecommendHeader *recommendHeader;

@property(nonatomic,strong) KWMClothingSetsHeader *clothingSetsHeader;

@property(nonatomic,strong) KWMHotSalesHeader *hotSalesHeader;

@property(nonatomic,strong) KWMSearchBar *titleView;

@property(nonatomic) KWMHomeData *homeData;

@property(nonatomic) NSInteger page;

@property(nonatomic) NSMutableArray<BUYProduct *>* productArray;

@property(nonatomic) NSMutableDictionary *dataMapping;

//@property(nonatomic) NSString *clotingSetsHandle;

@end

@implementation KWMNewHomeVC{
    CGFloat heightAdHeader;
    CGFloat heightClothingSets;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    self.page = 1;
//    [self requestProduct:@""];
    [self loadHomeData];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    if (self.titleView) {
        NSInteger count = [[KWMShoppingCart sharedInstance] count].integerValue;
        self.titleView.count = count;
        [self.titleView resumeView];
    }
    [self.cvHome reloadData];
}

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


- (void)initView{
//    self.title = @"首页";
    heightAdHeader = UI_SCREEN_WIDTH * 275 / 375;
    heightClothingSets = UI_SCREEN_WIDTH * 190 / 375 + 127; //127为图片外的布局高度
    self.adHeader = [[KWMAdHeader alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, heightAdHeader)];
    self.menuHeader = [[KWMMenuHeader alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 100)];
    self.recommendHeader = [[KWMRecommendHeader alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 230)];
    self.clothingSetsHeader = [[KWMClothingSetsHeader alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, heightClothingSets)];
    self.hotSalesHeader = [[KWMHotSalesHeader alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 250)];
    
    self.adHeader.delegate = self;
    self.menuHeader.delegate = self;
    self.recommendHeader.delegate = self;
    self.clothingSetsHeader.delegate = self;
    self.hotSalesHeader.delegate = self;
    
    [self initTitleView];
    [self initCollectionView];
}

-(void)initTitleView{
    self.titleView = [[KWMSearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    self.titleView.delegate = self;
    self.titleView.btnSearch.hidden = NO;
    [self.view addSubview:self.titleView];
}

- (void)initCollectionView{
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumColumnSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    layout.columnCount = 2;
    self.cvHome.collectionViewLayout = layout;
    
    [self.cvHome registerNib:[UINib nibWithNibName:NSStringFromClass([KWMNewHomeCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([KWMNewHomeCell class])];
    
    [self.cvHome registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMAdHeader kwmTag]];
    [self.cvHome registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMHotSalesHeader kwmTag]];
    [self.cvHome registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMRecommendHeader kwmTag]];
    [self.cvHome registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMClothingSetsHeader kwmTag]];
    [self.cvHome registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMMenuHeader kwmTag]];
    
    MJRefreshAutoNormalFooter *refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    [refreshFooter setTitle:NO_MORE_DATA forState:MJRefreshStateNoMoreData];
    self.cvHome.mj_footer = refreshFooter;
}

- (void) loadMore {
    [self requestProductWithHandle:@"products-list-app-homepage" tags:nil valueKeyPath:@"productArray"];
}

#pragma mark - KWMAdDelegate
-(void)kwm_gotoWebView:(NSString *)url{
    if (![KWMStringUtil isBlank:url]) {
        [self openURLWithString:url];
    }
}

#pragma mark - KWMMenuDelegate
-(void)kwm_onClickHotMenu{
    if([TestModel isEqualToString:@"YES"]){
        [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/products/%@",@"17618-01"]];
    }else{
        [self openURLWithString:@"https://cemarose.myshopify.com/collections/new?title=最新单品"];
    }
}

-(void)kwm_onClickNewMenu{
    KWMHomeVC* selectedGoodsVC = (KWMHomeVC *)[KWMBaseVC findControllerBy:[KWMHomeVC kwmTag] fromStoryboard:@"Main"];
    [self.navigationController pushViewController:selectedGoodsVC animated:YES];
}

-(void)kwm_onClickWishMenu{
    NSLog(@"wishmenu");
    if(![self checkLogin]){
        return;
    }
    KWMWishListVC* vc= (KWMWishListVC *)[KWMBaseVC findControllerBy:[KWMWishListVC kwmTag] fromStoryboard:@"NewProduct"];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)kwm_onClickDeliveryMenu{
    NSLog(@"deliverymenu");
    [self openURLWithString:@"https://www.cemarose.com/pages/service-description/?title=服务说明"];
}

#pragma mark - KWMRecommendDelegate
-(void)kwm_gotoRecommendPage{
    [self openURLWithString:@"https://cemarose.myshopify.com/collections/hot-sell-app?title=主推单品"];
}

-(void)kwm_onClickHotSalesAd:(KWMAdvertisement *)ad {
    if (![KWMStringUtil isBlank:ad.url]) {
        [self openURLWithString:ad.url];
    }
}

-(void)kwm_onClickFocusImage {
    if (![KWMStringUtil isBlank:self.homeData.clothing_sets.action]) {
        [self openURLWithString:self.homeData.clothing_sets.action];
    }
}

-(void)kwm_gotoClothingSetsPage{
//    [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/collections/%@",self.clotingSetsHandle]];
    if (![KWMStringUtil isBlank:self.homeData.clothing_sets.url]) {
        [self openURLWithString:self.homeData.clothing_sets.url];
    }
}

#pragma mark - KWMRecommendDelegate KWMClothingSetsDelegate KWMHotSalesDelegate
-(void)kwm_onClickProduct:(BUYProduct *)product{
//    NSLog(@"product");
    [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/products/%@",product.handle]];
//    [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/products/19247-01"]];
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 5;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == HeaderHotSales){
        return self.productArray ? self.productArray.count:0;
    }
    return 0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KWMNewHomeCell *homeCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([KWMNewHomeCell class]) forIndexPath:indexPath];
    BUYProduct *product = [self.productArray objectAtIndex:indexPath.row];
    homeCell.product = product;
    return homeCell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *headerView;
    if (kind == CHTCollectionElementKindSectionHeader) {
        switch (indexPath.section) {
            case HeaderAd:
                headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMAdHeader kwmTag] forIndexPath:indexPath];
                if(headerView.subviews.count == 0){
                    [headerView addSubview:self.adHeader];
                }
                break;
            case HeaderMenu:
                headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMMenuHeader kwmTag] forIndexPath:indexPath];
                if(headerView.subviews.count == 0){
                    [headerView addSubview:self.menuHeader];
                }
                break;
            case HeaderRecommend:
                headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMRecommendHeader kwmTag] forIndexPath:indexPath];
                if(headerView.subviews.count == 0){
                    [headerView addSubview:self.recommendHeader];
                }
                break;
            case HeaderClothingSets:
                headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMClothingSetsHeader kwmTag] forIndexPath:indexPath];
                if(headerView.subviews.count == 0){
                    [headerView addSubview:self.clothingSetsHeader];
                }
                break;
            case HeaderHotSales:
                headerView = [collectionView dequeueReusableSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:[KWMHotSalesHeader kwmTag] forIndexPath:indexPath];
                if(headerView.subviews.count == 0){
                    [headerView addSubview:self.hotSalesHeader];
                }
                break;
            default:
                break;
        }
    }
    return headerView;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForHeaderInSection:(NSInteger)section{
    NSInteger height = 0;
    switch (section) {
        case HeaderAd:
            height = heightAdHeader;
            break;
        case HeaderMenu:
            height = 100;
            break;
        case HeaderRecommend:
            height = 230;
            break;
        case HeaderClothingSets:
            height = heightClothingSets;
            break;
        case HeaderHotSales:
            height = self.hotSalesHeader.actrualHeight;
            break;
        default:
            break;
    }
    return height;
}

#pragma mark - CHTCollectionViewDelegateWaterfallLayout
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self kwm_onClickProduct:self.productArray[indexPath.item]];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    BUYProduct *product = [self.productArray objectAtIndex:indexPath.row];
    NSInteger width = (UI_SCREEN_WIDTH-30)/2;
    NSInteger height = [KWMNewHomeCell acturlHeight:product width:width];
    CGSize size = CGSizeMake(width, height);
    return size;
}

#pragma mark - KWMSearchBarDelegate
- (void)kwm_onClickShopCar{
    //购物车
    KWMShopCartVC *contactVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:contactVC animated:YES];
}

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

#pragma makr - api
//- (void)requestProduct:(NSString *)tag{
//    NSMutableArray *tags = nil;
//    if(tag){
//        tags = [NSMutableArray array];
//        [tags addObject:tag];
//    }
//    
//    __weak KWMNewHomeVC *weakSelf = self;
//    [self showLoading];
//    [self.client getProductsPage:1 inCollection:@(Collection_All_ID) withTags:tags sortOrder:BUYCollectionSortBestSelling completion:^(NSArray *products,NSUInteger page, BOOL reachedEnd, NSError *error){
//        [weakSelf hideLoading];
//        if(error){
//            [weakSelf showError:error];
//        }
//        else if(products && products.count>0){
//            weakSelf.productArray = products;
//            [weakSelf.cvHome reloadData];
////            [weakSelf initTestData];
//        }
//    }];    
//}

- (void) requestProductWithHandle:(NSString *) handle tags:(NSArray *) tags valueKeyPath:(NSString *) valueKeyPath {
    [self showLoading];
    BOOL isHome = [handle isEqualToString:@"products-list-app-homepage"];
    NSInteger cpage = isHome ? self.page : 1;
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if (!error) {
            [self.client getProductsPage:cpage inCollection:collection.identifier withTags:tags sortOrder:BUYCollectionSortCollectionDefault completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
                [self hideLoading];
                
                if (!error) {
                    [self setValue:products forKeyPath:valueKeyPath];
                    [self.cvHome reloadData];
                }else{
                    [self showError:error];
                }
                if (isHome) {
                    self.page = self.page + 1;
                    products.count ? [self.cvHome.mj_footer endRefreshing] : [self.cvHome.mj_footer endRefreshingWithNoMoreData];
                }
            }];
        }else{
            [self hideLoading];
            [self showError:error];
        }
    }];
}

//- (void) requestProductWithId:(NSNumber *) identifier tags:(NSArray *) tags valueKeyPath:(NSString *) valueKeyPath home:(BOOL) isHome page:(NSInteger) cpage{
//    [self showLoading];
//    [self.client getProductsPage:cpage inCollection:identifier withTags:tags sortOrder:BUYCollectionSortCollectionDefault completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
//        [self hideLoading];
//        
//        if (!error) {
//            [self setValue:products forKeyPath:valueKeyPath];
//            [self.cvHome reloadData];
//        }else{
//            [self showError:error];
//        }
//        if (isHome) {
//            self.page = self.page + 1;
//            products.count ? [self.cvHome.mj_footer endRefreshing] : [self.cvHome.mj_footer endRefreshingWithNoMoreData];
//        }
//    }];
//}

- (void) loadHomeData {
    [self requestProductWithHandle:@"hot-sell-app" tags:nil valueKeyPath:@"recommendHeader.productArray"];
    [self.api getHomeDataWithSuccess:^(NSURLSessionDataTask *task, KWMHomeDataResult *result) {
        self.homeData = result.data;
        [self.cvHome reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self showError:error];
    }];
}

- (void)setHomeData:(KWMHomeData *)homeData {
    _homeData = homeData;
//#if DEBUG
//    [self.homeData.ad_banner[0] setUrl:@"https://www.cemarose.com/pages/sale_test_111"];
//#endif
//    [self.homeData.ad_banner[0] setUrl:@"https://www.cemarose.cn/collections/skirts/girls"];
    self.adHeader.adArray = self.homeData.ad_banner;
    self.hotSalesHeader.bannerArray = self.homeData.hot_sales_ads;
//    self.homeData.hot_sales.single_show_count = @(1);
    self.clothingSetsHeader.headerImage = self.homeData.clothing_sets.image;
//    self.homeData.clothing_sets.url =@"https://www.cemarose.cn/collections/skirts/girls+spring-summer-2016?title=ml";
    NSURL *url = [[NSURL alloc] initWithString:self.homeData.clothing_sets.url];
    NSArray *clothingParam = [url.path arrayOfCaptureComponentsMatchedByRegex:@"collections\\/([^/]*+)\\/?(.*)$"];
    if (clothingParam.count) {
        clothingParam = clothingParam.firstObject;
        NSString *handle = clothingParam.count > 1 ? clothingParam[1] : nil;
        NSArray *tags = clothingParam.count > 2 ? [clothingParam[2] componentsSeparatedByString:@"+"] : nil;
        if (handle) {
//            self.clotingSetsHandle = handle;
            [self requestProductWithHandle:handle tags:tags valueKeyPath:@"clothingSetsHeader.productArray"];
        }
    }
    [self requestProductWithHandle:@"products-list-app-homepage" tags:nil valueKeyPath:@"productArray"];
}

- (void)setProductArray:(NSArray<BUYProduct *> *)productArray {
    if (!_productArray) {
        NSInteger ssize = self.homeData.hot_sales.single_show_count.integerValue;
        NSInteger count = productArray.count;
        self.hotSalesHeader.singleShowArray = count <= ssize ? productArray : [productArray subarrayWithRange:NSMakeRange(0, ssize)];
        _productArray = [[NSMutableArray alloc] init];
//        [_productArray addObjectsFromArray:[productArray subarrayWithRange:NSMakeRange(self.homeData.hot_sales.single_show_count.integerValue, 99)]];
        if (count > ssize) {
        [_productArray addObjectsFromArray:[productArray subarrayWithRange:NSMakeRange(ssize, count - ssize)]];
        }
    }else{
        [_productArray addObjectsFromArray:productArray];
    }
//    _productArray = productArray;
    
}

@end