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

#import "SceneLibraryViewController.h"
#import "SeceneLibraryCollectionViewCell.h"
#import "FullScreenViewController.h"
@interface SceneLibraryViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ReturnTableviewcellIndexpathdelegate>



/**
 *  筛选数据源
 */
@property (nonatomic,strong)  SceneFilter *filter;

/**
 *  列表数据
 */
@property (nonatomic,strong) NSMutableArray *responseArray;


/**
 *  筛选cell个数图片
 */
@property (nonatomic,strong) NSArray *imageArray;

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

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


@end

@implementation SceneLibraryViewController


#pragma mark -初始化
- (NSArray *)imageArray
{
    if (_imageArray == nil) {
        
        _imageArray = [NSArray arrayWithObjects:@"视角1",@"视角",@"视角3", nil];
    }
    return _imageArray;
    
}

/**
 *  初始化数据源
 */
- (NSMutableArray *)responseArray
{
    if (_responseArray == nil) {
        
        _responseArray = [NSMutableArray array];
    }
    return _responseArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self uiConfigAction];
    [self getdatasAction];

}



#pragma mark -UI
- (void)uiConfigAction
{
    self.seceneLibraryCollectionLayout.itemSize = CGSizeMake((ScreenWidth-6)/3, (ScreenWidth-6)/3-50);
    self.seceneLibraryCollectionLayout.minimumLineSpacing = 2;
    self.seceneLibraryCollectionLayout.minimumInteritemSpacing = 2;
    self.seceneLibraryCollectionLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
    self.seceneLibararyCollectionView.dataSource = self;
    self.seceneLibararyCollectionView.delegate = self;
    
    //设置按钮
    self.StyleButton = [screeningButton buttonWithType:UIButtonTypeCustom];
    self.StyleButton.frame = CGRectMake(ScreenWidth-400, 14, 150, 30);
    self.StyleButton.backgroundColor = kTCColor(131, 131, 131);
    [self.StyleButton setTitle:@"风格" forState:UIControlStateNormal];
    [self.StyleButton addTarget:self action:@selector(screeningStyleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.StyleButton setImage:TCImage(@"down_arr") forState:UIControlStateNormal];
    self.StyleButton.layer.masksToBounds = YES;
    self.StyleButton.layer.cornerRadius = 10;
    self.SpaceButton = [screeningButton buttonWithType:UIButtonTypeCustom];
    self.SpaceButton.frame = CGRectMake(ScreenWidth-200, 14, 150, 30);
    [self.SpaceButton setTitle:@"空间" forState:UIControlStateNormal];
    self.SpaceButton.layer.masksToBounds = YES;
    self.SpaceButton.backgroundColor = kTCColor(131, 131, 131);
    [self.SpaceButton addTarget:self action:@selector(HouseStyleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.SpaceButton setImage:TCImage(@"down_arr") forState:UIControlStateNormal];
    self.SpaceButton.layer.cornerRadius = 10;
    [self.backView addSubview:self.StyleButton];
    [self.backView addSubview:self.SpaceButton];
    self.indexPage = 1;
    
    
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        //默认数据
        self.indexPage = 1;
        SceneCondition *condition = [[SceneCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = self.indexPage;
        page.rows = KROWS;
        condition.page = page;
        
        [self.seceneLibararyCollectionView.mj_footer resetNoMoreData];
        [self getSceneLibrarydatas:condition isRemove:YES];
    }];
    
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.seceneLibararyCollectionView.mj_header = headerRefresh;
    [self.seceneLibararyCollectionView.mj_header beginRefreshing];
    //上拉加载
    self.seceneLibararyCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.indexPage ++ > self.totalPages) {
            [self.seceneLibararyCollectionView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            //默认数据
            SceneCondition *condition = [[SceneCondition alloc]init];
            DataPage *Newpage = [[DataPage alloc]init];
            Newpage.page = self.indexPage ++;
            Newpage.rows = KROWS;
            condition.page = Newpage;
            [self getSceneLibrarydatas:condition isRemove:NO];
        }
    }];
    
}
#pragma mark -获取场景筛选数据
- (void)getdatasAction
{
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/scene/getSceneFilter"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
          self.filter = [[SceneFilter alloc]initWithDictionary:returnValue[@"data"] error:nil];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
    }];
}


