//
//  ProductLibraryViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/5/4.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ProductLibraryViewController.h"
#import "ProductCollectionViewCell.h"
#import "ProductDetailsViewController.h"
#import "ScreeningView.h"
#import "screeningFirstView.h"
#import "screeningSecondView.h"
#import "ExperienceCentreViewController.h"


@interface ProductLibraryViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate,ScreeningButtonClickdelegate,TableviewSelectedIndexdelegate,SelectedCollectionItemDelegate,CAAnimationDelegate>

/**
 *  筛选背景框View
 */
@property (nonatomic,strong) ScreeningView *screenView;

/**
 *  分类View
 */
@property (nonatomic,strong) screeningFirstView *screenFirstView;

/**
 *  筛选View
 */
@property (nonatomic,strong) screeningSecondView *screenSecondView;

/**
 *  筛选数据源
 */
@property (nonatomic,strong) NSMutableArray *screeningDatas;

/**
 *  当前筛选按钮选中状态
 */
@property (nonatomic,assign) NSInteger selectedIndex;

/**
 *  商品数据源对象
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 *  复选返回时临时保存数据
 */
@property (nonatomic,strong) GoodsResponse *temporaryArray;

/**
 *  搜索结果个数
 */
@property (nonatomic,assign) int resultCount;


@end

@implementation ProductLibraryViewController

/**
 *  初始化筛选数据源
 */
- (NSMutableArray *)screeningDatas
{
    if (_screeningDatas == nil) {
        
        _screeningDatas = [NSMutableArray array];
    }
    return _screeningDatas;
}


/**
 *  初始化商品数据源数组
 */
