//
//  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"
#import "PerfectInformationViewController.h"
#import "MOFSPickerManager.h"

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

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

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

/**
 *  查询条件
 */
@property (nonatomic,strong) ConsumerQueryCondition *condition;


@property (nonatomic,copy) NSString *nameString;
@property (nonatomic,copy) NSString *phoneNumberString;
@property (nonatomic,copy) NSString *companyString;
@property (nonatomic,copy) NSString *addressString;

@end

@implementation ClientViewController


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

- (ConsumerQueryCondition *)condition
{
    if (!_condition) {
        _condition = [[ConsumerQueryCondition alloc]init];
        _condition.resellerCodeEquals = [Shoppersmanager manager].shoppers.employee.currentDepart.orgCode;
        DataPage *page = [[DataPage alloc]init];
        page.sort = @"createDate";
        page.order = @"desc";
        page.rows = KROWS;
        self.condition.page = page;
    }
    return _condition;
}

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

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

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

#pragma mark -布局
- (void)uiConfigAction
{
    ToStoreAddress *storeAddress = [Shoppersmanager manager].storeAddress;
    [self.locationButton setTitle:[NSString stringWithFormat:@"%@-%@-%@",storeAddress.province,storeAddress.city,storeAddress.country] forState:UIControlStateNormal];
    self.changePersonInformationButton.hidden = YES;
    self.informationTableview.tableFooterView = [UIView new];
}

#pragma mark -添加监听
- (void)addaddObserver
{
    //用户头像
    [self.customerHeader addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(customerHeaderClckAction:)]];
    //监听键盘落下的通知
    [Notification addObserver:self selector:@selector(keyboadrDismiss) name:UIKeyboardWillHideNotification object:nil];
    //设置当前客户通知
    [Notification addObserver:self selector:@selector(setupCurrentCustomer:) name:@"SETUPCURRENTCUSTOMER" object:nil];
    //清空当前客户数据
    [Notification addObserver:self selector:@selector(exitCurrentCustomer) name:@"EMPTYCUSTOMERNAME" object:nil];
    //监听输入变化
    [self.customerNameField addTarget:self action:@selector(nameChange:) forControlEvents:UIControlEventEditingChanged];
    [self.phoneNumberField addTarget:self action:@selector(phoneNumberChange:) forControlEvents:UIControlEventEditingChanged];
    [self.companyNameField addTarget:self action:@selector(companyChange:) forControlEvents:UIControlEventEditingChanged];
    [self.customerAddress addTarget:self action:@selector(addressChange:) forControlEvents:UIControlEventEditingChanged];
}


#pragma mark -省市区选择
- (IBAction)addressChooseButtonClickAction:(UIButton *)sender {
    
    [[MOFSPickerManager shareManger] showMOFSAddressPickerWithTitle:@"选择城市" cancelTitle:@"取消" commitTitle:@"完成" commitBlock:^(NSString *address, NSString *zipcode) {
        [sender setTitle:address forState:UIControlStateNormal];
        [self.changePersonInformationButton setTitle:@"保存" forState:UIControlStateNormal];
    } cancelBlock:^{
        
    }];
}

#pragma mark -名称变化时
- (void)nameChange:(UITextField *)textField
{
    self.nameString = textField.text;
}

#pragma mark -手机号码变化时
- (void)phoneNumberChange:(UITextField *)textField
{
    self.phoneNumberString = textField.text;
}

#pragma mark -公司名称变化时
- (void)companyChange:(UITextField *)textField
{
    self.companyString = textField.text;
}

#pragma mark -客户地址变化时
- (void)addressChange:(UITextField *)textField
{
    self.addressString= textField.text;
}

#pragma mark -设置刷新
- (void)setUpRefresh
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        
        weakSelf.condition.page.page = ONE;
        [weakSelf.informationTableview.mj_footer resetNoMoreData];
        [weakSelf getshoppersAssociatedCustomer:weakSelf.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 (++ weakSelf.condition.page.page > weakSelf.totalPages) {
            [weakSelf.informationTableview.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getshoppersAssociatedCustomer:weakSelf.condition isRemoveArray:NO];
        }
    }];
    self.informationTableview.mj_footer.automaticallyHidden = YES;
}

