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

#import "AddressViewController.h"
#import "ModifyShippingAddressView.h"

@interface AddressViewController ()<CityselectedDelegate>


/**
 *  城市选择器
 */
@property (nonatomic,strong) ModifyShippingAddressView *citySelecteview;

/**
 *  选中省
 */
@property (nonatomic,copy) NSString *provincesString;

/**
 * 选中城市
 */
@property (nonatomic,copy) NSString *cityString;

@end

@implementation AddressViewController


/**
 *  城市选择View
 *
 *  @return ModifyShippingAddressView
 */
- (ModifyShippingAddressView *)citySelecteview
{
    if (_citySelecteview == nil) {
        
        _citySelecteview = [[[NSBundle mainBundle] loadNibNamed:@"ModifyShippingAddressView"
                                                          owner:self options:nil] lastObject];
    }
    return _citySelecteview;
}


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

#pragma mark -布局
- (void)uiConfigAction
{
    self.recipientUserBackview.layer.masksToBounds = YES;
    self.recipientUserBackview.layer.cornerRadius = kCornerRadius;
    self.phoneNumberBackview.layer.masksToBounds = YES;
    self.phoneNumberBackview.layer.cornerRadius = kCornerRadius;
    self.detailsAddressBackview.layer.masksToBounds = YES;
    self.detailsAddressBackview.layer.cornerRadius = kCornerRadius;
    self.citySelected.layer.masksToBounds = YES;
    self.citySelected.layer.cornerRadius = kCornerRadius;
    self.delectAddressButton.layer.masksToBounds = YES;
    self.delectAddressButton.layer.cornerRadius = kCornerRadius;
    self.modifyButton.layer.masksToBounds = YES;
    self.modifyButton.layer.cornerRadius = kCornerRadius;
    [self.citySelected addTarget:self action:@selector(SelectedCityButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //判断是修改还是新增
    if (_isChange) {
        
        [self.delectAddressButton setTitle:@"删除" forState:UIControlStateNormal];
        [self.modifyButton setTitle:@"保存" forState:UIControlStateNormal];
    }
    
    self.recipientPerson.text = _model.name;
    self.PhoneNumber.text = _model.miblephone;
    [self.citySelected setTitle:_model.city forState:UIControlStateNormal];
    self.detailsAddress.text = _model.address;
}

#pragma mark -取消弹出的圆角
- (void)viewWillAppear:(BOOL)animated
{
    self.view.superview.layer.cornerRadius = 0;
}



#pragma mark -城市选择器
- (void)SelectedCityButtonClick
{
    
    self.citySelecteview.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 160);
    [self.view addSubview:self.citySelecteview];
    self.citySelecteview.delegate = self;
    [self.citySelecteview.selectedCityButton addTarget:self action:@selector(CompleteButton) forControlEvents:UIControlEventTouchUpInside];
    [UIView animateWithDuration:0.2 animations:^{
        
        self.citySelecteview.frame = CGRectMake(0, self.view.frame.size.height-160, self.view.frame.size.width, 160);
    }completion:^(BOOL finished) {
        
        self.citySelected.enabled = NO;
    }];
}


#pragma mark -完成按钮点击
- (void)CompleteButton
{
    [UIView animateWithDuration:0.2 animations:^{
        
        self.citySelecteview.frame = CGRectMake(0, ScreenHeight, self.view.frame.size.width, 160);
    }completion:^(BOOL finished) {
        
        [self.citySelecteview removeFromSuperview];
        self.citySelecteview = nil;
        self.citySelected.enabled = YES;
    }];
}



#pragma mark -关闭地址输入框
- (IBAction)turnoffAddressView:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 完成城市选择后
- (void)citySelected:(NSString *)cityString WithprovincesString:(NSString *)provincesString
{
    self.cityString = cityString;
    self.provincesString = provincesString;
    [self.citySelected setTitle:cityString forState:UIControlStateNormal];
}


#pragma mark 新增按钮点击，或者保存
- (IBAction)addAddressButtonClick:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"新增"]) {
       
        [self addAddressInformationRequest];
    }
    else if ([sender.currentTitle isEqualToString:@"保存"])
    {
        [self ChangeAddressInformationRequest];
    }
}


