//
//  SSCardCollectBasicInfoController.m
//  Open
//
//  Created by 雷俊博 on 2019/11/20.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SSCardCollectBasicInfoController.h"
#import "SSCardCollectBasicInfoCell.h"
#import "SSCardCollectBasicInfo2Cell.h"
#import "UIView+frameAdjust.h"
#import "UITextView+ZWPlaceHolder.h"
#import "CityTypeSelectView.h"

#import "SSCardCollectSelectedAddressController.h"
#import "SSCardCollectOtherInfoController.h"

#import <IQKeyboardManager.h>

@interface SSCardCollectBasicInfoController ()<UIScrollViewDelegate,UITextFieldDelegate,UITextViewDelegate,UIScrollViewDelegate>
{
    //记录位置
       CGFloat currentMaxY;
    //记录当前选中输入框
    NSInteger selectedTag;
    
    
    //户籍输入框
    UITextField* tf_householdRegister;
    //地址输入框
    UITextView* tv_address;
    UITextView* tv_address2;
    
    //详细地址view
    UIView *address2View;
    
    //邮政
    UITextField *tf_post;
    UIView *postView;
    
    //电话
    UITextField *tf_phone;
    UIView *phoneView;
    
    //邮箱
    UITextField *tf_mobile;
    UIView *mobView;
    
    //下一步
    UIButton *MyBtn;
    
    //iOS,地址框高度
       CGFloat addressContentOffsetY;
    
    
    //现居地址高度
    CGFloat currentAddressHeight;
    
    
    
    
}

@property (nonatomic, strong)UIScrollView *scrollView;

@property (nonatomic, strong)UIView *backView;

@property (nonatomic, strong)UIButton *btn_city;


@end

@implementation SSCardCollectBasicInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.scrollView];
    
    [self confirmNavBav];
    [self setupUI];
    
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    
    addressContentOffsetY = 58;
    currentAddressHeight = 58;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}


- (void)confirmNavBav
{
    UIButton *btn_back = [UIButton buttonWithType:UIButtonTypeCustom];
    btn_back.frame = CGRectMake(0, 0, 60, 40);
    
    [btn_back setTitle:@"返回" forState:UIControlStateNormal];
    [btn_back setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    btn_back.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn_back setImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    [btn_back addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [btn_back layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btn_back];
    if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7) {
        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negativeSpacer.width = -15;
        self.navigationItem.leftBarButtonItems = @[negativeSpacer, backItem];
    }else{
        self.navigationItem.leftBarButtonItem = backItem;
    }
}

- (void)setupUI
{
    NSArray *titleArray = @[@"*户籍性质",@"监护人姓名",@"监护人证件号",@"*现居地址",@"*详细地址",@"邮政编码",@"*联系电话",@"电子邮箱"];
    
    NSArray *placeArray = @[@"请选择户籍性质",@"请填写监护人姓名",@"请填写监护人身份证号码",@"请选择所居地区",@"请输入详细地址",@"请填写邮政编码",@"请填写联系电话",@"请填写邮政地址"];
    
    for (int i = 0; i < titleArray.count; i++) {
        
        if (i == 3 || i == 4) {
            currentMaxY = [self creatLine2WithLeftStr:titleArray[i] right:placeArray[i] height:58 index:i];
        }else{
            currentMaxY = [self creatLineWithLeftStr:titleArray[i] right:placeArray[i] height:58 index:i];
        }
       
    }
    
   currentMaxY = [self creatBtn];
    
          
}

- (CGFloat)creatLineWithLeftStr:(NSString *)leftName right:(NSString *)rightName height:(CGFloat)height index:(NSInteger)index
{
    NSArray *Bundle = [[NSBundle mainBundle]loadNibNamed:@"SSCardCollectBasicInfoCell" owner:self options:nil];
    SSCardCollectBasicInfoCell *view = [Bundle objectAtIndex:0];
    
    view.frame = CGRectMake(0, currentMaxY, ScreenWidth, height);
    
     [self.backView addSubview:view];
    
    view.lb_left.text = leftName;
    view.tf_right.placeholder = rightName;
    
    view.tf_right.delegate = self;
    
    if (index ==0) {
        view.img_arrow.hidden = NO;
    }
    
    view.tf_right.tag = 200 + index;
    
    
    if (index == 0) {
        
        tf_householdRegister = view.tf_right;
        
    }else if (index == 5){
        tf_post = view.tf_right;
        postView = view;
    }else if (index == 6){
        tf_phone = view.tf_right;
        phoneView = view;
    }else if (index == 7){
        tf_mobile = view.tf_right;
        mobView = view;
    }
    
    self.backView.height = view.maxY + 50;
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
    
    
    
     return view.maxY;
}
- (CGFloat)creatLine2WithLeftStr:(NSString *)leftName right:(NSString *)rightName height:(CGFloat)height index:(NSInteger)index
{
    NSArray *Bundle = [[NSBundle mainBundle]loadNibNamed:@"SSCardCollectBasicInfo2Cell" owner:self options:nil];
    SSCardCollectBasicInfo2Cell *view = [Bundle objectAtIndex:0];
    
    view.frame = CGRectMake(0, currentMaxY, ScreenWidth, height);
    
     [self.backView addSubview:view];
    
    view.lb_title.text = leftName;
    view.tv_address.placeholder = rightName;
    
    view.tv_address.delegate = self;
    
    
    view.img_arrow.hidden = (index == 4);
    
    view.tv_address.tag = 200 + index;
    
    if (index == 3) {
        tv_address = view.tv_address;
    }else if (index == 4){
        tv_address2 = view.tv_address;
        address2View = view;
    }
    
    self.backView.height = view.maxY + 50;
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
    
    return view.maxY;
    
}

- (CGFloat)creatBtn
{
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    
    [nextBtn setBackgroundColor:K_MainColor];
    
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    nextBtn.frame = CGRectMake(10, currentMaxY + 50, ScreenWidth - 20, 45);
    
    nextBtn.layer.cornerRadius = 5;
    
    [nextBtn addTarget:self action:@selector(goToNextVC:) forControlEvents:UIControlEventTouchUpInside];
    
   
    
    [self.backView addSubview:nextBtn];
    
     MyBtn  = nextBtn;
    
    self.backView.height = nextBtn.maxY + 50;
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
    
    return nextBtn.maxY;
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField  == tf_householdRegister) {
        
        [CityTypeSelectView show2CityTypeViewWithResultBlock:^(NSString * _Nonnull selectCityType) {
           
            if (selectCityType) {
                textField.text = selectCityType;
            }
        }];
        
        return NO;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    NSLog(@"%s",__func__);
    
    selectedTag = textField.tag;
}




#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    NSLog(@"%s",__func__);
    selectedTag = textView.tag;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if (textView == tv_address) {
        SSCardCollectSelectedAddressController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"SSCardCollectSelectedAddressController"];
           vc.title = @"选择地址";
        vc.block = ^(NSString * _Nonnull str) {
            textView.text = str;
            
            UIView *view  = textView.superview.superview;
            CGRect frame = view.frame;
            float height = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)].height;
            frame.size.height = height > 36 ? (height + 22) + 0.5 : 58;
            self->currentAddressHeight = frame.size.height;
            
            self->addressContentOffsetY = self->addressContentOffsetY - 58 + self->currentAddressHeight;
            view.frame = frame;
            
            self->address2View.minY = view.maxY;
            self->postView.minY = self->address2View.maxY;
            self->phoneView.minY = self->postView.maxY;
            self->mobView.minY = self->phoneView.maxY;
            
            self->MyBtn.minY = self->mobView.maxY + 50;
            self.backView.height = self->MyBtn.maxY + 50;
            self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
            
            [self->tv_address2 becomeFirstResponder];
            
        };
           [self.navigationController pushViewController:vc animated:YES];
        
        return NO;
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
       UIView *view  = textView.superview.superview;
        CGRect frame = view.frame;
        float height = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)].height;
        
    
       
        frame.size.height = height > 36 ? (height + 22) + 0.5 : 58;
        height = frame.size.height;
        view.frame = frame;
        addressContentOffsetY = 58 + height ;