#pragma mark -获取场景列表数据
- (void)getSceneLibrarydatas:(SceneCondition *)condition isRemove:(BOOL)remove
{
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/scene/query"] WithRequestType:0 WithParameter:condition WithReturnValueBlock:^(id returnValue) {
        
        [self endRefreshingForTableView:self.seceneLibararyCollectionView];
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            if (remove) {
                [self.responseArray removeAllObjects];
            }
            SceneResponse *response = [[SceneResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            self.totalPages = (int)returnValue[@"data"][@"totalPages"];
            for (TOSceneEntity *model in response.list) {
                [self.responseArray addObject:model];
            }
            
            [self.seceneLibararyCollectionView reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        [self endRefreshingForTableView:self.seceneLibararyCollectionView];
    }];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SeceneLibraryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"secenelibrary" forIndexPath:indexPath];
    cell.model = [self.responseArray objectAtIndex_opple:indexPath.item];
    return cell;
}

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    FullScreenViewController *fullScreenVC = [[FullScreenViewController alloc]init];
    fullScreenVC.datasArray = self.responseArray;
    fullScreenVC.currentindex = indexPath.row;
    [self presentViewController:fullScreenVC animated:YES completion:nil];
}


#pragma mark -切换显示风格
- (IBAction)SwitchdisplayStyleClick:(UIButton *)sender {
    
    [self ShowPopoverViewController:CGSizeMake(55, 180) Withdatas:self.imageArray ShowButton:sender SelectedIndex:100];
}


#pragma mark -筛选风格
- (void)screeningStyleButtonClick:(UIButton *)sender {

    [self dismissViewControllerAnimated:NO completion:nil];
    [self ShowPopoverViewController:CGSizeMake(150, 200) Withdatas:self.filter.styles ShowButton:sender SelectedIndex:0];
    
}


#pragma mark -空间风格
- (void)HouseStyleButtonClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:NO completion:nil];
    [self ShowPopoverViewController:CGSizeMake(150, 200) Withdatas:self.filter.space ShowButton:sender SelectedIndex:1];
}


#pragma mark -弹出popover视图控制器
- (void)ShowPopoverViewController:(CGSize)size Withdatas:(NSArray *)datasArray ShowButton:(UIButton *)button SelectedIndex:(NSInteger)index
{
    PopoverViewController *popover = [[PopoverViewController alloc]init];
    popover.datasArray = datasArray;
    popover.delegate = self;
    popover.Selectedindex = index;
    if (size.width == 55) {
        popover.isPictures = YES;
    }
    popover.contentSize = size;
    popover.preferredContentSize = size;
    popover.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = popover.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = popover.view;
    pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [self presentViewController:popover animated:YES completion:nil];
}


#pragma mark -选中筛选条件回传typecode
- (void)returnCellindexpathwithrow:(NSString *)Type WithcellTitle:(NSString *)title Withselected:(NSInteger)Selected
{
    [self dismissViewControllerAnimated:YES completion:nil];
    SceneCondition *condition = [[SceneCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.page = 0;
    condition.page = page;
    
    //空间code
    if (Selected) {
        
        condition.spaceEquals = Type;
        [self.SpaceButton setTitle:title forState:UIControlStateNormal];
    }else
    {//风格code
        condition.styleEquals = Type;
        [self.StyleButton setTitle:title forState:UIControlStateNormal];
    }
    [self getSceneLibrarydatas:condition isRemove:YES];
}


#pragma mark -筛选条件回传cellindex
- (void)returnWithIndexSelected:(NSInteger)selectedIndex
{

    NSInteger showcellNumber;
    switch (selectedIndex) {
        case 0:
        {
            showcellNumber = 2;
        }
            break;
        case 1:
        {
            showcellNumber = 3;
        }
            break;
        case 2:
        {
            showcellNumber = 4;
        }
            break;
            
        default:
            break;
    }
    [self.accordingStyle setBackgroundImage:TCImage([self.imageArray objectAtIndex_opple:selectedIndex]) forState:UIControlStateNormal];
    [self dismissViewControllerAnimated:YES completion:nil];
    self.seceneLibraryCollectionLayout.itemSize = CGSizeMake((ScreenWidth-showcellNumber*2)/showcellNumber, (ScreenWidth-showcellNumber*2)/showcellNumber-50);
    [self.seceneLibararyCollectionView reloadData];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // 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
