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

#import "SceneViewController.h"
#import "ScreeningTableViewCell.h"
#import "ScreeningCollectionViewCell.h"
#import "SceneSectionHeaderView.h"
#import "SceneListModel.h"
#import "DataDictModel.h"
#import "TOGoodsEntityModel.h"
#import "ProductScreeningCollectionViewCell.h"
#import "GoodsCategoryModel.h"

@interface SceneViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,DZNEmptyDataSetSource,UITextFieldDelegate>

/**
 *  场景数据源
 */
@property (nonatomic,strong) NSMutableArray *sceneDatasArray;

/**
 *  产品数据源
 */
@property (nonatomic,strong) NSMutableArray *productDatasArray;

/**
 *  当前页数
 */
@property (nonatomic,assign) int indexPage;

/**
 *  总页数
 */
@property (nonatomic,assign) int totalPages;


/**
 *  场景参数模型
 */
@property (nonatomic,strong) SceneCondition *conditionModel;

/**
 *  产品参数模型
 */
@property (nonatomic,strong) GoodsCondition *goodsModel;

/**
 *  场景筛选条件数据源
 */
@property (nonatomic,strong) NSMutableArray *sceneScreeningDatasArray;

/**
 *  产品筛选条件数据源
 */
@property (nonatomic,strong) NSMutableArray *productScreeningDatasArray;


/**
 *  右侧筛选条件选中下标
 */
@property (nonatomic,assign) NSInteger rightSelectedIndex;

/**
 *  区分场景和产品
 */
@property (nonatomic,assign) BOOL isScene;


/**
 *  类型区cell格式
 */
@property (nonatomic,assign) NSInteger sectionCellNumber;

/**
 *  当前选中的区头
 */
@property (nonatomic,assign) NSInteger selectedSectionNumber;

/**
 *  管理section开关(0,表示关闭,1,表示开启)
 */
@property (nonatomic,strong) NSMutableArray *openArray;

/**
 *  选中code
 */
@property (nonatomic,copy) NSString *selectedCode;

@end

@implementation SceneViewController



- (NSMutableArray *)sceneDatasArray
{
    if (!_sceneDatasArray) {
        
        _sceneDatasArray = [NSMutableArray array];
    }
    return _sceneDatasArray;
}

- (NSMutableArray *)productDatasArray
{
    if (!_productDatasArray) {
        
        _productDatasArray = [NSMutableArray array];
    }
    return _productDatasArray;
}

- (SceneCondition *)conditionModel
{
    if (!_conditionModel) {
        
        _conditionModel = [[SceneCondition alloc]init];
    }
    return _conditionModel;
}


- (GoodsCondition *)goodsModel
{
    if (!_goodsModel) {
        _goodsModel = [[GoodsCondition alloc]init];
    }
    return _goodsModel;
}

- (NSMutableArray *)sceneScreeningDatasArray
{
    if (!_sceneScreeningDatasArray) {
        
        _sceneScreeningDatasArray = [NSMutableArray array];
    }
    return _sceneScreeningDatasArray;
}

- (NSMutableArray *)productScreeningDatasArray
{
    if (!_productScreeningDatasArray) {
        
        _productScreeningDatasArray = [NSMutableArray array];
    }
    return _productScreeningDatasArray;
}

- (NSMutableArray *)openArray
{
    if (!_openArray) {
        
        _openArray = [NSMutableArray array];
    }
    return _openArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isScene = [[NSUserDefaults standardUserDefaults] boolForKey:@"SCENE"];
    [self UiConfigAction];
    [self ReturnDismiss];
    
    if (self.isScene) {
        //场景
        [self getDatasAction];
        
    }else
    {
        //产品
        [self GetdatasAction];
    }
}

