//
//  CommodityListViewController.m
//  ALand
//
//  Created by Z on 16/3/23.
//  Copyright © 2016年 Z. All rights reserved.
//

#import "CommodityListViewController.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"
#import "MJRefresh.h"
#define kCellID @"commodityCell"
#define kPageSize 20
@interface CommodityListViewController ()<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;  //排序的顺序 升序或降序


@end

@implementation CommodityListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //配置navigationbar
    self.navigationItem.title = @"商品列表";
    self.view.backgroundColor = kBacroundColor;
    self.field = @"";
    self.page = 0;
    self.direction = @"desc";
    
    [self setUpSortView];
    [self setUpCollectionView];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self setUpData];
    // Do any additional setup after loading the view.
}

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

- (void)setUpData {
    
 
    NSString *parameters;
    NSString *operation;
    if ([self.model isKindOfClass:[HotBrandModel class]]) {//热门品牌
        
        //设置请求模型
        HotBrandModel *model = self.model;
        operation = @"goodsData brand uuid equals";
        parameters = model.uuid;
        
    }else if([self.model isKindOfClass:[CatgoryModel class]]){//分类
        CatgoryModel *model = self.model;
        operation = @"goodsData category path startWith";
        parameters = model.path;
        
    }else if ([self.model isKindOfClass:[JavenHotTagsModel class]]){//热门标签
        CatgoryModel *model = self.model;
        operation = @"tag uuid equals";
        parameters = model.uuid;
    }
    
    NSDictionary *myDictionary = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                        @"parameters" : @[kDomain]},
                                                                      @{@"operation" : @"online only",
                                                                        @"parameters" : @[[NSNull null]]},
                                                                      @{@"operation" : operation,
                                                                        @"parameters" : @[parameters]}],
                                                    @"orders" : @[@{@"field" : self.field,
                                                                    @"direction" : self.direction}],
                                                    @"pageSize" : @(kPageSize),
                                                    @"page" : @(self.page),
                                                    @"probePages" : @0},
                                   @"fetchParts" : @[@"string"]};
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"goods/query2" parameters:myDictionary success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        
        for (NSDictionary *dic in responseObject[@"queryResult"]) {
            CommotityListModel *model = [CommotityListModel modelObjectWithDictionary:dic];
            [weakSelf.arrItemDatas addObject:model];
        }
        [weakSelf.collectionView reloadData];
        [weakSelf.collectionView.mj_header endRefreshing];
        if ([responseObject[@"queryResult"] count] < kPageSize) {
            [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [weakSelf.collectionView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

    }];
    
    
}

- (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 = @"";
            self.direction = @"desc";
        }
            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 = @"commission";
            self.direction = @"desc";
        }
            break;
        case 4:
        {
            self.field = @"commission";
            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 {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [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, 340);
    
    _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];
    
    WS(weakSelf)
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 0;
        [weakSelf resetReloadData];
    }];
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page += 1;
        
        [weakSelf setUpData];
    }];
//    _collectionView.mj_footer
    
}


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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CommodityDetailViewController *detailVC = [[CommodityDetailViewController alloc] init];
    detailVC.model = self.arrItemDatas[indexPath.row];
    CommodityListCollectionViewCell *cell = (CommodityListCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    detailVC.image = cell.imageViewTop.image;
    detailVC.isShowNavigationBar = NO;
    [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;
}

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