//
//
//
//    NSLog(@"addressContentOffsetY:%f",addressContentOffsetY);
//
    
    if (textView == tv_address) {
        address2View.minY = view.maxY;
        postView.minY = address2View.maxY;
        phoneView.minY = postView.maxY;
        mobView.minY = phoneView.maxY;
        MyBtn.minY = mobView.maxY + 50;
        self.backView.height = MyBtn.maxY + 50;
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
        
    }else if (textView == tv_address2){
        postView.minY = view.maxY;
        phoneView.minY = postView.maxY;
        mobView.minY = phoneView.maxY;
        MyBtn.minY = mobView.maxY + 50;
        self.backView.height = MyBtn.maxY + 50;
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
        
        [self.scrollView setContentOffset:CGPointMake(0,  58+ self->addressContentOffsetY - cl_kNavigationBarHeight ) animated:NO];
    }
//        departmentView.minY = view.maxY;
//        dateView.minY = departmentView.maxY;
//        self.topView.height = dateView.maxY + 50;
//        self.backView.height = dateView.maxY + 50;
//       self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.backView.height);
       
}



#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
    NSLog(@"偏移量:%f",scrollView.contentOffset.y);
}


#pragma mark - 通知
-(void)keyboardWillShow:(NSNotification *)notification
{
    NSLog(@"%s",__func__);
    
    NSDictionary *userInfo = [notification userInfo];
    CGFloat duration = [[userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
//    CGRect rect = [[userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"]CGRectValue];
    
   
    
    if (selectedTag < 203) {
        [UIView animateWithDuration:duration animations:^{
            [self.scrollView setContentOffset:CGPointMake(0, 58  - cl_kNavigationBarHeight ) animated:NO];
           }];
    }else if (selectedTag == 204){
        [UIView animateWithDuration:duration animations:^{
            [self.scrollView setContentOffset:CGPointMake(0, 58  + addressContentOffsetY  - cl_kNavigationBarHeight ) animated:NO];
        }];
        
    }else{
        [UIView animateWithDuration:duration animations:^{
            [self.scrollView setContentOffset:CGPointMake(0, 58 * 3  + addressContentOffsetY  - cl_kNavigationBarHeight ) animated:YES];
        }];
    }
   
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    //NSLog(@"keyboardWillHide:%@",notification);
    
    NSDictionary *userInfo = [notification userInfo];
    CGFloat duration = [[userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        [self.scrollView setContentOffset:CGPointMake(0, -cl_kNavigationBarHeight) animated:YES];
    }];
}

#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goToNextVC:(UIButton *)sender
{
    SSCardCollectOtherInfoController *vc = [[SSCardCollectOtherInfoController alloc]init];
    
    vc.title = @"其他信息";
    
    [self.navigationController pushViewController:vc animated:YES];
    
}



#pragma mark - getters and setters

- (UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    }
    return _backView;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight);
        
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        
        
        _scrollView.delegate = self;
        
        [_scrollView addSubview:self.backView];
    }
    return _scrollView;
}



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