#pragma mark -新增地址信息
- (void)addAddressInformationRequest
{
    TOShippingAddrEntity *address = [[TOShippingAddrEntity alloc]init];
    address.consumerId = [Customermanager manager].customerID;
    address.name = self.recipientPerson.text;
    address.miblephone = self.PhoneNumber.text;
    address.city = [self.citySelected currentTitle];
    address.province = self.provincesString;
    address.address = self.detailsAddress.text;
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/shippingAddress/save"] WithRequestType:0 WithParameter:address WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            AddressModel *model = [[AddressModel alloc]init];
            model.name = self.recipientPerson.text;
            model.miblephone = self.PhoneNumber.text;
            model.city = self.citySelected.currentTitle;
            model.address = self.detailsAddress.text;
            model.consumerId = [Customermanager manager].customerID;
            model.fid = returnValue[@"data"];
            model.isSelected = NO;
            //增加地址
            if ([self.delegate respondsToSelector:@selector(addAddressCell:)]) {
                
                [self.delegate addAddressCell:model];
            }
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        NSLog(@"%@",error);
        [self RemoveMBProgressHUDLoding];
    }];
    
    
}
//@synthesize fid;
//@synthesize createDate;
//@synthesize sysOrgCode;
//@synthesize name;
//@synthesize miblephone;
//@synthesize province;
//@synthesize city;
//@synthesize country;
//@synthesize address;
//@synthesize state;
//@synthesize consumerId;


//#pragma mark -修改地址数据源
//- (void)setModel:(AddressModel *)model
//{
//    _model = model;
//    self.recipientPerson.text = model.name;
//    self.PhoneNumber.text = model.miblephone;
//    [self.citySelected setTitle:model.city forState:UIControlStateNormal];
//    self.detailsAddress.text = model.address;
//    
//}




#pragma mark -更改地址
- (void)ChangeAddressInformationRequest
{
    
    TOShippingAddrEntity *address = [[TOShippingAddrEntity alloc]init];
    address.consumerId = [Customermanager manager].customerID;
    address.name = self.recipientPerson.text;
    address.miblephone = self.PhoneNumber.text;
    address.city = [self.citySelected currentTitle];
    address.address = self.detailsAddress.text;
    address.fid = _model.fid;
    
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/shippingAddress/save"] WithRequestType:0 WithParameter:address WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            AddressModel *model = [[AddressModel alloc]init];
            model.name = self.recipientPerson.text;
            model.miblephone = self.PhoneNumber.text;
            model.city = self.citySelected.currentTitle;
            model.address = self.detailsAddress.text;
            model.consumerId = [Customermanager manager].customerID;
            model.fid = returnValue[@"data"];
            model.isSelected = NO;
            //修改地址
            if ([self.delegate respondsToSelector:@selector(ChangeAddresscell:Withcellindex:)]) {
                
                [self.delegate ChangeAddresscell:model Withcellindex:_cellindex];
            }
        }
        else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
        
    } WithFailureBlock:^(id error) {
        
        NSLog(@"%@",error);
        [self RemoveMBProgressHUDLoding];
    }];
}


#pragma mark -取消新增地址，或者删除
- (IBAction)cancelButtonClick:(UIButton *)sender {
    
    if ([sender.currentTitle isEqualToString:@"取消"]) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else if ([sender.currentTitle isEqualToString:@"删除"])
    {
        [self deleteAddressButtonClick];
    }
}


#pragma mark -删除收货地址
- (void)deleteAddressButtonClick
{
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@%@",ServerAddress,@"/shippingAddress/remove/",_model.fid] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            [self SuccessMBProgressView:@"删除成功"];
            if ([self.delegate respondsToSelector:@selector(delecteCell:)]) {
                
                [self.delegate delecteCell:_model.fid];
            }
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self RemoveMBProgressHUDLoding];
    }];
}


/*
#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
