//
//  AllCustomerViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/5/6.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "AllCustomerViewController.h"
#import "AllCutomerTableViewCell.h"
#import "DateSelectedViewController.h"
#import "MyclientEntityModel.h"
#import "ClientdetailsViewController.h"

@interface AllCustomerViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

/**
 *  数据源
 */
@property (nonatomic,strong) NSMutableArray *customerResultArray;


@end

@implementation AllCustomerViewController


/**
 *  初始化客户数据源
 */
- (NSMutableArray *)customerResultArray
{
    if (_customerResultArray == nil) {
        
        _customerResultArray = [NSMutableArray array];
    }
    return _customerResultArray;
}

/**
 *  初始化参数模型
 */
- (ConsumerQueryCondition *)conditionModel
{
    if (!_conditionModel) {
        _conditionModel = [[ConsumerQueryCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _conditionModel.page = page;
        _conditionModel.resellerCodeEquals = [[Shoppersmanager manager].shoppers.employee.currentDepart  orgCode];
    }
    return _conditionModel;
}

#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 开启
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.searchTextfield.returnKeyType = UIReturnKeySearch;
    //设置按钮时间
    [self.begindateButton setTitle:[self dateAsString:[NSDate date]] forState:UIControlStateNormal];
    [self.enddateButton setTitle:[self dateAsString:[NSDate date]] forState:UIControlStateNormal];
    [self.enddateButton addCorner:10];
    [self.begindateButton addCorner:10];
}

#pragma mark -加载数据
- (void)loadWebDataSource
{
    WS(weakSelf);
    if (self.pullPageIndex == ONE) {
        [self.customerResultArray removeAllObjects];
    }
    self.conditionModel.page.page = self.pullPageIndex;
    [self getshoppersAssociatedCustomer:self.conditionModel completed:^(ConsumerPageResult *result) {
        if (weakSelf.pullPageIndex >= result.totalpages) {
            [weakSelf endRefresh:EndRefreshNotData];
        }else {
            [weakSelf endRefresh:EndRefreshDefault];
        }
    }];
}

#pragma mark -获取导购关联客户
- (void)getshoppersAssociatedCustomer:(ConsumerQueryCondition *)condition completed:(void(^)(ConsumerPageResult *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(GETshoppersCONSUMER)  withRequestType:ZERO withParameter:condition withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            ConsumerPageResult *customerResult = [[ConsumerPageResult alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(customerResult);
            for (TOConsumerEntity *objc in customerResult.results) {
                MyclientEntityModel *myclientModel = [[MyclientEntityModel alloc] initWithDictionary:[objc toDictionary] error:nil];
                [weakSelf.customerResultArray addObject:myclientModel];
            }
            [weakSelf.tableView reloadData];
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllCutomerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"allcustomercell" forIndexPath:indexPath];
    cell.contentBackView.layer.masksToBounds = YES;
    cell.contentBackView.layer.cornerRadius = kCornerRadius;
    cell.backgroundColor = [UIColor clearColor];
    cell.model = [self.customerResultArray objectAtIndex_opple:indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.customerResultArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 125;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClientdetailsViewController *clientdetails = [ClientdetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    clientdetails.model = [self.customerResultArray objectAtIndex_opple:indexPath.row];
    clientdetails.cellindex = indexPath.row;
    //设置当前客户
    WS(weakSelf);
    [clientdetails setCurrentUserBlock:^(NSInteger index,NSString *title) {
        
        NSString *customerID = [[weakSelf.customerResultArray objectAtIndex_opple:indexPath.row] fid];
        NSDictionary *dict = @{@"customerid":customerID,@"title":title,@"model":[weakSelf.customerResultArray objectAtIndex_opple:indexPath.row]};
        [Notification postNotificationName:@"SETUPCURRENTCUSTOMER" object:dict];
    }];
    [self pushViewController:clientdetails animated:YES];
}


#pragma mark -开始筛选时间
- (IBAction)StartScreeningButtonClick:(UIButton *)sender {
    
    DateSelectedViewController *datevc = [[DateSelectedViewController alloc]init];
    //选中时间回调
    WS(weakSelf);
    [datevc setSelectedDateBlock:^(NSDate *selectedDate) {
        [weakSelf.begindateButton setTitle:[weakSelf dateAsString:selectedDate] forState:UIControlStateNormal];
        [weakSelf CalltimeSearch];
    }];
    
    datevc.preferredContentSize = CGSizeMake(300, 250);
    datevc.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = datevc.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = datevc.view;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:datevc animated:YES completion:nil];
    });
}


#pragma mark -时间转换NSDate转NSString
- (NSString*)dateAsString:(NSDate*)date {
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString * timeString = [formatter stringFromDate:date];
    return timeString;
}

#pragma mark -结束筛选时间
- (IBAction)EndScreeningButtonClick:(UIButton *)sender {
    
    WS(weakSelf);
    DateSelectedViewController *datevc = [[DateSelectedViewController alloc]init];
    [datevc setSelectedDateBlock:^(NSDate *selectedDate) {
        [weakSelf.enddateButton setTitle:[weakSelf dateAsString:selectedDate] forState:UIControlStateNormal];
        [weakSelf CalltimeSearch];
        
    }];
    datevc.preferredContentSize = CGSizeMake(300, 250);
    datevc.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = datevc.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = datevc.view;
    [self presentViewController:datevc animated:YES completion:nil];
}


#pragma mark -调用时间段搜索
- (void)CalltimeSearch
{
    NSString *startString = self.begindateButton.currentTitle;
    NSString *endString = self.enddateButton.currentTitle;
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    NSDateFormatter* endformater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy-MM-dd"];
    NSDate* date = [formater dateFromString:startString];
    [formater setDateFormat:@"yyyy-MM-dd"];
    NSDate* date1 = [formater dateFromString:endString];
    
    //比较结果
    NSInteger result = [self compareOneDay:date withAnotherDay:date1];
    //比较两个NSDate的大小
    switch (result) {
        case -1://start < end
        {
            [formater setDateFormat:@"yyyy-MM-dd 00:00:01"];
            [endformater setDateFormat:@"yyyy-MM-dd 23:59:59"];
            self.conditionModel.createTimeBegin = [formater stringFromDate:date];
            self.conditionModel.createTimeEnd = [endformater stringFromDate:date1];
        }
            break;
        case 0://start == end
        {
            [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            self.conditionModel.createTimeBegin = nil;
            self.conditionModel.createTimeEnd = nil;
        }
            break;
        case 1://start > end
        {
            [formater setDateFormat:@"yyyy-MM-dd 00:00:01"];
            [endformater setDateFormat:@"yyyy-MM-dd 23:59:59"];
            self.conditionModel.createTimeBegin = [formater stringFromDate:date1];
            self.conditionModel.createTimeEnd = [endformater stringFromDate:date];
        }
            break;
            
        default:
            break;
    }
    self.conditionModel.nameEquals = nil;
    self.conditionModel.mobileEquals = nil;
    self.searchTextfield.text = nil;
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark -Return键检测
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.conditionModel.nameEquals = self.searchTextfield.text;
    self.conditionModel.mobileEquals = self.searchTextfield.text;
    if ([BaseViewController isBlankString:self.searchTextfield.text]) {
        self.conditionModel.nameEquals = nil;
        self.conditionModel.mobileEquals = nil;
    }
    [self.tableView.mj_header beginRefreshing];
    return YES;
}





@end
