//
//  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"
@interface AllCustomerViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

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

/**
 *  当前页数
 */
@property (nonatomic,assign) int indexPage;

/**
 *  总页数
 */
@property (nonatomic,assign) int totalPages;
@end

@implementation AllCustomerViewController


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


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self uiConfigAction];
    
}

#pragma mark -视图渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        ConsumerQueryCondition *condition = [[ConsumerQueryCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = 1;
        page.rows = 10;
        condition.page = page;
        [self getShoppersAssociatedCustomer:condition isRemove:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.allCustomerTableview.mj_header = headerRefresh;
    [self.allCustomerTableview.mj_header beginRefreshing];

    //上拉加载
    self.allCustomerTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        ConsumerQueryCondition *condition = [[ConsumerQueryCondition alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.rows = 10;
        if (self.indexPage ++ > self.totalPages) {
            [self.allCustomerTableview.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            page.page = self.indexPage ++;
            condition.page = page;
            [self getShoppersAssociatedCustomer:condition isRemove:NO];
        }
       
    }];
}


#pragma mark -UI
- (void)uiConfigAction
{
    self.indexPage = 1;
    self.allCustomerTableview.dataSource = self;
    self.allCustomerTableview.delegate = self;
    self.searchTextfield.delegate = self;
    self.view.backgroundColor = kMainGrayColor;
    self.allCustomerTableview.backgroundColor = [UIColor clearColor];
    self.searchTextfield.returnKeyType = UIReturnKeySearch;
    
    //调整布局
    [self.begindateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.RecentlydateLabe.mas_right).mas_offset(0);
        make.top.equalTo(self.RecentlydateLabe).mas_offset(-4);
        make.width.mas_offset(120);
    }];
    [self.redesignLabe mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.begindateButton.mas_right).mas_offset(10);
        make.top.equalTo(self.RecentlydateLabe).mas_offset(2);
        make.width.mas_offset(20);
    }];
    [self.enddateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.redesignLabe.mas_right).mas_offset(10);
        make.top.equalTo(self.RecentlydateLabe).mas_offset(-4);
        make.width.mas_offset(120);
    }];
    
    //设置按钮时间
    [self.begindateButton setTitle:[self dateAsString:[NSDate date]] forState:UIControlStateNormal];
    [self.enddateButton setTitle:[self dateAsString:[NSDate date]] forState:UIControlStateNormal];
    
    
    self.begindateButton.layer.masksToBounds = YES;
    self.begindateButton.layer.cornerRadius = 10;
    self.enddateButton.layer.masksToBounds = YES;
    self.enddateButton.layer.cornerRadius = 10;
}



#pragma mark -获取导购关联客户
- (void)getShoppersAssociatedCustomer:(ConsumerQueryCondition *)condition isRemove:(BOOL)remove
{
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/query"] WithRequestType:0 WithParameter:condition WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        [self endRefreshingForTableView:self.allCustomerTableview];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (remove) {
                [self.CustomerresultArray removeAllObjects];
            }
            ConsumerPageResult *Customerresult = [[ConsumerPageResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            self.totalPages = (int)returnValue[@"data"][@"totalPages"];
            for (TOConsumerEntity *objc in Customerresult.results) {
                
                MyclientEntityModel *myclientModel = [[MyclientEntityModel alloc]init];
                myclientModel.fid = objc.fid;
                myclientModel.createName = objc.createName;
                myclientModel.createBy = objc.createBy;
                myclientModel.createDate = objc.createDate;
                myclientModel.sysOrgCode = objc.sysOrgCode;
                myclientModel.name = objc.name;
                myclientModel.mobile = objc.mobile;
                myclientModel.province = objc.province;
                myclientModel.city = objc.city;
                myclientModel.country = objc.country;
                myclientModel.address = objc.address;
                myclientModel.picture = objc.picture;
                myclientModel.lastVisitedTime = objc.lastVisitedTime;
                
                [self.CustomerresultArray addObject:myclientModel];
            }
            
            [self.allCustomerTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        [self endRefreshingForTableView:self.allCustomerTableview];
        [self RemoveMBProgressHUDLoding];
    }];
}



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



