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

#import "CommodityManagementViewController.h"
#import "CommodityManagementTopView.h"
#import "UITableView+Category.h"
#import "CommodityTableViewCell.h"
#import "CommotityRequestModel.h"
#import "CommodityListModel/CommotityListModel.h"
#import "ManagementViewController.h"
#import "Conditions.h"
#define kCellID @"commodityCell"
#define kPageSize @999
#define kCellId @"CommodityTableViewCell.h"
@interface CommodityManagementViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) CommodityManagementTopView *topView;
@property (nonatomic, strong) UITableView *tableView;
@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;  //正在搜索的字段
@property (nonatomic, copy) NSString *condition;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) UIBarButtonItem *rightItem;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UIView *searchTitleView;




@end

@implementation CommodityManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.condition = @"shop online only";
    self.searchText = @"";
    self.field = @"";
    self.direction = @"desc";
    [self setUpNavigationbar];
    [self setUpViews];
    [self setUpSearchBar];
    [self setUpData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self resetReloadData];
}

- (void)setUpSearchBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth - 100, 35)];//allocate titleView
    UIColor *color = self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.backgroundColor = kRandomColor;
    self.searchBar.delegate = self;
    self.searchBar.frame = CGRectMake(0, 0, 0, 35);
    self.searchBar.centerX = titleView.centerX;
    self.searchBar.backgroundImage = [UIImage imageWithColor:color];
    [titleView addSubview:self.searchBar];
    
    self.searchTitleView = titleView;
}

- (void)cancelSearchAction {
    self.searchText = @"";
    self.condition = @"shop online only";

    self.searchBar.width = 0;
    self.searchBar.centerX = (kWidth - 100) / 2;

    self.navigationItem.titleView = self.titleView;
    self.navigationItem.rightBarButtonItem = self.rightItem;
}


- (void)setUpNavigationbar {
    self.navigationItem.title = @"商品管理";
    self.titleView = self.navigationItem.titleView;
    
    self.rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"searchIcon"] style:UIBarButtonItemStyleDone target:self action:@selector(searchAct)];
    self.rightItem.tintColor = kTextColorDarkGray;
    self.navigationItem.rightBarButtonItem = self.rightItem;
}


- (void)setUpViews {
    [self.view addSubview:self.topView];
    [self.view addSubview:self.sorView];
    
    //设置现在默认选中的排序方式
    [self.sorView defaultSelectISLeft:YES row:0];
    self.topView.isLeft = YES;
    self.topView.row = 0;
    
    WS(weakSelf)
    self.sorView.leftTableSelect = ^(NSInteger row){
        [weakSelf leftSelectCodtition:row];
        CLog(@"l");
    };
    
    self.sorView.rightTableSelect = ^(NSInteger row){
        [weakSelf rightSelectCondition:row];
        CLog(@"r");
    };
    
    //
    _tableView = [UITableView plainTableViewWithTarget:self cellNibName:@"CommodityTableViewCell" cellId:kCellId];
    [self.view addSubview:_tableView];
    _tableView.sd_layout.topSpaceToView(self.sorView,0).leftEqualToView(self.view).rightEqualToView(self.view).bottomEqualToView(self.view);
}


- (void)leftSelectCodtition:(NSInteger)row {
    self.topView.isLeft = YES;
    self.topView.row = row;
    
    switch (row) {
        case 0:
        {
            self.condition = @"shop online only";
        }
            break;
        case 1:
        {
            self.condition = @"shop offline only";
        }
            break;
        
        default:
            break;
    }
    
    [self resetReloadData];

}

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

- (void)rightSelectCondition:(NSInteger)row {
    self.topView.isLeft = NO;
    self.topView.row = row;
    
    
    switch (row) {
        case 0:
        {
            self.field = @"shop goods create time";
            self.direction = @"desc";
        }
            break;
        case 1:
        {
            self.field = @"salesvolume";
            self.direction = @"desc";
        }
            break;
        case 2:
        {
            self.field = @"brokerageRate";
            self.direction = @"desc";
        }
            break;
        case 3:
        {
            self.field = @" spec price";
            self.direction = @"desc";
            
        }
            break;
            
        default:
            break;
    }
    
    [self resetReloadData];
}



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

- (void)setUpData {
    
    NSDictionary *params = @{@"defintion" : @{@"probePages" : @0,
                                                    @"orders" : @[@{@"field" : self.field,
                                                                    @"direction" : self.direction}],
                                                    @"conditions" : @[@{@"parameters" : @[[UserInfo shareInstance].domain],
                                                                        @"operation" : @"domain equals",
                                                                        @"parameter" : @{@"operation" : @"string"}},
                                                                      @{@"parameters" : @[@[[UserInfo shareInstance].shop.uuid]],
                                                                        @"operation" : @"shop uuid equals",
                                                                        @"parameter" : @{@"operation" : @"sring"}},
                                                                      @{@"parameters" : @[self.searchText],
                                                                        @"operation" : self.condition,
                                                                        @"parameter" : @{@"operation" : @"sring"}}],
                                                    @"pageSize" : kPageSize,
                                                    @"page" : @0},
                                   @"fetchParts" : @[@"string"]};
    
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"goods/query2" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        for (NSDictionary *dic in responseObject[@"queryResult"]) {
            CommotityListModel *model = [CommotityListModel modelObjectWithDictionary:dic];
            [weakSelf.arrItemDatas addObject:model];
        }
        
        [weakSelf.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


#pragma mark =========== action ===========

- (void)searchAct {
    [self.sorView hide];
    CLog(@"search");
    WS(weakSelf)
    self.navigationItem.titleView = self.searchTitleView;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.searchBar.width = kWidth - 100;
        weakSelf.searchBar.centerX = (kWidth - 100) / 2;
    } completion:^(BOOL finished) {
        [weakSelf.searchBar becomeFirstResponder];

    }] ;
    
    UIBarButtonItem *cancelSearch = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelSearchAction)];
    self.navigationItem.rightBarButtonItem = cancelSearch;
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar endEditing:YES];

    [super viewWillDisappear:animated];
    [self.sorView hide];
}


#pragma mark =========== tableview delegate ===========

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrItemDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommodityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    
    [cell cellWithModel:self.arrItemDatas[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

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

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

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

#pragma mark =========== lazy loading ===========
- (CommodityManagementSortView *)sorView {
    if (!_sorView) {
        _sorView = [[CommodityManagementSortView new] sortView];
        _sorView.frame = CGRectMake(0, _topView.bottom - 50, kWidth, 49);
        
    }
    return _sorView;
}

- (CommodityManagementTopView *)topView {
    if (!_topView) {
        _topView = [CommodityManagementTopView viewWithNibName:@"CommodityManagementTopView"];
        _topView.frame = CGRectMake(0, 0, kWidth, 64 + 64);
        _topView.arrDatas = self.arrItemDatas;
    }
    return _topView;
}


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