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

#import "ClientViewController.h"
#import "InformationTableViewCell.h"
#import "ClientdetailsViewController.h"
#import "MyclientEntityModel.h"
#import "DeviceDirectionManager.h"

@interface ClientViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

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

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

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

@end

@implementation ClientViewController


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


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


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 开启
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


#pragma mark -布局
- (void)uiConfigAction
{
    //圆角
    self.customerNameBack.layer.masksToBounds = YES;
    self.customerNameBack.layer.cornerRadius = kCornerRadius;
    self.phoneNumberBack.layer.masksToBounds = YES;
    self.phoneNumberBack.layer.cornerRadius = kCornerRadius;
    self.companyNameBack.layer.masksToBounds = YES;
    self.companyNameBack.layer.cornerRadius = kCornerRadius;
    self.customerAddressBack.layer.masksToBounds = YES;
    self.customerAddressBack.layer.cornerRadius = kCornerRadius;
    self.addpersonInformationButton.layer.masksToBounds = YES;
    self.addpersonInformationButton.layer.cornerRadius = kCornerRadius;
    self.changePersonInformationButton.layer.masksToBounds = YES;
    self.changePersonInformationButton.layer.cornerRadius = kCornerRadius;
    self.indexPage = 1;
    self.customerHeader.userInteractionEnabled = YES;
    [self.customerHeader addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(customerHeaderClckAction:)]];
    
    //隐藏更改客户按钮
    self.changePersonInformationButton.hidden = YES;
    
    //代理
    self.informationTableview.delegate = self;
    self.informationTableview.dataSource = self;
    self.informationTableview.tableFooterView = [UIView new];
    self.searchPersonInformationField.delegate = self;
    //监听键盘落下的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboadrDismiss) name:UIKeyboardWillHideNotification object:nil];
    //设置当前客户通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SetupCurrentCustomer:) name:@"SETUPCURRENTCUSTOMER" object:nil];
    
    
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        ConsumerQueryCondition *condition = [[ConsumerQueryCondition alloc]init];
        condition.resellerCodeEquals = [[Shoppersmanager manager].Shoppers.employee.currentDepart  orgCode];
        DataPage *page = [[DataPage alloc]init];
        page.page = 1;
        condition.page = page;
        page.rows = KROWS;
        self.indexPage = 1;
        [self.informationTableview.mj_footer resetNoMoreData];
        [self getShoppersAssociatedCustomer:condition isRemoveArray:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.informationTableview.mj_header =headerRefresh;
    
    //进入刷新状态
    [self.informationTableview.mj_header beginRefreshing];
    //上拉加载
    self.informationTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (++ self.indexPage > self.totalPages) {
            [self.informationTableview.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            ConsumerQueryCondition *condition = [[ConsumerQueryCondition alloc]init];
            DataPage *page = [[DataPage alloc]init];
            page.page = self.indexPage ++;
            page.rows = KROWS;
            condition.page = page;
            [self getShoppersAssociatedCustomer:condition isRemoveArray:NO];
        }
    }];
}




