//
//  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;
}


/**
 *  上传模型
 */
- (SceneCondition *)conditionModel
{
    if (!_conditionModel) {
        
        _conditionModel = [[SceneCondition alloc]init];
    }
    return _conditionModel;
}



- (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;
        DataPage *page = [[DataPage alloc]init];
        page.page = self.indexPage;
        page.rows = KROWS;
        self.conditionModel.page = page;
        
        [self.seceneLibararyCollectionView.mj_footer resetNoMoreData];
        [self getSceneLibrarydatas:self.conditionModel 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
        {
            //默认数据
            DataPage *Newpage = [[DataPage alloc]init];
            Newpage.page = self.indexPage ++;
            Newpage.rows = KROWS;
            self.conditionModel.page = Newpage;
            [self getSceneLibrarydatas:self.conditionModel 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 = [returnValue[@"data"][@"totalpages"] intValue];
            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 dismissViewControllerAnimated:NO completion:nil];
    [self ShowPopoverViewController:CGSizeMake(55, 180) Withdatas:self.imageArray ShowButton:sender SelectedIndex:100];
}


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


    NSMutableArray *styleArray = [NSMutableArray arrayWithArray:self.filter.styles];
    DataDict *style = [[DataDict alloc]init];
    style.typename = @"全部";
    [styleArray insertObject:style atIndex:0];
    [self dismissViewControllerAnimated:NO completion:nil];
    [self ShowPopoverViewController:CGSizeMake(150, 200) Withdatas:styleArray ShowButton:sender SelectedIndex:0];
    
}


#pragma mark -空间风格
- (void)HouseStyleButtonClick:(UIButton *)sender {
    
    NSMutableArray *spaceArray = [NSMutableArray arrayWithArray:self.filter.space];
    DataDict *space = [[DataDict alloc]init];
    space.typename = @"全部";
    [spaceArray insertObject:space atIndex:0];
    [self dismissViewControllerAnimated:NO completion:nil];
    [self ShowPopoverViewController:CGSizeMake(150, 200) Withdatas:spaceArray 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];

    //空间code
    if (Selected) {
        
        self.conditionModel.spaceEquals = Type;
        [self.SpaceButton setTitle:[title isEqualToString:@"全部"]?@"空间":title forState:UIControlStateNormal];
    }else
    {//风格code
        
        self.conditionModel.styleEquals = Type;
        [self.StyleButton setTitle:[title isEqualToString:@"全部"]?@"风格":title forState:UIControlStateNormal];
    }
    [self.seceneLibararyCollectionView.mj_header beginRefreshing];
}


#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
