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

#import "CustomerManagementViewController.h"
#import "UITableView+Category.h"
#import "JavenSortView.h"
#import "CustomerTableViewCell.h"
#import "JavenCustomer.h"
#import "CustomerViewController.h"

#define kPageSize @10
#define kCellId @"CustomerTableViewCell.h"
@interface CustomerManagementViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) JavenSortView *sortView;
@property (nonatomic, strong) NSMutableArray *arrCellData;

@property (nonatomic, copy) NSString *field; //排序的字段
@property (nonatomic, copy) NSString *direction;  //排序的顺序 升序或降序
@end

@implementation CustomerManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.field = @"commission";
    self.direction = @"desc";
    self.view.backgroundColor = kBacroundColor;
    [self setUpSearchBar];
    [self setUpSortView];
    [self setUptableView];
    [self setUpData];
    // Do any additional setup after loading the view.
}

- (NSMutableArray *)arrCellData {
    if (!_arrCellData) {
        _arrCellData = [NSMutableArray array];
    }
    return _arrCellData;
}

- (void)setUpData {
    
    
    NSDictionary *params = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                        @"parameter" : @{@"operation" : @"string"},
                                                                        @"parameters" : @[[UserInfo shareInstance].domain]},
                                                                      @{@"operation" : @"reseller uuid equals",
                                                                        @"parameter" : @{@"operation" : @"string"},
                                                                        @"parameters" : @[[UserInfo shareInstance].uuid]}],
                                                    @"orders" : @[@{@"field" : self.field,
                                                                    @"direction" : self.direction}],
                                                    @"pageSize" : kPageSize,
                                                    @"page" : @0,
                                                    @"probePages" : @0},
                                   @"fetchParts" : @[@"string"]};
    WS(weakSelf)
    [[HTTPCilent shareCilent] POST:@"reseller/customer/query" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            
            
            for (NSDictionary *dic in responseObject[@"queryResult"]) {
                JavenCustomer *customer = [JavenCustomer modelObjectWithDictionary:dic];
                [weakSelf.arrCellData addObject:customer];
            }
            
            [weakSelf.tableView reloadData];
        }else{
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


- (void)setUpSearchBar {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth - 60, 35)];//allocate titleView
    UIColor *color = self.navigationController.navigationBar.barTintColor;
    [titleView setBackgroundColor:color];
    self.searchBar = [[UISearchBar alloc] init];
    self.searchBar.tintColor = kTextColorLiteGray;
    self.searchBar.backgroundColor = kRandomColor;
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入手机号";
    self.searchBar.frame = CGRectMake(0, 0, kWidth - 60, 35);
    self.searchBar.centerX = titleView.centerX;
    self.searchBar.backgroundImage = [UIImage imageWithColor:color];
    [titleView addSubview:self.searchBar];
    self.navigationItem.titleView = titleView;

}

- (void)setUpSortView {
      NSArray *arrLeftTitles =  @[@"全部客户",@"今日新增客户",@"本周新增客户"];
    NSArray *arrRightTitles = @[@"默认排序",@"订单数从高到低",@"收入从高到低"];
    self.sortView = [JavenSortView sortViewLeftTitles:arrLeftTitles rightTitles:arrRightTitles];
    self.sortView.frame = CGRectMake(0, 0, kWidth, 40);
    [self.view addSubview:self.sortView];
    
    WS(weakSelf)
    _sortView.leftTableSelect =  ^(NSInteger row){
        [weakSelf leftSortAction:row];
        CLog(@"%ld", (long)row);
    };
    
    _sortView.rightTableSelect = ^(NSInteger row){
        [weakSelf rightSortAction:row];
    };
}

- (void)rightSortAction:(NSInteger)row {
    switch (row) {
        case 0:
        {
            self.field = @"commission";
            self.direction = @"desc";
        }
            break;
        case 1://订单数 高-低
        {
            self.field = @"order count";
            
            self.direction = @"desc";
        }
            break;
        case 2://收入 高-低
        {
            self.field = @"commission";
            self.direction = @"desc";
        }
            break;
            
        default:
            break;
    }
    [self resetReloadData];
}


//排序
- (void)leftSortAction:(NSInteger)row {
    switch (row) {
        case 0:
        {
            self.field = @"commission";
            self.direction = @"desc";
        }
            break;
        case 1://价格 高-低
        {
            self.field = @"consumer create time";
            NSDateFormatter *f = [[NSDateFormatter alloc] init];
            [f setDateFormat:@"yyyy-MM-dd"];
            NSString *dateStr = [f stringFromDate:[NSDate date]];
            
            NSString *appendStr = [dateStr stringByAppendingString:@" 00:00:00"];
            
            
            self.direction = appendStr;
        }
            break;
        case 2://价格 低-高
        {
            self.field = @" spec price";
            self.direction = @"asc";
        }
            break;
            
        default:
            break;
    }
    [self resetReloadData];
}

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

- (void)setUptableView {
    self.tableView = [UITableView plainTableViewWithTarget:self cellNibName:@"CustomerTableViewCell" cellId:kCellId];
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.topSpaceToView(self.sortView,0).leftEqualToView(self.view).rightEqualToView(self.view).bottomEqualToView(self.view);
}

#pragma mark =========== tableview delegate ===========
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrCellData.count;
}

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CustomerViewController *customerVC = [[CustomerViewController alloc] init];
    customerVC.isShowNavigationBar = NO;
    [self.navigationController pushViewController:customerVC animated:YES];
}

#pragma mark =========== searchbar delegate ===========

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.sortView.userInteractionEnabled = YES;
    [self.searchBar endEditing:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.sortView hide];
    self.sortView.userInteractionEnabled = NO;
    self.searchBar.showsCancelButton = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{

    self.searchBar.showsCancelButton = NO;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.sortView.userInteractionEnabled = YES;

}


- (void)popAction {
    [super popAction];
    [self.sortView hide];
}


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