#pragma mark -获取导购关联客户
- (void)getShoppersAssociatedCustomer:(ConsumerQueryCondition *)condition isRemoveArray:(BOOL)remove
{
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/query"] WithRequestType:0 WithParameter:condition WithReturnValueBlock:^(id returnValue) {
        
        self.informationTableview.emptyDataSetSource = self;
        self.informationTableview.emptyDataSetDelegate = self;
        [self RemoveMBProgressHUDLoding];
        [self endRefreshingForTableView:self.informationTableview];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            if (remove) {
                [self.CustomerresultArray removeAllObjects];
            }
            NSDictionary *datas = returnValue[@"data"];
            
            ConsumerPageResult *Customerresult = [[ConsumerPageResult alloc]initWithDictionary:datas error:nil];
            self.totalPages = [datas[@"totalpages"] intValue];
            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;
                 myclientModel.company = objc.company;
                
                [self.CustomerresultArray addObject:myclientModel];
            }
            //刷新后添加选中状态
            for (int i=0; i<self.CustomerresultArray.count; i++) {
                MyclientEntityModel *myclientModel = [self.CustomerresultArray objectAtIndex_opple:i];
                if ([[Customermanager manager].model.fid isEqualToString:myclientModel.fid]) {
                    InformationTableViewCell *cell = [self.informationTableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                    myclientModel.selectedState = YES;
                    cell.setCurrentCustomer.selected = YES;
                }
            }
            [self.informationTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [self RemoveMBProgressHUDLoding];
        [self promptCustomerWithString:@"网络连接已断开"];
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        [self endRefreshingForTableView:self.informationTableview];
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"information" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexNumber = indexPath.row;
    cell.model = [self.CustomerresultArray objectAtIndex_opple:indexPath.row];
    //清空其他选中状态
    [cell setBlockSeletced:^(NSInteger index) {
        [self SetCustomerButtonClick:index];
    }];
    return cell;
}

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

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


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
    ClientdetailsViewController *clientdetails = [storyboard instantiateViewControllerWithIdentifier:@"clientdetails"];
    clientdetails.model = [self.CustomerresultArray objectAtIndex_opple:indexPath.row];
    clientdetails.cellindex = indexPath.row;
    //设置当前客户
    [clientdetails setCurrentUserBlock:^(NSInteger index,NSString *title) {
        if ([title isEqualToString:@"设为当前客户"]) {
            InformationTableViewCell *cell = [self.informationTableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            [self SetCustomerButtonClick:index];
            cell.setCurrentCustomer.selected = YES;
            
        }else if ([title isEqualToString:@"退出当前客户"])
        {
            [self ExitCurrentCustomer];
            [self.addpersonInformationButton setTitle:@"添加客户信息" forState:UIControlStateNormal];
        }
    }];
    [self.navigationController pushViewController:clientdetails animated:YES];
}


#pragma mark -所有客户界面 设置当前客户通知回调
- (void)SetupCurrentCustomer:(NSNotification *)not
{
    NSDictionary *dict = not.object;
    for (InformationTableViewCell *cell in self.informationTableview.visibleCells) {
        
        cell.setCurrentCustomer.selected = NO;
    }
    for (MyclientEntityModel *model in self.CustomerresultArray) {
        
        if ([model.fid isEqualToString:dict[@"customerid"]]) {
            model.selectedState = YES;
        }else
        {
           model.selectedState = NO;
        }
    }
    if ([dict[@"title"] isEqualToString:@"设为当前客户"]) {
        MyclientEntityModel *model = dict[@"model"];
        self.customerNameField.text = model.name;
        self.phoneNumberField.text = model.mobile;
        self.customerAddress.text = model.address;
        [self.customerHeader sd_setImageWithURL:[NSURL URLWithString:model.picture] placeholderImage:TCImage(@"now")];
        //保存客户信息
        [Shoppersmanager manager].currentCustomer = YES;
        [Customermanager manager].model = model;
        [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
        self.changePersonInformationButton.hidden = NO;
        [self SetupUserShoppingCarNumberRequest];
        [self SetupUserRequest];
        [self ChangeCustomerName];
        
        self.customerNameField.enabled = NO;
        self.customerAddress.enabled = NO;
        self.phoneNumberField.enabled = NO;
        self.companyNameField.enabled = NO;
    }else if ([dict[@"title"] isEqualToString:@"退出当前客户"])
    {
        [self ExitCurrentCustomer];
    }
}

#pragma mark -设置为当前客户回调2
- (void)SetCustomerButtonClick:(NSInteger)index;
{
    
    for (InformationTableViewCell *cell in self.informationTableview.visibleCells) {
        
        cell.setCurrentCustomer.selected = NO;
    }
    for (MyclientEntityModel *model in self.CustomerresultArray) {
        
        model.selectedState = NO;
    }
    MyclientEntityModel *model = [self.CustomerresultArray objectAtIndex_opple:index];
    model.selectedState = YES;
    
    self.customerNameField.text = model.name;
    self.phoneNumberField.text = model.mobile;
    self.customerAddress.text = model.address;
    self.companyNameField.text = model.company;

    [self.customerHeader sd_setImageWithURL:[NSURL URLWithString:model.picture] placeholderImage:TCImage(@"now")];
    //保存客户信息
    [Shoppersmanager manager].currentCustomer = YES;
    [Customermanager manager].model = model;
    [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
    self.changePersonInformationButton.hidden = NO;
    [self SetupUserShoppingCarNumberRequest];
    [self SetupUserRequest];
    [self ChangeCustomerName];
    
    self.customerNameField.enabled = NO;
    self.customerAddress.enabled = NO;
    self.phoneNumberField.enabled = NO;
    self.companyNameField.enabled = NO;
}


#pragma mark -更改客户头像
- (void)customerHeaderClckAction:(UITapGestureRecognizer *)tap
{
    if (![Shoppersmanager manager].currentCustomer) {
        [self ErrorMBProgressView:@"请先设置当前客户"];
        return;
    }
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
    PcCamera.delegate = self;
    [DeviceDirectionManager instance].isHorizontal=YES;
    __weak typeof(self) weakSelf = self;
    [alertView addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
            PcCamera.allowsEditing = YES;
            [weakSelf presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [weakSelf ErrorMBProgressView:@"相机无法使用"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            PcCamera.allowsEditing = YES;
            [weakSelf presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [weakSelf ErrorMBProgressView:@"相册无法打开"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alertView dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark -拍照、从相册选择
#pragma -mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [DeviceDirectionManager instance].isHorizontal=NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *Headimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    __weak typeof(self) weskSelf = self;
    //修改并保存头像
    [self uploadUserHeader:Headimage completeBlock:^(NSString *string) {
        weskSelf.customerHeader.image = Headimage;
        [Customermanager manager].model.picture = string;
        for (int i=0;i<self.CustomerresultArray.count;i++) {
            MyclientEntityModel *customerModel = (MyclientEntityModel *)[self.CustomerresultArray objectAtIndex_opple:i];
            if ([customerModel.fid isEqualToString:[Customermanager manager].model.fid]) {
                customerModel.picture = string;
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.informationTableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
                break;
            }
        }
    }];
}

#pragma mark -保存选中头像、并上传
- (void)uploadUserHeader:(UIImage *)image completeBlock:(void(^)(NSString *string))complete
{
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
     __weak typeof(self) weskSelf = self;
    [[NetworkRequestClassManager Manager] UploadImageWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/system/upload"] WithRequestType:1 WithImageDatas:data WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [weskSelf modifyshoppersInformation:returnValue[@"data"] complete:^{
                complete(returnValue[@"data"]);
            }];
        }else
        {
            [weskSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithprogressBlock:^(double progress) {
        if (progress >= 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weskSelf.TCHud.labelText = @"上传完成";
                [weskSelf RemoveMBProgressHUDLoding];
            });
        }else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weskSelf ShowProgressView:progress];
            });
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weskSelf.TCHud.labelText = @"上传失败";
            [weskSelf RemoveMBProgressHUDLoding];
        });
    } WithFailureBlock:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weskSelf.TCHud.labelText = @"上传失败";
            [weskSelf RemoveMBProgressHUDLoding];
        });
    }];
}


