//
//  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 "YXPickerManager.h"
#import "InviterViewController.h"
#import "InviterNavigationViewController.h"

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

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

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

/**
 邀请人entity
 */
@property (nonatomic,strong) VDesignerEntity *inviterEntity;

@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;
        _condition.page = page;
    }
    return _condition;
}

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

- (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 -UI
- (void)uiConfigAction
{
    [self.addpersonInformationButton horizontalCenterImageAndTitle:5];
}

#pragma mark -设置默认门店地址
- (void)setupDefaultStoreAddress
{
    ToStoreAddress *storeAddress = [Shoppersmanager manager].storeAddress;
    [self.locationButton setTitle:[NSString stringWithFormat:@"%@-%@-%@",storeAddress.province,storeAddress.city,storeAddress.country] forState:UIControlStateNormal];
}

#pragma mark -添加监听
- (void)addObserver
{
    //用户头像
    [self.customerHeader addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(customerHeaderClckAction:)]];
    //设置当前客户通知
    [Notification addObserver:self selector:@selector(setupCurrentCustomer:) name:SETUPCURRENTCUSTOMER object:nil];
    //清空当前客户数据
    [Notification addObserver:self selector:@selector(exitCurrentCustomer) name:EMPTYCUSTOMERNAME object:nil];
}


#pragma mark -省市区选择
- (IBAction)addressChooseButtonClickAction:(UIButton *)sender {
    [self.view endEditing:YES];
    NSString *address = nil;
    ToStoreAddress *storeAddress = [Shoppersmanager manager].storeAddress;
    if (storeAddress) {
        address = [NSString stringWithFormat:@"%@-%@-%@",storeAddress.province,storeAddress.city,storeAddress.country];
    }
    if (![BaseViewController isBlankString:sender.currentTitle]) {
        address = sender.currentTitle;
    }
    [[YXPickerManager shareManager] showAddressPickerView:kMainBlueColor defaultAddress:address commitBlock:^(NSString *address, NSString *zipcode) {
        [sender setTitle:address forState:UIControlStateNormal];
    } cancelBlock:^{
        
    }];
}