#pragma mark -获取导购关联客户
- (void)getshoppersAssociatedCustomer:(ConsumerQueryCondition *)condition isRemoveArray:(BOOL)remove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(GETshoppersCONSUMER)  withRequestType:ZERO withParameter:condition withReturnValueBlock:^(id returnValue) {
        
        weakSelf.informationTableview.emptyDataSetSource = weakSelf;
        weakSelf.informationTableview.emptyDataSetDelegate = weakSelf;
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefreshingForTableView:weakSelf.informationTableview];
        if (RESULT(returnValue)) {
            
            if (remove) {
                [weakSelf.CustomerresultArray removeAllObjects];
            }
            NSDictionary *datas = RESPONSE(returnValue);
            ConsumerPageResult *Customerresult = [[ConsumerPageResult alloc]initWithDictionary:datas error:nil];
            weakSelf.totalPages = [datas[@"totalpages"] intValue];
            for (TOConsumerEntity *objc in Customerresult.results) {
                
                 MyclientEntityModel *myclientModel = [[MyclientEntityModel alloc]initWithDictionary:[objc toDictionary] error:nil];
                [weakSelf.CustomerresultArray addObject:myclientModel];
            }
            //刷新后添加选中状态
            for (int i=0; i<weakSelf.CustomerresultArray.count; i++) {
                MyclientEntityModel *myclientModel = [weakSelf.CustomerresultArray objectAtIndex_opple:i];
                if ([[Customermanager manager].model.fid isEqualToString:myclientModel.fid]) {
                    InformationTableViewCell *cell = [weakSelf.informationTableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                    myclientModel.selectedState = YES;
                    cell.setCurrentCustomer.selected = YES;
                }
            }
            [weakSelf.informationTableview reloadData];
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefreshingForTableView:weakSelf.informationTableview];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


- (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];
    //清空其他选中状态
    WS(weakSelf);
    [cell setBlockSeletced:^(NSInteger index) {
        [weakSelf 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
{
    ClientdetailsViewController *clientdetails = [[[self class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"clientdetails"];
    clientdetails.model = [self.CustomerresultArray objectAtIndex_opple:indexPath.row];
    clientdetails.cellindex = indexPath.row;
    //设置当前客户
    WS(weakSelf);
    [clientdetails setCurrentUserBlock:^(NSInteger index,NSString *title) {
        if ([title isEqualToString:@"设为当前客户"]) {
            InformationTableViewCell *cell = [weakSelf.informationTableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
            [weakSelf setCustomerButtonClick:index];
            cell.setCurrentCustomer.selected = YES;
        }else if ([title isEqualToString:@"退出当前客户"])
        {
            [weakSelf exitCurrentCustomer];
            [weakSelf.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"];
        //保存客户信息
        [Shoppersmanager manager].currentCustomer = YES;
        [Customermanager manager].model = model;
        [self setUpCurrentCustomerAssignment:model];
        [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
        [self notEditing];
    }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];
    //判断省市区是否为空
    if ([[self class] isBlankString:model.country]) {
        WS(weakSelf);
        [[MOFSPickerManager shareManger] showMOFSAddressPickerWithTitle:@"选择城市" cancelTitle:@"取消" commitTitle:@"完成" commitBlock:^(NSString *address, NSString *zipcode) {
            //省市区
            NSArray *addressArray = [address componentsSeparatedByString:@"-"];
            model.province = addressArray[0];
            model.city = addressArray[1];
            model.country = addressArray[2];
            model.selectedState = YES;
            //保存客户信息
            [Shoppersmanager manager].currentCustomer = YES;
            [Customermanager manager].model = model;
            [self setUpCurrentCustomerAssignment:model];
            [weakSelf addCustomerInformation:YES];
            [weakSelf.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
            [weakSelf notEditing];
        } cancelBlock:nil];

    }else {
        model.selectedState = YES;
        //保存客户信息
        [Shoppersmanager manager].currentCustomer = YES;
        [Customermanager manager].model = model;
        [self setUpCurrentCustomerAssignment:model];
        [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
        [self notEditing];
    }
}

#pragma mark -不可编辑状态
- (void)notEditing {
    
    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) {
        [XBLoadingView showHUDViewWithText:@"请先设置当前客户"];
        return;
    }
    if([BaseViewController determineCameraPermissions]){
        UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
        PcCamera.delegate = self;
        [DeviceDirectionManager instance].isHorizontal=YES;
        WS(weakSelf);
        ShowAlertView(@"请选择", nil, @[@"拍照",@"从相册选择",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ZERO) {
                //拍照
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
                    PcCamera.allowsEditing = YES;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf presentViewController:PcCamera animated:YES completion:nil];
                    });
                }
                else
                {
                    [DeviceDirectionManager instance].isHorizontal=NO;
                    [XBLoadingView showHUDViewWithText:@"相机无法使用"];
                }
            }else if (index == ONE) {
                //从相册中选择
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                    [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                    PcCamera.allowsEditing = YES;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf presentViewController:PcCamera animated:YES completion:nil];
                    });
                }
                else
                {
                    [DeviceDirectionManager instance].isHorizontal=NO;
                    [XBLoadingView showHUDViewWithText:@"相册无法打开"];
                }
            }else {
                [DeviceDirectionManager instance].isHorizontal=NO;
            }
        });
    }
}

#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<weskSelf.CustomerresultArray.count;i++) {
            MyclientEntityModel *customerModel = (MyclientEntityModel *)[weskSelf.CustomerresultArray objectAtIndex_opple:i];
            if ([customerModel.fid isEqualToString:[Customermanager manager].model.fid]) {
                customerModel.picture = string;
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [weskSelf.informationTableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
                break;
            }
        }
    }];
}