#pragma mark -上传完成修改导购个人信息
- (void)modifyshoppersInformation:(NSString *)headerurl complete:(void(^)())block
{
    [self CreateMBProgressHUDLoding];
    MyclientEntityModel *customerEntity = [[MyclientEntityModel alloc]init];
    customerEntity = [Customermanager manager].model;
    customerEntity.picture = headerurl;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/save"] WithRequestType:0 WithParameter:customerEntity WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            block();
            [self SuccessMBProgressView:@"修改成功"];
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [self RemoveMBProgressHUDLoding];
    } WithFailureBlock:^(NSError *error) {
        [self RemoveMBProgressHUDLoding];
    }];
}



#pragma mark -更新用户名字
- (void)ChangeCustomerName
{
    MyclientEntityModel *model = [Customermanager manager].model;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGECUSTOMERNAME" object:model.name];
}


#pragma mark -设置为当前客户、查询购物车数量
- (void)SetupUserShoppingCarNumberRequest
{
    [self QueryShoppingCarNumber];
}



#pragma mark -设置为当前用户请求、写入访问时间
- (void)SetupUserRequest
{
    MyclientEntityModel *model = [Customermanager manager].model;
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@%@",ServerAddress,@"/consumer/saveLastVisitedTime?consumerId=",model.fid] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            NSLog(@"写入客户访问时间成功");
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        [self promptCustomerWithString:@"网络连接已断开"];
        
    } WithFailureBlock:^(id error) {
        
        NSLog(@"写入客户访问时间失败");
    }];
}