#pragma mark -邀请人选择
- (IBAction)inviterButtonClickAction:(UIButton *)sender {
    [self.view endEditing:YES];
    InviterNavigationViewController *chooseNav = [InviterNavigationViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    InviterViewController *inviterVc = (InviterViewController *)chooseNav.visibleViewController;
    WS(weakSelf);
    [inviterVc setSelectedBlock:^(VDesignerEntity *entity) {
        weakSelf.inviterEntity = entity;
        [weakSelf.inviterButton setTitle:entity.userName forState:UIControlStateNormal];
        [weakSelf addCustomerInformation];
    }];
    chooseNav.preferredContentSize = CGSizeMake(ScreenHeight-300, ScreenHeight-300);
    chooseNav.modalPresentationStyle = UIModalPresentationFormSheet;
    UIPopoverPresentationController *pop = chooseNav.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = chooseNav.view;
    [self presentViewController:chooseNav animated:YES completion:nil];
}


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

#pragma mark -获取导购关联客户
- (void)getshoppersAssociatedCustomer:(ConsumerQueryCondition *)condition completed:(void(^)(ConsumerDesignerPageResult *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(GETshoppersCONSUMER)  withRequestType:ZERO withParameter:condition withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            ConsumerDesignerPageResult *customerResult = [[ConsumerDesignerPageResult 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];
            }
            //刷新后添加选中状态
            for (int i=0; i<weakSelf.customerResultArray.count; i++) {
                MyclientEntityModel *myclientModel = [weakSelf.customerResultArray objectAtIndex_opple:i];
                if ([[Customermanager manager].model.consumer.fid isEqualToString:myclientModel.consumer.fid]) {
                    InformationTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                    myclientModel.selectedState = YES;
                    cell.setCurrentCustomer.selected = YES;
                }
            }
        }
        else
        {
            [weakSelf endRefresh:EndRefreshDefault];
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        [weakSelf.tableView reloadData];

    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [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 = [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) {
        if ([title isEqualToString:@"设为当前客户"]) {
            InformationTableViewCell *cell = [weakSelf.tableView 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 pushViewController:clientdetails animated:YES];
}


#pragma mark -所有客户界面 设置当前客户通知回调
- (void)setupCurrentCustomer:(NSNotification *)not
{
    NSDictionary *dict = not.object;
    for (InformationTableViewCell *cell in self.tableView.visibleCells) {
        cell.setCurrentCustomer.selected = NO;
    }
    for (MyclientEntityModel *model in self.customerResultArray) {
        if ([model.consumer.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];
    }else if ([dict[@"title"] isEqualToString:@"退出当前客户"])
    {
        [self exitCurrentCustomer];
    }
    [self changeCustomerName];
}

#pragma mark -设置为当前客户回调2
- (void)setCustomerButtonClick:(NSInteger)index;
{
    for (InformationTableViewCell *cell in self.tableView.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.consumer.country]) {
        WS(weakSelf);
        ToStoreAddress *storeAddress = [Shoppersmanager manager].storeAddress;
        NSString *address = [NSString stringWithFormat:@"%@-%@-%@",storeAddress.province,storeAddress.city,storeAddress.country];
        [[YXPickerManager shareManager] showAddressPickerView:kMainBlueColor defaultAddress:address commitBlock:^(NSString *address, NSString *zipcode) {
            //省市区
            NSArray *addressArray = [address componentsSeparatedByString:@"-"];
            model.consumer.province = addressArray[0];
            model.consumer.city = addressArray[1];
            model.consumer.country = addressArray[2];
            model.selectedState = YES;
            //保存客户信息
            [Shoppersmanager manager].currentCustomer = YES;
            [Customermanager manager].model = model;
            [self setUpCurrentCustomerAssignment:model];
            [weakSelf addCustomerInformation];
            [weakSelf.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
        } cancelBlock:nil];
        
    }else {
        model.selectedState = YES;
        //保存客户信息
        [Shoppersmanager manager].currentCustomer = YES;
        [Customermanager manager].model = model;
        [self setUpCurrentCustomerAssignment:model];
        [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
    }
    [self changeCustomerName];
    [self.tableView reloadData];
}


#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.consumer.picture = string;
        for (int i=0;i<weskSelf.customerResultArray.count;i++) {
            MyclientEntityModel *customerModel = (MyclientEntityModel *)[weskSelf.customerResultArray objectAtIndex_opple:i];
            if ([customerModel.consumer.fid isEqualToString:[Customermanager manager].model.consumer.fid]) {
                customerModel.consumer.picture = string;
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [weskSelf.tableView 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.consumer.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.consumer.name];
}

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

#pragma mark -设置为当前用户请求、写入访问时间
- (void)setupUserRequest
{
    MyclientEntityModel *model = [Customermanager manager].model;
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@",SERVERREQUESTURL(SAVEVISITEDTIME),model.consumer.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];
}

#pragma mark -退出当前客户
- (void)exitCurrentCustomer
{
    self.customerNameField.text = nil;
    self.customerAddress.text = nil;
    self.phoneNumberField.text = nil;
    self.companyNameField.text = nil;
    [self.inviterButton setTitle:@"" forState:UIControlStateNormal];
    [self setupDefaultStoreAddress];
    [Shoppersmanager manager].currentCustomer = NO;
    [Customermanager manager].model = nil;
    self.customerHeader.image = TCImage(@"customer");
    [self changeCustomerName];
    [self queryShoppingCarNumber];
    for (InformationTableViewCell *cell in self.tableView.visibleCells) {
        cell.setCurrentCustomer.selected = NO;
    }
    for (MyclientEntityModel *model in self.customerResultArray) {
        model.selectedState = NO;
    }
}

#pragma mark -添加客户信息请求
- (void)addCustomerInformation
{
    [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 (![phoneNumber isTelephone]) {
        [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];
    TOConsumerEntity *consumer = [[TOConsumerEntity alloc] init];
    consumer.createName = [Shoppersmanager manager].shoppers.employee.realName;
    consumer.mobile = self.phoneNumberField.text;
    consumer.address = self.customerAddress.text;
    consumer.name = self.customerNameField.text;
    consumer.company = self.companyNameField.text;
    consumer.picture = [Customermanager manager].model.consumer.picture;
    //省市区
    NSArray *addressArray = [[self.locationButton currentTitle] componentsSeparatedByString:@"-"];
    consumer.province = addressArray[0];
    consumer.city = addressArray[1];
    consumer.country = addressArray[2];
    customerEntity.consumer = consumer;
    //修改/还是新增
    if ([Customermanager manager].model) {
       consumer.fid = [Customermanager manager].model.consumer.fid;
    }
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    NSString *inviterId = @"";
    if (self.inviterEntity) {
        inviterId = self.inviterEntity.fid;
        TODesignerCustomerEntity *entity = [[TODesignerCustomerEntity alloc] init];
        entity.designerCode = self.inviterEntity.userName;
        customerEntity.designerCustomer = entity;
    }
    NSString *urlsString = [NSString stringWithFormat:SERVERREQUESTURL(ADDCONSUMER),inviterId];
    [HTTP networkRequestWithURL:urlsString withRequestType:ZERO withParameter:consumer withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf.tableView.mj_header beginRefreshing];
            //新增保存ID
            if (![Customermanager manager].model) {
                customerEntity.consumer.fid = RESPONSE(returnValue);
                [Customermanager manager].model = customerEntity;
                [XBLoadingView showHUDViewWithSuccessText:@"新增成功" completeBlock:nil];
                [weakSelf addAddressInformationRequest];
            }else
            {
                [XBLoadingView showHUDViewWithSuccessText:@"修改成功" completeBlock:nil];
            }
            //保存客户信息
            [Customermanager manager].model = customerEntity;
            [Shoppersmanager manager].currentCustomer = YES;
            [weakSelf.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
            [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.consumer.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 -UITextFieldDelegate代理 ----搜索、完成
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if (textField.returnKeyType == UIReturnKeyDone) {
        [self addCustomerInformation];
        return YES;
    }
    [self searchCustomerInforMation];
    return YES;
}


#pragma amrk -搜索客户信息
- (void)searchCustomerInforMation
{
    if ([BaseViewController isBlankString:self.searchPersonInformationField.text]) {
        self.condition.nameEquals = nil;
        self.condition.mobileEquals = nil;
        self.condition.resellerCodeEquals = [Shoppersmanager manager].shoppers.employee.currentDepart.orgCode;
    }else {
        self.condition.resellerCodeEquals = nil;
        self.condition.nameEquals = self.searchPersonInformationField.text;
        self.condition.mobileEquals = self.searchPersonInformationField.text;
        self.condition.resellerCodeEquals = nil;
    }
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark -设置为当前客户赋值
- (void)setUpCurrentCustomerAssignment:(MyclientEntityModel *)model
{
    self.customerAddress.text = model.consumer.address;
    self.phoneNumberField.text = model.consumer.mobile;
    self.companyNameField.text = model.consumer.company;
    self.customerNameField.text = model.consumer.name;
    [self.inviterButton setTitle:model.designerCustomer.designerCode forState:UIControlStateNormal];
    [self.locationButton setTitle:[NSString stringWithFormat:@"%@-%@-%@",model.consumer.province,model.consumer.city,model.consumer.country] forState:UIControlStateNormal];
    [self.customerHeader sd_setImageWithURL:[NSURL URLWithString:model.consumer.picture] placeholderImage:ReplaceImage];
}




@end
