//
//  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"

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

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

@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];
    [self getShoppersAssociatedCustomer];
}


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



#pragma mark -获取导购关联客户
- (void)getShoppersAssociatedCustomer
{
    
    [self CreateMBProgressHUDLoding];
    ConsumerQueryCondition *condition = [[ConsumerQueryCondition alloc]init];
    DataPage *page = [[DataPage alloc]init];
    page.page = 0;
    condition.page = page;
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/query"] WithRequestType:0 WithParameter:condition WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            ConsumerPageResult *Customerresult = [[ConsumerPageResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            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.informationTableview reloadData];
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}


- (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];
    [self.navigationController pushViewController:clientdetails animated:YES];
}





#pragma mark -设置为当前客户回调
- (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;
    //保存客户信息
    [Shoppersmanager manager].currentCustomer = YES;
    [Customermanager manager].customerID = model.fid;
    [Customermanager manager].customerName = model.name;
    [Customermanager manager].customerPhoneNumber = model.mobile;
    [Customermanager manager].companyAddress = model.address;
    [Customermanager manager].cutomerAddress = model.address;
    [self.addpersonInformationButton setTitle:@"退出当前客户" forState:UIControlStateNormal];
    self.changePersonInformationButton.hidden = NO;
}




#pragma mark -添加客户信息、或者退出当前客户
- (IBAction)addCustomerInformationORExit:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"退出当前客户"]) {
      
        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].customerID = nil;
        [self.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
        
        //全部为为选中状态
        for (InformationTableViewCell *cell in self.informationTableview.visibleCells) {
            
            cell.setCurrentCustomer.selected = NO;
        }
        for (MyclientEntityModel *model in self.CustomerresultArray) {
            
            model.selectedState = NO;
        }
        [sender setTitle:@"添加客户信息" forState:UIControlStateNormal];
        return;
    }
    [self addCustomerInformation:NO];
}


#pragma mark -添加客户信息请求 -新增、或者修改
- (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;
    }
    
    //客户信息类
    TOConsumerEntity *customerEntity = [[TOConsumerEntity alloc]init];
    customerEntity.createName = self.customerNameField.text;
    customerEntity.mobile = self.phoneNumberField.text;
    customerEntity.address = self.customerAddress.text;
    customerEntity.name = self.companyNameField.text;
    //修改
    if (isChange) {
       customerEntity.fid = [Customermanager manager].customerID;
    }
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/consumer/save"] WithRequestType:0 WithParameter:customerEntity WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            //新增保存ID
            if (!isChange) {
                [Customermanager manager].customerID = returnValue[@"data"];
                [self SuccessMBProgressView:@"新增成功"];
            }else
            {
                [self SuccessMBProgressView:@"修改成功"];
                [self.changePersonInformationButton setTitle:@"更改客户信息" forState:UIControlStateNormal];
            }
            //保存客户信息
            [Customermanager manager].customerName = customerEntity.name;
            [Customermanager manager].customerPhoneNumber = customerEntity.mobile;
            [Customermanager manager].companyAddress = customerEntity.address;
            [Customermanager manager].cutomerAddress = customerEntity.address;
            [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;
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
        
    }];
}


#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 = 0;
    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 error:nil];
            NSLog(@"%@",result);
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -键盘落下,判断更改信息按钮是否可见,可见则取消输入框的响应
- (void)KeyboadrDismiss
{
    if (!self.changePersonInformationButton.selected) {
     
        self.customerNameField.enabled = NO;
        self.customerAddress.enabled = NO;
        self.phoneNumberField.enabled = NO;
        self.companyNameField.enabled = NO;
    }
}


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