#pragma mark -添加客户信息、或者退出当前客户
- (IBAction)addCustomerInformationORExit:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"退出当前客户"]) {
       
        [self ExitCurrentCustomer];
        [sender setTitle:@"添加客户信息" forState:UIControlStateNormal];
        return;
    }
    [self addCustomerInformation:NO];
    
}

#pragma mark -退出当前客户
- (void)ExitCurrentCustomer
{
    self.customerNameField.text = nil;
    self.customerAddress.text = nil;
    self.phoneNumberField.text = nil;
    self.companyNameField.text = nil;
    self.customerNameField.enabled = YES;
    self.customerAddress.enabled = YES;
    self.phoneNumberField.enabled = YES;
    self.companyNameField.enabled = YES;
    self.changePersonInformationButton.hidden = YES;
    [Shoppersmanager manager].currentCustomer = NO;
    [Customermanager manager].model = nil;
    self.customerHeader.image = TCImage(@"now");
    [self.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
    [self ChangeCustomerName];
    [self QueryShoppingCarNumber];
    //全部为为选中状态
    for (InformationTableViewCell *cell in self.informationTableview.visibleCells) {
        
        cell.setCurrentCustomer.selected = NO;
    }
    for (MyclientEntityModel *model in self.CustomerresultArray) {
        
        model.selectedState = NO;
    }
}

#pragma mark -添加客户信息请求 -新增、或者修改 ischange为真是新增
- (void)addCustomerInformation:(BOOL)isChange
{
    [self.view endEditing:YES];
    if (self.customerNameField.text.length == 0) {
        
        [self ErrorMBProgressView:@"客户名不能为空"];
        return;
    }
    if (self.phoneNumberField.text.length == 0) {
        
        [self ErrorMBProgressView:@"手机号码不能为空"];
        return;
    }
    
    NSString *phoneNumber = self.phoneNumberField.text;
    if (![HENLENSONG isValidateMobile:phoneNumber]) {
        
        [self ErrorMBProgressView:@"手机号码格式不正确"];
        return;
    }
    //客户信息类
    MyclientEntityModel *customerEntity = [[MyclientEntityModel alloc]init];
    customerEntity.createName = [Shoppersmanager manager].Shoppers.employee.realName;
    customerEntity.mobile = self.phoneNumberField.text;
    customerEntity.address = self.customerAddress.text;
    customerEntity.name = self.customerNameField.text;
    customerEntity.company = self.companyNameField.text;
    customerEntity.picture = [Customermanager manager].model.picture;
    //修改
    if (isChange) {
       customerEntity.fid = [Customermanager manager].model.fid;
    }
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/save"] WithRequestType:0 WithParameter:customerEntity WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            //进入刷新状态
            [self.informationTableview.mj_header beginRefreshing];
            //新增保存ID
            if (!isChange) {
                [Customermanager manager].model.fid = returnValue[@"data"];
                [self SuccessMBProgressView:@"新增成功"];
                [self addAddressInformationRequest];
            }else
            {
                [self SuccessMBProgressView:@"修改成功"];
                [self.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
            }
            //保存客户信息
            [Customermanager manager].model = customerEntity;
            [Shoppersmanager manager].currentCustomer = YES;
            [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
            self.changePersonInformationButton.hidden = NO;
            self.customerNameField.enabled = NO;
            self.customerAddress.enabled = NO;
            self.phoneNumberField.enabled = NO;
            self.companyNameField.enabled = NO;
            
            [self SetupUserShoppingCarNumberRequest];
            [self SetupUserRequest];
            [self ChangeCustomerName];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        [self RemoveMBProgressHUDLoding];
        [self promptCustomerWithString:@"网络连接已断开"];
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        
    }];
}


#pragma mark -新增客户成功写入默认地址信息
- (void)addAddressInformationRequest
{
    TOShippingAddrEntity *address = [[TOShippingAddrEntity alloc]init];
    address.consumerId = [Customermanager manager].model.fid;
    address.name = self.customerNameField.text;
    address.miblephone = self.phoneNumberField.text;
    address.address = self.customerAddress.text;
    
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/shippingAddress/save"] WithRequestType:0 WithParameter:address WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            NSLog(@"写入默认收货地址成功");
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        [self promptCustomerWithString:@"网络连接已断开"];
        
    } WithFailureBlock:^(id error) {
        
        NSLog(@"写入默认收货地址失败");
    }];
}