#pragma mark -UI
- (void)UiConfigAction
{
    
    self.styleButton.layer.masksToBounds = YES;
    self.styleButton.layer.cornerRadius = kSelectedCornerRadius;
    self.typeButton.layer.masksToBounds = YES;
    self.typeButton.layer.cornerRadius = kSelectedCornerRadius;
    self.spaceButton.layer.masksToBounds = YES;
    self.spaceButton.layer.cornerRadius = kSelectedCornerRadius;
    self.materialButton.layer.masksToBounds = YES;
    self.materialButton.layer.cornerRadius = kSelectedCornerRadius;
    self.priceButton.layer.masksToBounds = YES;
    self.priceButton.layer.cornerRadius = kSelectedCornerRadius;
    self.styleButton.selected = YES;
    self.styleButton.backgroundColor = kMainBlueColor;
    self.rightSelectedIndex = 0;
    self.searchProductField.delegate = self;
    
    //筛选Tableview
    self.screeningTableView.delegate = self;
    self.screeningTableView.dataSource = self;
    self.screeningTableView.tableFooterView = [UIView new];
    [self.screeningTableView registerClass:[ScreeningTableViewCell class] forCellReuseIdentifier:@"ScreeningCellNew"];
    //section
    [self.screeningTableView registerClass:[SceneSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"headerView"];
    self.myTableViewBackView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.myTableViewBackView.layer.shadowOffset = CGSizeMake(0, 0);
    self.myTableViewBackView.layer.shadowRadius = 4;
    self.myTableViewBackView.layer.shadowOpacity = 0.5;
    self.myTableViewBackView.layer.masksToBounds = NO;
    
    //数据列表UICollectionView
    if (self.isScene) {
        self.collectionViewLayout.itemSize = CGSizeMake((self.sceneOrProductClollectionView.mj_w-40)/3, (self.sceneOrProductClollectionView.mj_w-40)/4);
        self.collectionViewLayout.minimumLineSpacing = 10;
        self.collectionViewLayout.minimumInteritemSpacing = 10;
        self.collectionViewLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }else
    {
        self.collectionViewLayout.itemSize = CGSizeMake((self.sceneOrProductClollectionView.mj_w-40)/3, self.sceneOrProductClollectionView.mj_w/3);
        self.collectionViewLayout.minimumLineSpacing = 10;
        self.collectionViewLayout.minimumInteritemSpacing = 10;
        self.collectionViewLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    self.sceneOrProductClollectionView.dataSource = self;
    self.sceneOrProductClollectionView.delegate = self;
}


#pragma mark -场景数据
- (void)getDatasAction
{
    __weak typeof(self) weakSelf = self;
    //场景筛选条件
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/scene/getSceneFilter"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
             SceneFilter *filterModel = [[SceneFilter alloc]initWithDictionary:returnValue[@"data"] error:nil];
            //风格
            NSMutableArray *styleArray = [NSMutableArray array];
            //空间
            NSMutableArray *spaceArray = [NSMutableArray array];
            [weakSelf.sceneScreeningDatasArray addObject:styleArray];
            [weakSelf.sceneScreeningDatasArray addObject:spaceArray];
            for (DataDict *model in filterModel.styles) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.sceneScreeningDatasArray firstObject] addObject:newModel];
            }
            for (DataDict *model in filterModel.space) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.sceneScreeningDatasArray lastObject] addObject:newModel];
            }
            [weakSelf.screeningTableView reloadData];
        }
        else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
    }];
    
    
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        //默认数据
        weakSelf.indexPage = 1;
        DataPage *page = [[DataPage alloc]init];
        page.page = weakSelf.indexPage;
        page.rows = KROWS;
        weakSelf.conditionModel.page = page;
        [weakSelf.sceneOrProductClollectionView.mj_footer resetNoMoreData];
        [weakSelf getSceneLibrarydatas:weakSelf.conditionModel isRemove:YES];
    }];
    
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.sceneOrProductClollectionView.mj_header = headerRefresh;
    [self.sceneOrProductClollectionView.mj_header beginRefreshing];
    //上拉加载
    self.sceneOrProductClollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (++ weakSelf.indexPage > weakSelf.totalPages) {
            [weakSelf.sceneOrProductClollectionView.mj_footer endRefreshingWithNoMoreData];
            
        }else
        {
            //默认数据
            DataPage *Newpage = [[DataPage alloc]init];
            Newpage.page = weakSelf.indexPage ++;
            Newpage.rows = KROWS;
            weakSelf.conditionModel.page = Newpage;
            [weakSelf getSceneLibrarydatas:weakSelf.conditionModel isRemove:NO];
        }
    }];
}


