//
//  ICRQInputPopup.m
//  XFFruit
//
//  Created by Xummer on 15/6/8.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRQInputPopup.h"

#define BTN_HEIGHT          (44)

@interface ICRQInputPopup () <UITextFieldDelegate>
@property (strong, nonatomic) IBTUIView *m_topView;
@property (strong, nonatomic) IBTUIButton *m_closeBtn;
@property (strong, nonatomic) IBTUIButton *m_bottomBtn;
@property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo;
@end

@implementation ICRQInputPopup

#pragma mark - Life Cycle
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    
    [self addKeyboardNotification];
    
    self.m_bEnableTapToDismiss = NO;
    self.m_bShowShowInCenter = YES;
    
    [self initTableViewInfo];
    
    return self;
}

- (void)initTableViewInfo {
    
    self.m_topView = [[IBTUIView alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = self.width,
        .size.height = BTN_HEIGHT
    }];
    
    self.m_topView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
    [self addSubview:_m_topView];
    
    IBTUILabel *titleLabel = [[IBTUILabel alloc] initWithFrame:_m_topView.bounds];
    titleLabel.text = @"填写内容";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor grayColor];
    [titleLabel autoresizingWithStrechFullSize];
    [_m_topView addSubview:titleLabel];
    
    self.m_closeBtn = [IBTUIButton buttonWithType:UIButtonTypeCustom];
    [_m_closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [_m_closeBtn setTitleColor:ICR_TINTCOLOR forState:UIControlStateNormal];
    _m_closeBtn.frame = (CGRect){
        .origin.x = _m_topView.width - 90,
        .origin.y = 0,
        .size.width = 90,
        .size.height = _m_topView.height
    };
    [_m_closeBtn addTarget:self action:@selector(dismissPopup)
          forControlEvents:UIControlEventTouchUpInside];
    _m_closeBtn.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_m_topView addSubview:_m_closeBtn];
    
    self.m_bottomBtn = [IBTUIButton buttonWithType:UIButtonTypeCustom];
    [_m_bottomBtn setTitle:@"保存" forState:UIControlStateNormal];
    [_m_bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_m_bottomBtn setBackgroundImage:[UIImage imageWithColor:ICR_ORANGE_BTN_COLOR]      forState:UIControlStateNormal];
    _m_bottomBtn.frame = (CGRect){
        .origin.x = 0,
        .origin.y = self.height - BTN_HEIGHT,
        .size.width = self.width,
        .size.height = BTN_HEIGHT
    };
    [_m_bottomBtn addTarget:self action:@selector(onBottomBtnAction:)
           forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_m_bottomBtn];
    
    self.m_tableViewInfo =
    [[IBTTableViewInfo alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = _m_topView.bottom,
        .size.width = self.width,
        .size.height = self.height - _m_bottomBtn.height - _m_topView.height
    } style:UITableViewStylePlain];
    
    IBTTableView *tableV = [_m_tableViewInfo getTableView];
    [self addSubview:tableV];
}