- (NSMutableArray *)datasArray
{
    if (_datasArray == nil) {
        
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}


/**
 *  初始化复选模型
 */
- (GoodsCondition *)condtionModel
{
    if (!_condtionModel) {
        _condtionModel = [[GoodsCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _condtionModel.page = page;
    }
    return _condtionModel;
}

#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getFiltrateData];
}

#pragma mark -布局
- (void)uiConfigAction
{
    self.selectedIndex = 9999;//无任何意义
    self.productCollectionLayout.itemSize = CGSizeMake((ScreenWidth-100)/3, (ScreenWidth-100)/3);
    self.productCollectionLayout.sectionInset = UIEdgeInsetsMake(20, 30, 20, 30);
    self.productCollectionLayout.minimumLineSpacing = 20;
    self.productCollectionLayout.minimumInteritemSpacing = 20;
    [self createScreeningButton];
}

#pragma mark -上、下拉加载数据 （获取商品）
- (void)loadWebDataSource
{
    WS(weakSelf);
    //扫描二维码结果
    if (![[self class] isBlankString:self.barcode]) {
        [self barCodeSearchRequest];
    }else
    {
        if (![[self class] isBlankString:self.selectedCode]) {
            switch (weakSelf.selectedIndex) {
                case 0://类型
                {
                    weakSelf.condtionModel.categoryEquals = weakSelf.selectedCode;
                }
                    break;
                case 1://风格
                {
                    weakSelf.condtionModel.styleEquals = weakSelf.selectedCode;
                }
                    break;
                case 2://空间
                {
                    weakSelf.condtionModel.spaceEquals = weakSelf.selectedCode;
                }
                    break;
                case 3://材质
                {
                    weakSelf.condtionModel.materialEqueals = weakSelf.selectedCode;
                }
                    break;
                case 4://价格
                {
                    //价格字符串切割
                    NSArray *spacrArray = [weakSelf.selectedCode componentsSeparatedByString:@"到"];
                    weakSelf.condtionModel.startprice = (NSDecimalNumber *)[NSDecimalNumber numberWithInteger:[[spacrArray objectAtIndex_opple:0] integerValue]];
                    weakSelf.condtionModel.endprice = (NSDecimalNumber *)[NSDecimalNumber numberWithInteger:[[spacrArray objectAtIndex_opple:1] integerValue]];
                }
                    break;
                default:
                    weakSelf.condtionModel.nameLike = weakSelf.selectedCode;
                    break;
            }
        }
        if (self.pullPageIndex == ONE) {
            [self.datasArray removeAllObjects];
        }
        self.condtionModel.page.page = self.pullPageIndex;
        [self getGoodsListdatas:self.condtionModel completed:^(GoodsResponse *result) {
            if (weakSelf.pullPageIndex >= result.totalpages) {
                [weakSelf endRefresh:EndRefreshNotData];
            }else {
                [weakSelf endRefresh:EndRefreshDefault];
            }
        }];
    }
}


#pragma mark -获取产品筛选数据
- (void)getFiltrateData
{
  WS(weakSelf);
  [HTTP networkWithDictionaryRequestWithURL:SERVERREQUESTURL(PRODUCTSCREENING)  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
      if (RESULT(returnValue)) {
          [weakSelf.screeningDatas removeAllObjects];
          GoodsFilter *goodsStyle = [[GoodsFilter alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
          [weakSelf.screeningDatas addObject:goodsStyle.categories];
          [weakSelf.screeningDatas addObject:goodsStyle.styles];
          [weakSelf.screeningDatas addObject:goodsStyle.space];
          [weakSelf.screeningDatas addObject:goodsStyle.material];
          [weakSelf.screeningDatas addObject:goodsStyle.price];
    }else {
          [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
      }
      
  }withFailureBlock:^(NSError *error) {
      [XBLoadingView showHUDViewWithText:error.localizedDescription];
  }];
}


#pragma mark -获取商品列表数据
- (void)getGoodsListdatas:(GoodsCondition *)conditon completed:(void(^)(GoodsResponse *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(PRODUCTLIST)  withRequestType:ZERO withParameter:conditon withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            GoodsResponse *result = [[GoodsResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(result);
            for (TOGoodsEntity *model in result.goodsEntity) {
                [weakSelf.datasArray addObject:model];
            }
            [weakSelf.collectionView reloadData];
        }else {
           [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark 填条形码搜索
- (void)barCodeSearchRequest
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    NSString *urlString = [NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(BARCODESEARCH),self.barcode];
    [HTTP networkWithDictionaryRequestWithURL:[self returnUrlString:urlString]  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            if ([RESPONSE(returnValue) isKindOfClass:[NSNull class]]) {
                [XBLoadingView showHUDViewWithText:@"暂无商品信息"];
                return;
            }
            TOGoodsEntity *goods = [[TOGoodsEntity alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.datasArray removeAllObjects];
            [weakSelf.datasArray addObject:goods];
            [weakSelf.collectionView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:@"查询失败"];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -筛选按钮
- (void)createScreeningButton
{
    UIButton *screeningButton = [UIButton buttonWithType:UIButtonTypeSystem];
    screeningButton.frame = CGRectMake(ScreenWidth-100, ScreenHeight*6/10, 50, 50);
    //阴影层
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(ScreenWidth-97.5, ScreenHeight*6/10+2.5, 45, 45);//保证layer的size比筛选按钮高宽都短5像素
    layer.backgroundColor = [UIColor blackColor].CGColor;
    layer.shadowOffset = CGSizeMake(0, 8);
    layer.shadowOpacity = 0.7;
    layer.cornerRadius = 25;
    [self.view.layer addSublayer:layer];
    
    //筛选按钮
    screeningButton.layer.masksToBounds = YES;
    screeningButton.layer.cornerRadius = 25;
    [screeningButton setTitle:@"筛选" forState:UIControlStateNormal];
    screeningButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [screeningButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [screeningButton setTitleColor:kMainBlueColor forState:UIControlStateSelected];
    [screeningButton addTarget:self action:@selector(screeningButtonClick) forControlEvents:UIControlEventTouchUpInside];
    screeningButton.backgroundColor = kMainBlueColor;
    [self.view addSubview:screeningButton];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"productcell" forIndexPath:indexPath];
    TOGoodsEntity *model = [self.datasArray objectAtIndex_opple:indexPath.item];
    cell.model = model;
    cell.cellindex = indexPath.row;
    //加入购物车
    WS(weakSelf);
    __weak typeof(ProductCollectionViewCell *) weakCell = cell;
    [cell setReturnCellCgpoint:^void(CGPoint centerPoint,NSInteger cellindex ,CGSize size) {
        //判断是否有当前客户
        if (![Shoppersmanager manager].currentCustomer) {
            [XBLoadingView showHUDViewWithText:@"必须设置当前客户"];
            return;
        }
        //库存为0时不能加入购物车
        if (model.number == 0) {
            [XBLoadingView showHUDViewWithText:@"此商品库存不足"];
            return;
        }
        TOGoodsEntity *model = [weakSelf.datasArray objectAtIndex_opple:cellindex];
        [XBLoadingView showHUDViewWithDefault];
        [weakSelf addGoodsShoppingbags:model complate:^{
            [XBLoadingView hideHUDViewWithDefault];
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
            imageView.image = weakCell.productImageView.image;
            imageView.center = centerPoint;
            [weakSelf.view.window.layer addSublayer:imageView.layer];
            [imageView startAnimationWithEndPoint:SHARED_APPDELEGATE.shoppingCarPoint withControlPoint:CGPointMake(200, 200) animateWithDuration:ONE completed:^{
                [weakSelf queryShoppingCarNumber];
            }];
        }];
    }];
    return cell;
}

#pragma mark -动画完成后移除
- (void)removeFromLayer:(CALayer *)layerAnimation{
    
    [layerAnimation removeFromSuperlayer];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datasArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductDetailsViewController *productDetails = [ProductDetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    productDetails.goodsID = [[self.datasArray objectAtIndex_opple:indexPath.item] fid];
    [self pushViewController:productDetails animated:YES];
}


#pragma mark -筛选
- (void)screeningButtonClick
{
    self.screenView = [[[NSBundle mainBundle] loadNibNamed:@"ScreeningView" owner:self options:nil]firstObject];
    self.screenView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    self.screenView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    self.screenView.delegate = self;
    //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissScreenView)];
    tap.delegate = self;
    tap.cancelsTouchesInView = NO;
    [self.screenView addGestureRecognizer:tap];
    self.screenView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self.view.window addSubview:self.screenView];
    self.screenView.alpha = 0;
    //监听Segmented菜单
    [self.screenView.sortingSegmented addTarget:self action:@selector(sortingSegmentedClick:) forControlEvents:UIControlEventValueChanged];
    self.selectedIndex = 0;
    [self CreateClassificationView];
    [UIView animateWithDuration:0.2 animations:^{
        self.screenView.alpha = 1;
    }];
}


#pragma mark -分类、筛选view切换
- (void)sortingSegmentedClick:(UISegmentedControl *)sender {
    
    switch (sender.selectedSegmentIndex) {
        case 0://分类
        {
            [self.screenSecondView removeFromSuperview];
            [self CreateClassificationView];
        }
            break;
        case 1://筛选
        {
            [self.screenFirstView removeFromSuperview];
            [self CreateScreenSubView];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -创建分类View
- (void)CreateClassificationView
{
    //分类View
    self.screenFirstView = [[[NSBundle mainBundle] loadNibNamed:@"screeningFirstView" owner:self options:nil] firstObject];
    self.screenFirstView.frame = CGRectMake(0, 50, 470, 310);
    self.screenFirstView.delegate = self;
    [self screeningButtonClick:self.selectedIndex];
    [self.screenView.backgroundView addSubview:self.screenFirstView];
}


#pragma mark -创建筛选选项View
- (void)CreateScreenSubView
{
    self.screenSecondView = [[[NSBundle mainBundle] loadNibNamed:@"screeningSecondView" owner:self options:nil] firstObject];
    self.screenSecondView.frame = CGRectMake(0, 50, 470, 310);
    self.screenSecondView.delegate = self;
    [self screeningButtonClick:self.selectedIndex];
    self.screenSecondView.totalNumber = self.datasArray.count;
    [self.screenView.backgroundView addSubview:self.screenSecondView];
}


#pragma mark -screeningButtonClickdelegate代理
- (void)screeningButtonClick:(NSInteger)buttontag
{
    self.selectedIndex = buttontag;
    //分类
    if (self.screenView.sortingSegmented.selectedSegmentIndex == 0) {
        self.screenFirstView.selectedIndex = buttontag;
        self.screenFirstView.datasArray = [self.screeningDatas objectAtIndex_opple:buttontag];
    }
    //筛选
    else if (self.screenView.sortingSegmented.selectedSegmentIndex == 1)
    {
        self.screenSecondView.selectedIndex = buttontag;
        self.screenSecondView.datasArray = [self.screeningDatas objectAtIndex_opple:buttontag];
    }
}

#pragma mark -选中条件
- (void)selectedItem:(NSString *)typecode withTitle:(NSString *)title
{
    [self emptyModel];

    [self dismissScreenView];
    if (self.selectedIndex == 4) {
        self.selectedCode = title;
    }else
    {
      self.selectedCode = typecode;
    }
    [self.collectionView.mj_header beginRefreshing];
}


#pragma mark -筛选子模块的
- (void)tableSelectedindex:(NSInteger)index
{
    
    [self screeningButtonClick:index];
    self.screenView.indexselected = index;
    
}


#pragma mark -筛选复选模块选中的uicollection cell
- (void)collectionSelectedindexWithStyleCode:(NSString *)styleCode
                              withCategories:(NSString *)categoriesCode
                                   withSpace:(NSString *)spaceCode
                                withMaterial:(NSString *)materialCode
                                   withPrice:(NSString *)priceTitle
{
    
    GoodsCondition *condition = [[GoodsCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.rows = 10;
    page.page = 1;
    condition.page = page;
    if (![[self class] isBlankString:styleCode]) {
       condition.styleEquals = styleCode;
    }
    if (![[self class] isBlankString:categoriesCode]) {
       condition.categoryEquals = categoriesCode;
    }
    if (![[self class] isBlankString:spaceCode]) {
        condition.spaceEquals = spaceCode;
    }
    if (![[self class] isBlankString:materialCode]) {
        condition.materialEqueals = materialCode;
    }
    if (![priceTitle isEqualToString:@"全部"]) {
        //价格字符串切割
        NSArray *spacrArray = [priceTitle componentsSeparatedByString:@"到"];
        condition.startprice = (NSDecimalNumber *)[NSDecimalNumber numberWithInteger:[[spacrArray objectAtIndex_opple:0] integerValue]];
        condition.endprice = (NSDecimalNumber *)[NSDecimalNumber numberWithInteger:[[spacrArray objectAtIndex_opple:1] integerValue]];
    }
    self.condtionModel.styleEquals = condition.styleEquals;
    self.condtionModel.categoryEquals = condition.categoryEquals;
    self.condtionModel.spaceEquals = condition.spaceEquals;
    self.condtionModel.materialEqueals = condition.materialEqueals;
    self.condtionModel.startprice = condition.startprice;
    self.condtionModel.endprice = condition.endprice;
    self.selectedCode = nil;//清空单选
    WS(weakSelf);
    [self getGoodsListdatas:condition completed:^(GoodsResponse *result) {
        weakSelf.screenSecondView.totalNumber = result.total;
        //临时保存
        weakSelf.temporaryArray = result;
    }];
}


#pragma mark -显示筛选后的结果
- (void)showScreeningResponse
{
    if (self.temporaryArray.goodsEntity.count == 0) {
        [XBLoadingView showHUDViewWithText:@"暂无数据"];
    }else {
        self.datasArray = [NSMutableArray arrayWithArray:self.temporaryArray.goodsEntity];
        [self.collectionView reloadData];
        [self dismissScreenView];
    }
}


#pragma mark -移除筛选框
- (void)dismissScreenView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.screenView.alpha = 0;
    }completion:^(BOOL finished) {
        [self.screenView removeFromSuperview];
    }];
}


#pragma mark -UIGestureRecognizerDelegate代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    //取消子视图的的时间穿透，否则子视图的点击无效，会被传递到父视图响应
    if (CGRectContainsPoint(self.screenView.backgroundView.frame, [touch locationInView:self.screenView])) {
        return NO;
    }
    return YES;
}


#pragma mark -添加至购物车
- (void)addGoodsShoppingbags:(TOGoodsEntity *)model complate:(void(^)())response
{
    SaveShoppingCartRequest *shopCar = [[SaveShoppingCartRequest alloc]init];
    shopCar.consumerId = [Customermanager manager].model.consumer.fid;
    shopCar.goodsId = model.fid;
    shopCar.count = @"1";
    shopCar.attachmentUrl = @"";
    [HTTP networkRequestWithURL:SERVERREQUESTURL(ADDSHOPPINGBAG)  withRequestType:ZERO withParameter:shopCar withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            response();
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(id error) {
        [XBLoadingView hideHUDViewWithDefault];
        [XBLoadingView showHUDViewWithText:@"加入购物车失败"];
    }];
}

#pragma mark -清空模型
- (void)emptyModel
{
    self.condtionModel.nameLike = nil;
    self.condtionModel.styleEquals = nil;
    self.condtionModel.spaceEquals = nil;
    self.condtionModel.categoryEquals = nil;
    self.condtionModel.startprice = nil;
    self.condtionModel.endprice = nil;
    self.condtionModel.materialEqueals = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearDisk];
    NSLog(@"结算到内存警告");
    // Dispose of any resources that can be recreated.
}

@end