#pragma mark -获取场景列表数据
- (void)getSceneLibrarydatas:(SceneCondition *)condition isRemove:(BOOL)remove
{
    __weak typeof(self) weakSelf = self;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/scene/query"] WithRequestType:0 WithParameter:condition WithReturnValueBlock:^(id returnValue) {
        
        weakSelf.sceneOrProductClollectionView.emptyDataSetSource = weakSelf;
        [weakSelf endRefreshingForTableView:weakSelf.sceneOrProductClollectionView];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            if (remove) {
                [weakSelf.sceneDatasArray removeAllObjects];
            }
            SceneResponse *response = [[SceneResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.totalPages = [returnValue[@"data"][@"totalpages"] intValue];
            for (TOSceneEntity *model in response.list) {
                
                SceneListModel *newModel = [[SceneListModel alloc]init];
                newModel.fid = model.fid;
                newModel.sceneCode = model.sceneCode;
                newModel.name = model.name;
                newModel.pricure = model.pricure;
                newModel.category = model.category;
                newModel.style = model.style;
                newModel.space = model.space;
                newModel.isSelectedSate = NO;
                [self.sceneDatasArray addObject:newModel];
            }
            for (SceneListModel *model in SHARED_APPDELEGATE.sceneArray) {
                for (SceneListModel *sceneModel in self.sceneDatasArray) {
                    if ([model.fid isEqualToString:sceneModel.fid]) {
                        sceneModel.isSelectedSate = YES;
                    }
                }
            }
            
            [weakSelf.sceneOrProductClollectionView reloadData];
        }
        else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [weakSelf endRefreshingForTableView:weakSelf.sceneOrProductClollectionView];
    }];
}


#pragma mark -产品数据
- (void)GetdatasAction
{
    [self getScreeningdatasisRemoveArray:YES];
    //下拉刷新
    __weak typeof(self) weakSelf = self;
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        
        //分页数据
        DataPage *Newpage = [[DataPage alloc]init];
        Newpage.page = 1;
        Newpage.rows = KROWS;
        weakSelf.goodsModel.page = Newpage;
        weakSelf.indexPage = 1;
        [weakSelf.sceneOrProductClollectionView.mj_footer resetNoMoreData];
        [weakSelf getGoodsListDatasisRemove:YES Withobject:self.goodsModel];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.sceneOrProductClollectionView.mj_header = headerRefresh;
    [self.sceneOrProductClollectionView.mj_header beginRefreshing];
    
    //上拉加载
    self.sceneOrProductClollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        

        if (++ weakSelf.indexPage > weakSelf.totalPages) {
            [weakSelf.sceneOrProductClollectionView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            //分页数据
            DataPage *Newpage = [[DataPage alloc]init];
            Newpage.page = weakSelf.indexPage ++;
            Newpage.rows = KROWS;
            weakSelf.goodsModel.page = Newpage;
            [weakSelf getGoodsListDatasisRemove:NO Withobject:weakSelf.goodsModel];
        }
    }];
}


