//
//  ICRLoginViewController.m
//  XFFruit
//
//  Created by Xummer on 3/22/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRLoginContentView.h"
#import "ICRLoginViewController.h"

#import "APService.h"
#import "GXFFunctionDB.h"
#import "GXFFunctionDBHelper.h"
#import "ICRAppDelegate.h"

#define LOGIN_CONTAINER_LEFT_MARGIN (20)
#define LOGIN_CONTAINER_HEIGHT (450)

@interface ICRLoginViewController () {
    CGFloat m_fDefaultContainerY;
}
@property (strong, nonatomic) ICRLoginContentView *m_containerView;
@end

@implementation ICRLoginViewController

#pragma mark - Life Cycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupSubviews];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    if (m_fDefaultContainerY == 0) {
        m_fDefaultContainerY = _m_containerView.y;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self selector:@selector(inputTextEditChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter removeObserver:self];
}

#pragma mark - Private Method
- (void)setupSubviews
{
    UIImageView *bg = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bg.image = [UIImage imageWithColor:GXF_SAVE_COLOR];//
    [bg autoresizingWithStrechFullSize];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onBGTapped:)];
    bg.userInteractionEnabled = YES;
    [bg addGestureRecognizer:tapGesture];

    [self.view addSubview:bg];

    self.m_containerView = [[ICRLoginContentView alloc] initWithFrame:(CGRect) {
        .origin.x = LOGIN_CONTAINER_LEFT_MARGIN, .origin.y = (self.view.height - LOGIN_CONTAINER_HEIGHT) * .5f, .size.width = self.view.width - 2 * LOGIN_CONTAINER_LEFT_MARGIN, .size.height = LOGIN_CONTAINER_HEIGHT
    }
                                                            showCCode:YES];
    [_m_containerView autoresizingWithVerticalCenter];

    [_m_containerView.m_loginBtn addTarget:self action:@selector(onLoginTapped:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_m_containerView];

    ICRUserUtil *userU = [ICRUserUtil sharedInstance];

    self.m_containerView.m_cCodeTextF.text = userU.registerCode;//*registerCode;  //企业认证码
    self.m_containerView.m_userNameTextF.text = userU.userName;
    if (userU.isLogout) {
        // self.m_containerView.m_passwordTextF.text = userU.password;
    } else {
        self.m_containerView.m_passwordTextF.text = userU.password;
    }
    
#ifdef DEBUG
    self.m_containerView.m_cCodeTextF.text = @"923";
    self.m_containerView.m_userNameTextF.text = @"admin";
    self.m_containerView.m_passwordTextF.text = @"thoradmin";
#else
    
#endif

    [self.m_containerView checkLoginEnable];

#ifdef Demonstrate
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenSize.height - 34, ScreenSize.width, 20)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"上海海鼎信息工程股份有限公司  V%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [self.view addSubview:label];
#else
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenSize.height - 34, ScreenSize.width, 20)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"V%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    [self.view addSubview:label];
#endif
}

#pragma mark - Logic

#pragma mark - Actions
- (void)onBGTapped:(__unused id)sender
{
    [self.view endEditing:YES];
}

- (void)onLoginTapped:(__unused id)sender
{

#if 0
    ICRAppViewControllerManager *mgr =
    [ICRAppViewControllerManager getAppViewControllerManager];
    [mgr openMainFrame];
#else

    NSString *nsRegisterCode = self.m_containerView.m_cCodeTextF.text;
    NSString *nsUserName = self.m_containerView.m_userNameTextF.text;
    NSString *nsPassword = self.m_containerView.m_passwordTextF.text;

    void (^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];

        ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
        userUtil.bAutoLogin = @([_m_containerView isAutoLogin]);

        [userUtil saveArchive];

        ICRAppViewControllerManager *mgr = [ICRAppViewControllerManager getAppViewControllerManager];
        [mgr openMainFrame];

#pragma 可以开新线程 ，待优化
        //当登陆成功时就建立功能数据表
        //        [[GXFFunctionDB sharedInstance] deleteTables];
        [[GXFFunctionDB sharedInstance] createTables];

        //完成对初始化数据书库的操作
        if (![[GXFFunctionDBHelper sharedInstance] successInsertOriginFunctions]) {
            [[GXFFunctionDBHelper sharedInstance] insertAllOriginFunctions];
        }
        if (![[GXFFunctionDBHelper sharedInstance] sucessInsertOriginDisplayFunctions]) {
            [[GXFFunctionDBHelper sharedInstance] insertAllOriginDisplayFunctions];
        }

        //更改功能权限
        for (int count = 0; count < userUtil.permissions.count; count++) {
            GXFFunction *function = [[GXFFunctionDB sharedInstance] functionSelectWithId:[userUtil.permissions[count] integerValue]];
            if (function.Id) {
                function.hasPermission = 1;
                [[GXFFunctionDB sharedInstance] updateFunctionHasPermissionWithId:function];
            }
        }

        //配置功能 不是默认配置
        NSUserDefaults *f_default = [NSUserDefaults standardUserDefaults];
        BOOL noDefault = [[f_default objectForKey:@"noDefault"] integerValue] > 0 ? YES : NO;
        if (!noDefault) {
            [[GXFFunctionDB sharedInstance] defaultdisplayFunctions];
        }

        //极光别名
        NSSet *setTags = [NSSet setWithArray:@[ @"" ]];
        [APService setTags:setTags alias:userUtil.userId callbackSelector:nil object:nil];

    };

    void (^fail)(id) = ^(id data) {
        CLog(@"error =%@", data);
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];//@"输入的信息不正确，请重新输入"
                                       //        [IBTLoadingView showTextOnly: data inView:self.view];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLoginWithUserName:nsUserName password:nsPassword registerCode:nsRegisterCode success:succ failure:fail];
#endif
}

#pragma mark - TextObserver
- (void)inputTextEditChanged:(NSNotification *)obj
{
    [self.m_containerView checkLoginEnable];
}

#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.view 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.m_containerView.y = -50.0f;

    // 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.m_containerView.y = m_fDefaultContainerY;

    // commit animations
    [UIView commitAnimations];
}

@end
