//
//  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"
#import "MJRefresh.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, strong) NSMutableArray *results;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *field; //排序的字段
@property (nonatomic, copy) NSString *direction;  //排序的顺序 升序或降序
@property (nonatomic, copy) NSString *customerCreateDate;
@property (nonatomic, strong) id phoneNo;


@end

@implementation CustomerManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBacroundColor;
    self.page = 0;
    self.phoneNo = [NSNull null];
    [self setUpDefaultConditions];
    [self setUpSearchBar];
    [self setUpSortView];
    [self setUptableView];
    [self setUpData];
    // Do any additional setup after loading the view.
}

- (void)setUpDefaultConditions {
    self.field = @"commission";
    self.direction = @"desc";
    self.customerCreateDate = @"2011-04-09 00:00:00";
}



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

- (NSMutableArray *)results {
    if (!_results) {
        _results = [NSMutableArray array];
    }
    return _results;
}

- (void)setUpData {
    WS(weakSelf);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPCilent shareCilent] POST:@"reseller/customer/query" parameters:[self getParams] success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

        
        if ([responseObject[@"code"] isEqualToNumber:@0]) {
            NSMutableArray *arr = weakSelf.searchBar.isFirstResponder ? weakSelf.results : weakSelf.arrCellData;
            
            for (NSDictionary *dic in responseObject[@"queryResult"]) {
                JavenCustomer *customer = [JavenCustomer modelObjectWithDictionary:dic];
                [arr addObject:customer];
            }
            if ([responseObject[@"queryResult"] count] < kPageSize) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            [weakSelf.tableView reloadData];
        }else{
            [MBProgressHUD Javen_showError:responseObject[@"message"] onView:weakSelf.view delay:0.7 complete:nil];

        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];

    }];
}

- (NSDictionary *)getParams
{
    NSDictionary *searchParams = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                  @"parameters" : @[kDomain]},
                                                                @{@"operation" : @"createInfo.time between",
                                                                  @"parameters" : @[self.customerCreateDate, [NSNull null]]},
                                                                @{@"operation" : @"reseller uuid equals",
                                                                  @"parameters" : @[[UserInfo shareInstance].reseller.uuid]}
                                                                ,
                                                                @{@"operation" : @"consumer mobilephone equals",
                                                                  @"parameters" : @[_phoneNo]}
                                                                ],
                                              @"orders" : @[@{@"field" : self.field,
                                                              @"direction" : self.direction}],
                                              @"pageSize" : @(kPageSize),
                                              @"page" : @(self.page),
                                              @"probePages" : @0},
                             @"fetchParts" : @[@""]};
    
    NSDictionary *params = @{@"defintion" : @{@"conditions" : @[@{@"operation" : @"domain equals",
                                                                        @"parameters" : @[kDomain]},
                                                                      @{@"operation" : @"createInfo.time between",
                                                                        @"parameters" : @[self.customerCreateDate, [NSNull null]]},
                                                                      @{@"operation" : @"reseller uuid equals",
                                                                        @"parameters" : @[[UserInfo shareInstance].reseller.uuid]}
                                                                      ],
                                                    @"orders" : @[@{@"field" : self.field,
                                                                    @"direction" : self.direction}],
                                                    @"pageSize" : @(kPageSize),
                                                    @"page" : @(self.page),
                                                    @"probePages" : @0},
                                   @"fetchParts" : @[@""]};
    
    return self.searchBar.isFirstResponder ? searchParams : params;
}


- (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 {
    self.page = 0;
    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 {
    self.page = 0;
    switch (row) {
        case 0:
        {
            self.field = @"commission";
            self.direction = @"desc";
            self.customerCreateDate = @"2011-04-09 00:00:00";
        }
            break;
        case 1://今日新增
        {
            
            NSDateFormatter *f = [[NSDateFormatter alloc] init];
            [f setDateFormat:@"yyyy-MM-dd 00:00:00"];
            NSString *dateStr = [f stringFromDate:[NSDate date]];
            
            self.customerCreateDate = dateStr;
        }
            break;
        case 2://本周新增
        {
            NSDate *aweekBefore = [NSDate dateWithTimeIntervalSinceNow:-24*60*60*7];
            NSDateFormatter *f = [[NSDateFormatter alloc] init];
            [f setDateFormat:@"yyyy-MM-dd 00:00:00"];
            NSString *dateStr = [f stringFromDate:aweekBefore];
            
            self.customerCreateDate = dateStr;
        }
            break;
            
        default:
            break;
    }
    [self resetReloadData];
}

//改变排序条件之后重新请求数据
- (void)resetReloadData {
    [self.results removeAllObjects];
    [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);
    
    WS(weakSelf)
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page += 1;
        [weakSelf setUpData];
    }];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId forIndexPath:indexPath];
    
    if (self.searchBar.isFirstResponder) {
        [cell cellwithModel:self.results[indexPath.row]];
    }else{
        [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];
    [self.searchBar resignFirstResponder];
    if (self.searchBar.isFirstResponder && self.results.count > 0) {
        CustomerViewController *customerVC = [[CustomerViewController alloc] init];
        customerVC.isShowNavigationBar = NO;
        customerVC.customer = self.results[indexPath.row];
        [self.navigationController pushViewController:customerVC animated:YES];
    }else{
        CustomerViewController *customerVC = [[CustomerViewController alloc] init];
        customerVC.isShowNavigationBar = NO;
        customerVC.customer = self.arrCellData[indexPath.row];
        [self.navigationController pushViewController:customerVC animated:YES];
    }

}

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

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

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.phoneNo = [NSNull null];
    self.searchBar.text = @"";
    self.phoneNo = [NSNull null];
    [self.searchBar endEditing:YES];
    [self.tableView reloadData];
}

- (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;
    [self.results removeAllObjects];
    [self setUpDefaultConditions];
    [self setUpData];
    
}


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


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"customerManagerment"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"customerManagerment"];
}

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