#pragma mark -开始筛选时间
- (IBAction)StartscreeningButtonClick:(UIButton *)sender {
    
    DateSelectedViewController *datevc = [[DateSelectedViewController alloc]init];
    //选中时间回调
    [datevc setSelectedDateBlock:^(NSDate *selectedDate) {
        
        [self.begindateButton setTitle:[self dateAsString:selectedDate] forState:UIControlStateNormal];
        [self 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 -时间转换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 {
    
    
    DateSelectedViewController *datevc = [[DateSelectedViewController alloc]init];
    //选中时间回调
    [datevc setSelectedDateBlock:^(NSDate *selectedDate) {
        
        [self.enddateButton setTitle:[self dateAsString:selectedDate] forState:UIControlStateNormal];
        [self 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];
    [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];
    ConsumerQueryCondition *searchCustomer = [[ConsumerQueryCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.page = 1;
    page.rows = 99999;
    searchCustomer.page = page;
    //比较两个NSDate的大小
    switch (result) {
        case -1://start < end
        {
            [formater setDateFormat:@"yyyy-MM-dd HH:dd:ss"];
            searchCustomer.createTimeBegin = [formater stringFromDate:[self ReturnZeroTime:date]];
            searchCustomer.createTimeEnd = [formater stringFromDate:[self ReturnZeroTime:date1]];
        }
            break;
        case 0://start == end
        {
            [formater setDateFormat:@"yyyy-MM-dd HH:dd:ss"];
            searchCustomer.createTimeBegin = [formater stringFromDate:[self ReturnZeroTime:date]];
            searchCustomer.createTimeEnd = [formater stringFromDate:[self ReturnZeroTime:date1]];
        }
            break;
        case 1://start > end
        {
            [formater setDateFormat:@"yyyy-MM-dd HH:dd:ss"];
            searchCustomer.createTimeBegin = [formater stringFromDate:[self ReturnZeroTime:date1]];
            searchCustomer.createTimeEnd = [formater stringFromDate:[self ReturnZeroTime:date]];
        }
            break;
            
        default:
            break;
    }
    
    [self searchCustomerInforMation:searchCustomer];
}


#pragma mark -返回某天零时的时间
- (NSDate *)ReturnZeroTime:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:date];
    components.hour = 8;
    components.minute = 0;
    components.second = 0;
    NSTimeInterval ts = (double)(int)[[calendar dateFromComponents:components] timeIntervalSince1970];
    return [NSDate dateWithTimeIntervalSince1970:ts];
}


#pragma mark -比较两个NSDate的大小
- (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

#pragma mark -Return键检测
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    ConsumerQueryCondition *searchCustomer = [[ConsumerQueryCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.page = 1;
    page.rows = 10;
    searchCustomer.page = page;
    searchCustomer.nameEquals = self.searchTextfield.text;
    searchCustomer.mobileEquals = self.searchTextfield.text;
    
    if (self.searchTextfield.text.length == 0) {
        
        [self ErrorMBProgressView:@"搜索信息不能为空"];
        return YES;
    }
    [self searchCustomerInforMation:searchCustomer];
    return YES;
}

#pragma amrk -搜索客户信息
- (void)searchCustomerInforMation:(ConsumerQueryCondition *)Condition
{

    
    [self CreateMBProgressHUDLoding];
    //request
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/query"] WithRequestType:0 WithParameter:Condition WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [self.CustomerresultArray removeAllObjects];
            ConsumerPageResult *result = [[ConsumerPageResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            self.totalPages = (int)returnValue[@"data"][@"totalPages"];
            for (TOConsumerEntity *objc in result.results) {
                
                MyclientEntityModel *myclientModel = [[MyclientEntityModel alloc]init];
                myclientModel.fid = objc.fid;
                myclientModel.createName = objc.createName;
                myclientModel.createBy = objc.createBy;
                myclientModel.createDate = objc.createDate;
                myclientModel.sysOrgCode = objc.sysOrgCode;
                myclientModel.name = objc.name;
                myclientModel.mobile = objc.mobile;
                myclientModel.province = objc.province;
                myclientModel.city = objc.city;
                myclientModel.country = objc.country;
                myclientModel.address = objc.address;
                myclientModel.picture = objc.picture;
                myclientModel.lastVisitedTime = objc.lastVisitedTime;
                [self.CustomerresultArray addObject:myclientModel];
            }
            [self.allCustomerTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}





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