#pragma mark -保存选中头像、并上传
- (void)uploadUserHeader:(UIImage *)image completeBlock:(void(^)(NSString *string))complete
{
    WS(weakSelf);
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    XBLoadingView *progressView = [XBLoadingView showHUDViewProgressLabel:@"上传头像中"];
    [HTTP uploadImageWithURL:SERVERREQUESTURL(UPLOADHEADER) withRequestType:ONE withImageDatas:data withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            [weakSelf modifyshoppersInformation:RESPONSE(returnValue) complete:^{
                complete(RESPONSE(returnValue));
            }];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withprogressBlock:^(double progress) {
        
        if (progress >= 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progressView.labelText = @"上传完成";
                [progressView hide:YES afterDelay:1];
            });
        }else{
            progressView.progress = progress;
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -上传完成修改导购个人信息
- (void)modifyshoppersInformation:(NSString *)headerurl complete:(void(^)())block
{
    [XBLoadingView showHUDViewWithDefault];
    MyclientEntityModel *customerEntity = nil;
    customerEntity = [Customermanager manager].model;
    customerEntity.picture = headerurl;
    [HTTP networkRequestWithURL:SERVERREQUESTURL(ADDCONSUMER)  withRequestType:ZERO withParameter:customerEntity withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [XBLoadingView showHUDViewWithSuccessText:@"修改成功" completeBlock:^{
                block();
            }];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


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


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

#pragma mark -设置为当前用户请求、写入访问时间
- (void)setupUserRequest
{
    MyclientEntityModel *model = [Customermanager manager].model;
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(SAVEVISITEDTIME),model.fid]  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            NSLog(@"写入客户访问时间成功");
        }
    } 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.locationButton setTitle:nil forState:UIControlStateNormal];
    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 ([BaseViewController isBlankString:self.customerNameField.text]) {
        [XBLoadingView showHUDViewWithText:@"客户名不能为空"];
        return;
    }
    if ([BaseViewController isBlankString:self.phoneNumberField.text]) {
        [XBLoadingView showHUDViewWithText:@"手机号码不能为空"];
        return;
    }
    NSString *phoneNumber = self.phoneNumberField.text;
    if (![HENLENSONG isValidateMobile:phoneNumber]) {
        [XBLoadingView showHUDViewWithText:@"手机号码格式不正确"];
        return;
    }
    if ([BaseViewController isBlankString:self.customerAddress.text]) {
        [XBLoadingView showHUDViewWithText:@"地址不能为空"];
        return;
    }
    if ([BaseViewController isBlankString:[self.locationButton currentTitle]]) {
        [XBLoadingView showHUDViewWithText:@"省市区不能为空"];
        return;
    }
    //客户信息类
    MyclientEntityModel *customerEntity = [[MyclientEntityModel alloc]init];
    customerEntity.createName = [Shoppersmanager manager].shoppers.employee.realName;
    customerEntity.mobile = self.phoneNumberString;
    customerEntity.address = self.addressString;
    customerEntity.name = self.nameString;
    customerEntity.company = self.companyString;
    customerEntity.picture = [Customermanager manager].model.picture;
    //修改
    if (isChange) {
       customerEntity.fid = [Customermanager manager].model.fid;
    }
    //省市区
    NSArray *addressArray = [[self.locationButton currentTitle] componentsSeparatedByString:@"-"];
    customerEntity.province = addressArray[0];
    customerEntity.city = addressArray[1];
    customerEntity.country = addressArray[2];
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(ADDCONSUMER)  withRequestType:ZERO withParameter:customerEntity withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf.informationTableview.mj_header beginRefreshing];
            //新增保存ID
            if (!isChange) {
                customerEntity.fid = RESPONSE(returnValue);
                [Customermanager manager].model = customerEntity;
                [XBLoadingView showHUDViewWithSuccessText:@"新增成功" completeBlock:nil];
                [weakSelf addAddressInformationRequest];
            }else
            {
                [XBLoadingView showHUDViewWithSuccessText:@"修改成功" completeBlock:nil];
                [weakSelf.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
            }
            //保存客户信息
            [Customermanager manager].model = customerEntity;
            [Shoppersmanager manager].currentCustomer = YES;
            [weakSelf.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
            [weakSelf notEditing];
            [weakSelf setUpCurrentCustomerAssignment:customerEntity];
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(id error) {
        [XBLoadingView hideHUDViewWithDefault];
    }];
}