- (void)updateSuervyData:(NSArray *)arrDatas {
    [_m_tableViewInfo removeSectionAt:0];
    
    IBTTableViewSectionInfo *secInfo = [IBTTableViewSectionInfo sectionInfoDefaut];
    
    IBTTableViewCellInfo *cellInfo;
    
    for (NSString *nsTitle in arrDatas) {
        cellInfo = [IBTTableViewCellInfo editorCellForSel:nil
                                                   target:nil
                                                    title:[nsTitle stringByAppendingString:@":"]
                                                   margin:0
                                                      tip:@"请输入"
                                              autoCorrect:NO
                                                    focus:NO
                                                     text:nil];
        
        [cellInfo addUserInfoValue:@( NSTextAlignmentRight )
                            forKey:CInfoEditorAlignKey];
        
        [cellInfo addUserInfoValue:@( UIKeyboardTypeDefault )
                            forKey:CInfoEditorKeyboardTypeKey];
        
        [secInfo addCell:cellInfo];
    }
    
    cellInfo = [IBTTableViewCellInfo editorCellForSel:nil
                                              target:nil
                                               title:@"零售价:"
                                              margin:0
                                                 tip:@"请输入"
                                         autoCorrect:NO
                                               focus:NO
                                                text:nil];
    
    [cellInfo addUserInfoValue:@( NSTextAlignmentRight )
                        forKey:CInfoEditorAlignKey];
    
    [cellInfo addUserInfoValue:@( UIKeyboardTypeDecimalPad )
                        forKey:CInfoEditorKeyboardTypeKey];
    
    UITextField *textF = [cellInfo getUserInfoValueForKey:CInfoEditorKey];
    textF.delegate = self;
    
    [secInfo addCell:cellInfo];
    [_m_tableViewInfo addSection:secInfo];
    
    [[_m_tableViewInfo getTableView] reloadData];
    
}

- (void)dealloc {
    [self removeKeyboardNotification];
}

#pragma mark - Actions
- (void)onBottomBtnAction:(__unused id)sender {
    
    IBTTableViewSectionInfo *secInfo = [_m_tableViewInfo getSectionAt:0];
    NSUInteger uiCellCount = [secInfo getCellCount];
    if (uiCellCount == 0) {
        return;
    }
    
    IBTTableViewCellInfo *cellInfo;
    
    BOOL bIsAllInputed = YES;
    NSMutableArray *mArrRecords = [NSMutableArray array];
    for (NSUInteger i = 0; i < uiCellCount; i ++) {
        cellInfo = [secInfo getCellAt:i];
        NSString *str = [cellInfo getUserInfoValueForKey:CInfoEditorTextKey];
        if (str.length == 0) {
            bIsAllInputed = NO;
            break;
        }
        [mArrRecords addObject:str];
    }
    
    if (bIsAllInputed) {
        if ([_m_delegate respondsToSelector:@selector(inputPopup:didAddRecords:)]) {
            [_m_delegate inputPopup:self didAddRecords:mArrRecords];
        }
        
        [self dismissPopup];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if ([string isEqualToString:@""]) {
        return YES;
    }
    else if ([string isEqualToString:@"."]) {
        // 判断 textField.text 是否为 纯数字
        if ([textField.text rangeOfString:@"."].location != NSNotFound) {
            return NO;
        }
        else {
            return YES;
        }
    }
    else if (textField.text.length == 1 &&
             [textField.text isEqualToString:@"0"])
    {
        BOOL bIsNum = [[self class] checkIsNumberWithStr:string];
        if (bIsNum) {
            if (![string isEqualToString:@"0"]) {
                textField.text = string;
            }
        }
        
        return NO;
    }
    
    return [[self class] checkIsNumberWithStr:string];
}

+ (BOOL)checkIsNumberWithStr:(NSString *)string {
    NSString *regexStr = @"^[0-9]\\d*$";
    
    NSError *error = nil;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
    if (string != nil && regex != nil) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
        if (firstMatch) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - Keyboard Notification

- (void)addKeyboardNotification {
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self
                   selector:@selector(keyboardWillShow:)
                       name:UIKeyboardWillShowNotification
                     object:nil];
    [notiCenter addObserver:self
                   selector:@selector(keyboardWillHide:)
                       name:UIKeyboardWillHideNotification
                     object:nil];
}

- (void)removeKeyboardNotification {
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter removeObserver:self
                          name:UIKeyboardWillShowNotification
                        object:nil];
    [notiCenter removeObserver:self
                          name:UIKeyboardWillHideNotification
                        object:nil];
}


#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self convertRect:keyboardBounds toView:nil];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    
    self.y = self.superview.height - CGRectGetHeight(keyboardBounds) - self.height;
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    self.y = (self.superview.height - self.height) * .5f;
    
    // commit animations
    [UIView commitAnimations];
}


@end