#pragma mark -获取产品筛选数据
- (void)getScreeningdatasisRemoveArray:(BOOL)remove
{
    __weak typeof(self) weakSelf = self;
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/goods/getGoodsFilter"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            if (remove) {
                [weakSelf.productScreeningDatasArray removeAllObjects];
            }
            GoodsFilter *goodsScreening = [[GoodsFilter alloc]initWithDictionary:returnValue[@"data"] error:nil];
            for (int i=0; i<5; i++) {
                NSMutableArray *array = [NSMutableArray array];
                [weakSelf.productScreeningDatasArray addObject:array];
            }
            for (DataDict *model in goodsScreening.styles) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.productScreeningDatasArray objectAtIndex_opple:0] addObject:newModel];
            }
            for (DataDict *model in goodsScreening.space) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.productScreeningDatasArray objectAtIndex_opple:1] addObject:newModel];
            }
            for (GoodsCategory *model in goodsScreening.categories) {
                GoodsCategoryModel *newModel = [[GoodsCategoryModel alloc]init];
                newModel.fid = model.fid;
                newModel.name = model.name;
                newModel.children = model.children;
                newModel.isSelectedState = NO;
                [weakSelf.openArray addObject:@"0"];//section关闭状态;
                [[weakSelf.productScreeningDatasArray objectAtIndex_opple:2] addObject:newModel];
            }
            for (DataDict *model in goodsScreening.material) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.productScreeningDatasArray objectAtIndex_opple:3] addObject:newModel];
            }
            for (DataDict *model in goodsScreening.price) {
                DataDictModel *newModel = [[DataDictModel alloc]init];
                newModel.typename = model.typename;
                newModel.typecode = model.typecode;
                newModel.isSelectedSate = NO;
                [[weakSelf.productScreeningDatasArray objectAtIndex_opple:4] addObject:newModel];
            }
            [weakSelf.screeningTableView reloadData];
        }
        else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(NSError *error) {
        
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}


#pragma mark -获取商品列表数据
- (void)getGoodsListDatasisRemove:(BOOL)remove Withobject:(GoodsCondition *)conditon
{
    __weak typeof(self)weakSelf = self;
    [self getGoodsListdatas:conditon returnResponse:^(GoodsResponse *response) {
        
        weakSelf.sceneOrProductClollectionView.emptyDataSetSource = weakSelf;
        if (remove) {
            [weakSelf.productDatasArray removeAllObjects];
        }
        for (TOGoodsEntity *model in response.goodsEntity) {
            
            TOGoodsEntityModel *newModel = [[TOGoodsEntityModel alloc]init];
            newModel.resellerInv = model.resellerInv;
            newModel.resellerTagPrice = model.resellerTagPrice;
            newModel.resellerState = model.resellerState;
            newModel.categoryName = model.categoryName;
            newModel.brandName = model.brandName;
            newModel.fid = model.fid;
            newModel.createDate = model.createDate;
            newModel.onlineTime = model.onlineTime;
            newModel.company = model.company;
            newModel.code = model.code;
            newModel.name = model.name;
            newModel.number = model.number;
            newModel.categoryId = model.categoryId;
            newModel.brandId = model.brandId;
            newModel.keyword = model.keyword;
            newModel.guidePrice = model.guidePrice;
            newModel.tagPrice = model.tagPrice;
            newModel.costPrice = model.costPrice;
            newModel.state = model.state;
            newModel.inv = model.inv;
            newModel.detailedIntro = model.detailedIntro;
            newModel.weight = model.weight;
            newModel.unit = model.unit;
            newModel.productProfile = model.productProfile;
            newModel.power = model.power;
            newModel.colorTemperature = model.colorTemperature;
            newModel.spec = model.spec;
            newModel.function = model.function;
            newModel.material = model.material;
            newModel.lightSource = model.lightSource;
            newModel.goodsStyle = model.goodsStyle;
            newModel.series = model.series;
            newModel.area = model.area;
            newModel.size = model.size;
            newModel.space = model.space;
            newModel.installMethod = model.installMethod;
            newModel.lightNumber = model.lightNumber;
            newModel.pictures = model.pictures;
            newModel.barcode = model.barcode;
            newModel.isSelectedState = NO;
            newModel.goodsNumber = 1;
            [weakSelf.productDatasArray addObject:newModel];
        }
        for (TOGoodsEntityModel *model in SHARED_APPDELEGATE.productArray) {
            for (TOGoodsEntityModel *productModel in weakSelf.productDatasArray) {
                if ([model.fid isEqualToString:productModel.fid]) {
                    productModel.isSelectedState = YES;
                }
            }
        }
        [weakSelf.sceneOrProductClollectionView reloadData];
    }];
}

