//
//  CommoditySearchViewController.m
//  ALand
//
//  Created by Z on 16/4/12.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "CommoditySearchViewController.h"
#import "CommodityListCollectionViewCell.h"
#import "SortView.h"
#import "CommodityDetailViewController.h"
#import "CommotityRequestModel.h"
#import "HotBrandModel.h"
#import "CatgoryModel.h"
#import "JavenHotTagsModel.h"
#import "CommodityListModel/CommotityListModel.h"

#define kCellID @"commodityCell"
#define kPageSize @10
@interface CommoditySearchViewController ()<UISearchBarDelegate,UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) SortView *sortView;
@property (nonatomic, strong) NSMutableArray *arrItemDatas;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *field; //排序的字段
@property (nonatomic, copy) NSString *direction;  //排序的顺序 升序或降序
@property (nonatomic, copy) NSString *searchText;  //正在搜索的字段

@end

@implementation CommoditySearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.direction = @"desc";
    self.field = @"";
    [self setUpSearchBar];
    [self setUpSortView];
    [self setUpCollectionView];
    // Do any additional setup after loading the view from its nib.
}

- (void)popAction
{
    [self.navigationController.navigationBar endEditing:YES];
    [self DismissModalViewControllerAnimated:YES];
}

- (void)setUpSearchBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 35)];//allocate titleView
    UIColor *color = self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, 260, 35);
    searchBar.centerX = titleView.centerX;
    searchBar.backgroundImage = [UIImage imageWithColor:color];
    [searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [titleView addSubview:searchBar];
    self.navigationItem.titleView = titleView;
    
    [searchBar becomeFirstResponder];
}



- (NSMutableArray *)arrItemDatas {
    if (!_arrItemDatas) {
        _arrItemDatas = [NSMutableArray array];
    }
    return _arrItemDatas;
}

- (void)setUpData {
    
    NSDictionary *myDictionary = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"goodsData name like",
                                                                        @"parameters" : @[self.searchText]},
                                                                      @{@"operation" : @"domain equals",
                                                                        @"parameters" : @[[UserInfo shareInstance].domain]},
                                                                     ],
                                                    @"orders" : @[@{@"direction" : self.direction,
                                                                    @"field" : self.field}],
                                                    @"page" : @0,
                                                    @"pageSize" : @999,
                                                    @"probePages" : @0},
                                   @"fetchParts" : [NSNull null]};
    
    
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"goods/query2" parameters:myDictionary success:^(NSURLSessionDataTask *task, id responseObject) {
        
        for (NSDictionary *dic in responseObject[@"queryResult"]) {
            CommotityListModel *model = [CommotityListModel modelObjectWithDictionary:dic];
            [weakSelf.arrItemDatas addObject:model];
        }
        
        [weakSelf.collectionView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
}
- (void)setUpSortView {
    _sortView = [[[SortView alloc] init] customNew];
    [self.view addSubview:_sortView];
    _sortView.sd_layout.topSpaceToView(self.view,1).leftEqualToView(self.view).rightEqualToView(self.view).heightIs(44);
    _sortView.backgroundColor = [UIColor whiteColor];
    
    
    //点击排序列表之后回调传入选中行数 筛选
    WS(weakSelf)
    _sortView.selecedBlock = ^(NSInteger row){
        [weakSelf sortAction:row];
        CLog(@"%ld", (long)row);
    };
    
    _sortView.rightAction = ^(){
        weakSelf.field = @"salesvolume";
        weakSelf.direction = @"desc";
        [weakSelf resetReloadData];
    };
    
}

//排序
- (void)sortAction:(NSInteger)row {
    switch (row) {
        case 0:
        {
            self.field = nil;
            self.direction = nil;
        }
            break;
        case 1://价格 高-低
        {
            self.field = @" spec price";
            self.direction = @"desc";
        }
            break;
        case 2://价格 低-高
        {
            self.field = @" spec price";
            self.direction = @"asc";
        }
            break;
        case 3://佣金
        {
            self.field = @"brokerageRate";
            self.direction = @"desc";
        }
            break;
        case 4:
        {
            self.field = @"brokerageRate";
            self.direction = @"asc";
        }
            break;
        case 5://点击量
        {
            self.field = @"visited";
            self.direction = @"desc";
        }
            break;
        case 6:
        {
            self.field = @"visited";
            self.direction = @"asc";
        }
            break;
            
        default:
            break;
    }
    [self resetReloadData];
}

//改变排序条件之后重新请求数据
- (void)resetReloadData {
    [self.arrItemDatas removeAllObjects];
    [self setUpData];
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.sortView hide];
}


- (void)setUpCollectionView {
    UICollectionViewFlowLayout *layOut = [[UICollectionViewFlowLayout alloc] init];
    layOut.minimumLineSpacing = 10;
    layOut.itemSize = CGSizeMake((ScreenSize.width - 30)/2, ScreenSize.height / 2.2);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layOut];
    [self.view addSubview:_collectionView];
    _collectionView.sd_layout.topSpaceToView(self.view, 50).leftEqualToView(self.view).bottomEqualToView(self.view).rightEqualToView(self.view);
    _collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = kBacroundColor;
    [_collectionView registerNib:[UINib nibWithNibName:@"CommodityListCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:kCellID];
}


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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CommodityDetailViewController *detailVC = [[CommodityDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CommodityListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];
    
    [cell cellWithModel:self.arrItemDatas[indexPath.row]];
    return cell;
}


#pragma mark =========== searchBar Delegate ===========

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    CLog(@"点击搜索");
    [self.navigationController.navigationBar endEditing:YES];
    
    [self resetReloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.searchText = searchText;
}

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