#pragma mark -更改客户信息
- (IBAction)changeCustomerInformation:(UIButton *)sender {
    
    
    if ([sender.currentTitle isEqualToString:@"保存"]) {
        
        [self.customerNameField resignFirstResponder];
        [sender setTitle:@"更改客户信息" forState:UIControlStateNormal];
         [self addCustomerInformation:YES];
    }else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.customerNameField becomeFirstResponder];
        });
        [sender setTitle:@"保存" forState:UIControlStateNormal];
    }
    self.customerNameField.enabled = YES;
    self.customerAddress.enabled = YES;
    self.phoneNumberField.enabled = YES;
    self.companyNameField.enabled = YES;
}



#pragma mark -UITextFieldDelegate代理 ----搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self searchCustomerInforMation];
    return YES;
}


#pragma amrk -搜索客户信息
- (void)searchCustomerInforMation
{
    if (self.searchPersonInformationField.text.length == 0) {
        
        [self ErrorMBProgressView:@"搜索信息不能为空"];
        return;
    }
    [self CreateMBProgressHUDLoding];
    ConsumerQueryCondition *searchCustomer = [[ConsumerQueryCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.page = 1;
    page.rows = 10;
    searchCustomer.page = page;
    searchCustomer.nameEquals = self.searchPersonInformationField.text;
    searchCustomer.mobileEquals = self.searchPersonInformationField.text;
    
    //request
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/query"] WithRequestType:0 WithParameter:searchCustomer WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            ConsumerPageResult *result = [[ConsumerPageResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [self.CustomerresultArray removeAllObjects];
            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.informationTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        [self RemoveMBProgressHUDLoding];
        [self promptCustomerWithString:@"网络连接已断开"];
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -键盘落下，判断更改信息按钮是否可见，可见则取消输入框的响应
- (void)KeyboadrDismiss
{
    if (!self.changePersonInformationButton.hidden) {
     
        self.customerNameField.enabled = NO;
        self.customerAddress.enabled = NO;
        self.phoneNumberField.enabled = NO;
        self.companyNameField.enabled = NO;
        [self.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
    }
}


#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

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