#pragma mark -获取商品列表数据
- (void)getGoodsListdatas:(GoodsCondition *)conditon returnResponse:(void(^)(GoodsResponse *))finish
{
    __weak typeof(self) weakSelf = self;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/goods/query"] WithRequestType:0 WithParameter:conditon WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf endRefreshingForTableView:weakSelf.sceneOrProductClollectionView];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            GoodsResponse *sponse = [[GoodsResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.totalPages = [returnValue[@"data"][@"totalpages"] intValue];
            //返回结果
            finish(sponse);
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        [weakSelf ErrorMBProgressView:@"网络连接中断"];
    } WithFailureBlock:^(NSError *error) {
        
        [weakSelf endRefreshingForTableView:weakSelf.sceneOrProductClollectionView];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}



#pragma mark - UITableViewDataSource代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.rightSelectedIndex == 2) {
        
        BOOL boolValue = [[self.openArray objectAtIndex_opple:section] boolValue];
        GoodsCategoryModel *model = [[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:section];
        return boolValue?model.children.count:0;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ScreeningTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ScreeningCellNew" forIndexPath:indexPath];
    GoodsCategoryModel *model= [self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex][indexPath.section];
    cell.screeningLabe.text = [[model.children objectAtIndex_opple:indexPath.row] name];
    return cell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self CancelTableviewSectionState];
    ScreeningTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.screeningLabe.backgroundColor = kTCColor(221, 221, 221);
    cell.screeningLabe.textColor = kMainBlueColor;
    GoodsCategoryModel *model = [[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:indexPath.section];
    self.goodsModel.categoryEquals = [[model.children objectAtIndex_opple:indexPath.row] fid];
    [self.sceneOrProductClollectionView.mj_header beginRefreshing];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SceneSectionHeaderView *sectionView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (self.isScene) {
        [sectionView.sectionButton setTitle:[[self.sceneScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex][section] typename] forState:UIControlStateNormal];
    }else
    {
        if (self.rightSelectedIndex == 2) {
          [sectionView.sectionButton setTitle:[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex][section] name] forState:UIControlStateNormal];
        }else
        {
          [sectionView.sectionButton setTitle:[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex][section] typename] forState:UIControlStateNormal];
        }
    }
    sectionView.sectionButton.tag = section+100;
    [sectionView.sectionButton addTarget:self action:@selector(SectionButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    return sectionView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    NSArray *array = [self.isScene?self.sceneScreeningDatasArray:self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 55;
}



#pragma mark -区头选中
- (void)SectionButtonClickAction:(UIButton *)button
{
    [self CancelTableviewSectionState];
    if (self.rightSelectedIndex !=2 ) {
        button.selected = YES;
        button.backgroundColor = kTCColor(221, 221, 221);
    }
    [self emptyModel];
    switch (self.rightSelectedIndex) {
        case 0://风格
        {
            if (self.isScene) {
                
                self.conditionModel.styleEquals = [[[self.sceneScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typecode];
                self.conditionModel.spaceEquals = nil;
            }else
            {
                self.goodsModel.styleEquals = [[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typecode];
            }
        }
            break;
        case 1://空间
        {
            if (self.isScene) {
                
                self.conditionModel.spaceEquals = [[[self.sceneScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typecode];
                self.conditionModel.styleEquals = nil;
            }else
            {
                self.goodsModel.spaceEquals = [[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typecode];
            }
        }
            break;
        case 2://类型
        {

        }
            break;
        case 3://材质
        {
            self.goodsModel.materialEqueals = [[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typecode];
        }
            break;
        case 4://价格
        {
            //价格字符串切割
            NSArray *spacrArray = [[[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] objectAtIndex_opple:button.tag-100] typename] componentsSeparatedByString:@"到"];
            self.goodsModel.startprice = [NSNumber numberWithInteger:[[spacrArray objectAtIndex_opple:0] integerValue]];
            self.goodsModel.endprice = [NSNumber numberWithInteger:[[spacrArray objectAtIndex_opple:1] integerValue]];
        }
            break;
            
        default:
            break;
    }
    if (self.rightSelectedIndex == 2) {

        BOOL boolValue = [[self.openArray objectAtIndex_opple:button.tag-100] boolValue];
        NSMutableIndexSet *index = [[NSMutableIndexSet alloc]init];
        for (int i=0; i<self.openArray.count; i++) {
            [self.openArray replaceObjectAtIndex:i withObject:@"0"];
            [index addIndex:i];
        }
        [self.openArray replaceObjectAtIndex:button.tag-100 withObject:boolValue?@"0":@"1"];
        [self.screeningTableView reloadSections:index withRowAnimation:UITableViewRowAnimationMiddle];
        
    }else
    {
      [self.sceneOrProductClollectionView.mj_header beginRefreshing];
    }
}



#pragma mark -tableview取消所有cell选中
- (void)CancelTableviewSectionState
{

    NSArray *array = nil;
    if (self.isScene) {
        array = [self.sceneScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex];
    }else
    {
        if (self.rightSelectedIndex == 2) {
            array = [[[self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex] firstObject] children];
        }else
        {
          array = [self.productScreeningDatasArray objectAtIndex_opple:self.rightSelectedIndex];
        }
    }
    for (int i=0; i<array.count; i++) {
        UITableViewHeaderFooterView *sectionView = [self.screeningTableView headerViewForSection:i];
        for (id objc in sectionView.subviews) {
            if ([objc isKindOfClass:[UIButton class]]) {
                
                UIButton *button = (UIButton *)objc;
                button.selected = NO;
                button.backgroundColor = [UIColor whiteColor];
            }
        }
    }
}



#pragma mark -UICollectionViewDataSource代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.isScene) {
       return self.sceneDatasArray.count;
    }else
    {
        return self.productDatasArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isScene) {
        ScreeningCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ScreeningCollectioncell" forIndexPath:indexPath];
        cell.model = [self.sceneDatasArray objectAtIndex_opple:indexPath.item];
        cell.layer.shadowColor = [UIColor blackColor].CGColor;
        cell.layer.shadowRadius = 4;
        cell.layer.shadowOpacity = 0.5;
        cell.contentView.layer.shadowOffset = CGSizeMake(0, 0);
        cell.layer.masksToBounds = NO;
        return cell;
    }else
    {
        ProductScreeningCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCollectionViewCell" forIndexPath:indexPath];
        cell.backgroundColor = kMainGrayColor;
        cell.model = [self.productDatasArray objectAtIndex_opple:indexPath.item];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self)weakSelf = self;
    [self emptyModel];
    if (self.isScene) {
        ScreeningCollectionViewCell *cell = (ScreeningCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        CGPoint startPoint = [cell convertPoint:cell.sceneImageView.center toView:self.sceneOrProductClollectionView.window];
        if ([self.delegate respondsToSelector:@selector(SelectedImageswithModel:withisScene:returnResponse:)]) {
            SceneListModel *model = [self.sceneDatasArray objectAtIndex_opple:indexPath.item];
            [self.delegate SelectedImageswithModel:model withisScene:self.isScene returnResponse:^(BOOL boolValue) {
                //判断选中的图片是否存在
                if (!boolValue) {
                   [weakSelf StartAddShoppingCarAnimationWithimage:[cell.sceneImageView image] withStartpoint:startPoint withSize:cell.mj_size];
                    model.isSelectedSate = YES;
                    [weakSelf.sceneOrProductClollectionView reloadItemsAtIndexPaths:@[indexPath]];
                }else
                {
                    model.isSelectedSate = NO;
                    [weakSelf.sceneOrProductClollectionView reloadItemsAtIndexPaths:@[indexPath]];
                }
            }];
        }
    }else
    {
        ProductScreeningCollectionViewCell *cell = (ProductScreeningCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        CGPoint startPoint = [cell convertPoint:cell.goodsImageView.center toView:self.sceneOrProductClollectionView.window];
                if ([self.delegate respondsToSelector:@selector(SelectedImageswithModel:withisScene:returnResponse:)]) {
            GoodsCategoryModel *model = [self.productDatasArray objectAtIndex_opple:indexPath.item];
            [self.delegate SelectedImageswithModel:model withisScene:self.isScene returnResponse:^(BOOL boolValue) {
                //判断图片是否存在
                if (!boolValue) {
                    [weakSelf StartAddShoppingCarAnimationWithimage:[cell.goodsImageView image] withStartpoint:startPoint withSize:cell.mj_size];
                    model.isSelectedState = YES;
                    [weakSelf.sceneOrProductClollectionView reloadItemsAtIndexPaths:@[indexPath]];
                }else
                {
                    model.isSelectedState = NO;
                    [weakSelf.sceneOrProductClollectionView reloadItemsAtIndexPaths:@[indexPath]];
                }
            }];
        }
    }
}



#pragma mark -加入场景库、产品库动画
- (void)StartAddShoppingCarAnimationWithimage:(UIImage *)image withStartpoint:(CGPoint)point withSize:(CGSize)imageSize
{
    CGPoint startPoint = point;
    CGPoint endPoint = self.endAnimationPoint;
    CGPoint controlPoint = CGPointMake(endPoint.x, startPoint.x);
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    imageView.center = point;

    imageView.tag = 100;
    imageView.image = image;
    [self.view.window.layer addSublayer:imageView.layer];
    
    //路径曲线
    UIBezierPath *movePath = [UIBezierPath bezierPath];
    [movePath moveToPoint:imageView.center];
    [movePath addQuadCurveToPoint:endPoint
                     controlPoint:controlPoint];
    //关键帧
    CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    moveAnim.path = movePath.CGPath;
    moveAnim.removedOnCompletion = YES;
    
    //旋转变化
    CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
    scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    //x，y轴缩小到0.1,Z 轴不变
    scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
    scaleAnim.removedOnCompletion = YES;
    
    //透明度变化
    CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"alpha"];
    opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
    opacityAnim.toValue = [NSNumber numberWithFloat:0.1];
    opacityAnim.removedOnCompletion = YES;
    
    //关键帧，旋转，透明度组合起来执行
    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
    //当动画完成，停留到结束位置
    animGroup.removedOnCompletion = NO;
    animGroup.fillMode = kCAFillModeForwards;
    animGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim,opacityAnim, nil];
    animGroup.duration = 1;
    animGroup.delegate = self;
    [imageView.layer addAnimation:animGroup forKey:nil];
    [self performSelector:@selector(removeFromLayer:) withObject:imageView.layer afterDelay:1];
    
}

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

#pragma mark -动画完成
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if ([self.delegate respondsToSelector:@selector(RefreshSceneAndProduct:)]) {
        
        [self.delegate RefreshSceneAndProduct:self.isScene];
    }
}


#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}


- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}



#pragma mark -筛选条件
- (IBAction)ScreeningConditionsSelectedButtonClick:(UIButton *)sender {
    
    switch (sender.tag) {
        case 100://风格
        {
            
        }
            break;
        case 101://空间
        {
            
        }
            break;
        case 102://类型
        {
            
        }
            break;
        case 103://材质
        {
            
        }
            break;
        case 104://价格
        {
            
        }
            break;
            
        default:
            break;
    }
    
    for (int i=0; i<self.openArray.count; i++) {
        [self.openArray replaceObjectAtIndex:i withObject:@"0"];
    }
    [self emptyModel];
    self.rightSelectedIndex = sender.tag - 100;
    [self RemoveAllButtonisSelected];
    [self CancelTableviewSectionState];
    sender.selected = YES;
    sender.backgroundColor = kMainBlueColor;
    [self.screeningTableView reloadData];
}


#pragma mark -取消所有筛选条件按钮的选中
- (void)RemoveAllButtonisSelected
{
    for (UIView *view in self.clickEventView.subviews) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *button = (UIButton *)view;
            button.selected = NO;
            button.backgroundColor = [UIColor whiteColor];
        }
    }
}


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


#pragma mark -搜索框
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self emptyModel];
    [textField resignFirstResponder];
    self.goodsModel.nameLike = textField.text;
    [self.sceneOrProductClollectionView.mj_header beginRefreshing];
    return YES;
}

#pragma mark -返回手势
- (void)ReturnDismiss
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ReturnButtonClickAction)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

#pragma mark -销毁
- (void)ReturnButtonClickAction
{
    if (self.dismissBlock) {
        self.dismissBlock();
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


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


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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