#pragma mark -新增客户成功写入默认地址信息
- (void)addAddressInformationRequest
{
    TOShippingAddrEntity *address = [[TOShippingAddrEntity alloc]init];
    MyclientEntityModel *model = [Customermanager manager].model;
    address.consumerId = model.fid;
    address.name = self.customerNameField.text;
    address.miblephone = self.phoneNumberField.text;
    address.address = self.customerAddress.text;
    //省市区
    NSArray *addressArray = [[self.locationButton currentTitle] componentsSeparatedByString:@"-"];
    address.province = addressArray[0];
    address.city = addressArray[1];
    address.country = addressArray[2];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(ADDADDRESS)  withRequestType:ZERO withParameter:address withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            NSLog(@"写入默认收货地址成功");
        }
        else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }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
    {
        self.nameString = self.customerNameField.text;
        self.phoneNumberString = self.phoneNumberField.text;
        self.companyString = self.companyNameField.text;
        self.addressString = self.customerAddress.text;
        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;
    self.locationButton.enabled = YES;
}


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


#pragma amrk -搜索客户信息
- (void)searchCustomerInforMation
{
    if ([BaseViewController isBlankString:self.searchPersonInformationField.text]) {
        self.condition.nameEquals = nil;
        self.condition.mobileEquals = nil;
    }else {
        self.condition.nameEquals = self.searchPersonInformationField.text;
        self.condition.mobileEquals = self.searchPersonInformationField.text;
    }
    [self.informationTableview.mj_header beginRefreshing];
}


#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 -设置为当前客户赋值
- (void)setUpCurrentCustomerAssignment:(MyclientEntityModel *)model
{
    self.customerAddress.text = model.address;
    self.phoneNumberField.text = model.mobile;
    self.companyNameField.text = model.company;
    self.customerNameField.text = model.name;
    self.phoneNumberString = model.mobile;
    self.addressString = model.address;
    self.nameString = model.name;
    self.companyString = model.company;
    [self.locationButton setTitle:[NSString stringWithFormat:@"%@-%@-%@",model.province,model.city,model.country] forState:UIControlStateNormal];
    [self.customerHeader sd_setImageWithURL:[NSURL URLWithString:model.picture] placeholderImage:ReplaceImage];
}

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

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

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

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return 100;
}



@end