//
//  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,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>



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

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


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

/**
 *  总页数
 */
@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];
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _conditionModel.page = page;
    }
    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 setTitle:@"风格" forState:UIControlStateNormal];
    [self.styleButton addTarget:self action:@selector(screeningstyleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.spaceButton = [ScreeningButton buttonWithType:UIButtonTypeCustom];
    self.spaceButton.frame = CGRectMake(ScreenWidth-200, 14, 150, 30);
    [self.spaceButton setTitle:@"空间" forState:UIControlStateNormal];
    [self.spaceButton addTarget:self action:@selector(HousestyleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.styleButton];
    [self.backView addSubview:self.spaceButton];
    
    //下拉刷新
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{

        weakSelf.conditionModel.page.page = ONE;
        [weakSelf.seceneLibararyCollectionView.mj_footer resetNoMoreData];
        [weakSelf getSceneLibrarydatas:weakSelf.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 ( ++ weakSelf.conditionModel.page.page > weakSelf.totalPages) {
            [weakSelf.seceneLibararyCollectionView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getSceneLibrarydatas:weakSelf.conditionModel isRemove:NO];
        }
    }];
    self.seceneLibararyCollectionView.mj_footer.automaticallyHidden = YES;

    
}
#pragma mark -获取场景筛选数据
- (void)getdatasAction
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SCENESCREENING)  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
          weakSelf.filter = [[SceneFilter alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(id error) {
        
    }];
}


#pragma mark -获取场景列表数据
- (void)getSceneLibrarydatas:(SceneCondition *)condition isRemove:(BOOL)remove
{
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SCENELIST)  withRequestType:ZERO withParameter:condition withReturnValueBlock:^(id returnValue) {
        
        weakSelf.seceneLibararyCollectionView.emptyDataSetSource = weakSelf;
        weakSelf.seceneLibararyCollectionView.emptyDataSetDelegate = weakSelf;
        [weakSelf endRefreshingForTableView:weakSelf.seceneLibararyCollectionView];
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            if (remove) {
                [weakSelf.responseArray removeAllObjects];
            }
            SceneResponse *response = [[SceneResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            weakSelf.totalPages = [RESPONSE(returnValue)[@"totalpages"] intValue];
            for (TOSceneEntity *model in response.list) {
                [weakSelf.responseArray addObject:model];
            }
            [weakSelf.seceneLibararyCollectionView reloadData];
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefreshingForTableView:weakSelf.seceneLibararyCollectionView];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


- (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
{
    //空间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 = 0;
    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.seceneLibraryCollectionLayout.itemSize = CGSizeMake((ScreenWidth-showcellNumber*2)/showcellNumber, (ScreenWidth-showcellNumber*2)/showcellNumber-50);
    [self.seceneLibararyCollectionView reloadData];
}



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

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

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (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
