//
//  LoginViewController.m
//  redstar
//
//  Created by admin on 15/10/22.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginView.h"
#import "CustomDropMenuView.h"

#import "RootTabBarController.h"

#import <AFNetworking.h>
#import "CommonFunc.h"
#import "HttpClient.h"
#import "APService.h"
#import <MBProgressHUD.h>

#define kUsernameTableViewCell @"usernameTableViewCell"

@interface LoginViewController () <CustomDropMenuDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate, UIAlertViewDelegate> {
    BOOL isOpened; // 判断存取本地的tableView是否打开
}
@property (nonatomic, strong) LoginView *loginView;
@property (nonatomic, strong) NSMutableDictionary *allUserDict;

@property (nonatomic, strong) UITableView *dropTableView;
@property (nonatomic, strong) CustomDropMenuView *menu;

@property (nonatomic, strong) RootTabBarController *rootTBC;
@property (nonatomic, strong) NSString *jumpURL;
@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"loginView"];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"loginView"];
}
#pragma mark - ViewDidLoad
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self getVersion];
    
    isOpened = NO;
    
    [self addAllClick];
   
    
    self.loginView.usernameTextFiled.delegate = self;
    self.loginView.passwordTextFiled.delegate = self;
    // 初始化数组
    
    [self requestLogin];
}

- (void)loadView
{
    self.view = self.loginView;
}

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

#pragma mark - Private Methods
// 获取版本
- (void)getVersion
{
    HttpClient *httpCilent = [[HttpClient alloc] initWithUrl:[NSString stringWithFormat:@"%@%@", kRedStarURL, kCheckUpdateURL]];
    [httpCilent checkAndUpdateCurrentVersionWithCompletion:^(id response, NSError *error) {
        
        if (response[@"data"] == nil || response[@"data"] == NULL || [response[@"data"] isEqual:[NSNull null]] || response[@"data"] == Nil) {
            return;
        } else {
            NSDictionary *dict = response[@"data"];
            NSString *newVersion = [NSString stringWithFormat:@"%@", dict[@"version"]];
            self.jumpURL = [NSString stringWithFormat:@"%@", dict[@"url"]];
            BOOL isForce = [dict[@"forceUpdate"] boolValue];
            [self checkAppUpdate:newVersion forceUpdate:isForce];
        }
    }];
}

- (void)checkAppUpdate:(NSString *)newVersion forceUpdate:(BOOL)forceUpdate
{
    // 获取当前版本
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [NSString stringWithFormat:@"%@",infoDic[@"CFBundleShortVersionString"]];
    
    if (![currentVersion isEqualToString:newVersion]) {
        
        if (forceUpdate) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示！" message:[NSString stringWithFormat:@"发现新版本：%@，如果不更新，可能造成本应用无法使用！", newVersion] delegate:self cancelButtonTitle:nil otherButtonTitles:@"前往更新", nil];
            alert.delegate = self;
            alert.tag = 322234;
            [alert show];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示！" message:[NSString stringWithFormat:@"发现新版本：%@", newVersion] delegate:self cancelButtonTitle:@"稍后再说" otherButtonTitles:@"前往更新", nil];
            alert.delegate = self;
            [alert show];
            alert.tag = 3058284;
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3058284) {
        if (buttonIndex == 1) {
            NSString *url = self.jumpURL;
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
    } else if (alertView.tag == 322234){
        if (buttonIndex == 0) {
            NSString *url = self.jumpURL;
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }
    }
}



- (void)requestLogin
{
   
    // 获取上次登陆信息
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"loginMessage"] isEqualToString:@"ok"]) {
        NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
        NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        
        self.loginView.usernameTextFiled.text = username;
        self.loginView.passwordTextFiled.text = password;
        
        if (self.loginView.usernameTextFiled.text.length == 0 || self.loginView.passwordTextFiled.text.length == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"账号、密码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        } else {
            
            HttpClient *httpClient = [[HttpClient alloc] initWithLogin];
            UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
            [MBProgressHUD showHUDAddedTo:window animated:YES];
            [httpClient loginWithUsername:username password:password completion:^(id response, NSError *error) {
                if ([response[@"message"] isEqualToString:@"ok"]) {
                    // 保存登陆信息
                    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                    [userDefault setObject:username forKey:@"username"];
                    [userDefault setObject:password forKey:@"password"];
                    [userDefault setObject:response[@"message"] forKey:@"loginMessage"];
                    
                    NSDictionary *dict = response[@"data"];
                    NSString *user_code = dict[@"user_code"];
                    NSString *user_name = dict[@"user_name"];
                    NSString *user_uuid = dict[@"user_uuid"];
                    NSString *enterprise_name = dict[@"enterprise_name"];
                    NSString *enterprise_uuid = dict[@"enterprise_uuid"];
                    NSString *org_name = dict[@"org_name"];
                    NSString *authenticode = dict[@"authenticode"];
                    NSArray *permissions = dict[@"permissions"];
                    
                    [userDefault setObject:enterprise_uuid forKey:@"enterprise_uuid"];
                    [userDefault setObject:user_code forKey:@"user_code"];
                    [userDefault setObject:user_name forKey:@"user_name"];
                    [userDefault setObject:user_uuid forKey:@"user_uuid"];
                    [userDefault setObject:enterprise_name forKey:@"enterprise_name"];
                    [userDefault setObject:org_name forKey:@"org_name"];
                    [userDefault setObject:authenticode forKey:@"authenticode"];
                    [userDefault setObject:permissions forKey:@"permissions"];

                    self.rootTBC = [[RootTabBarController alloc] init];
                    [MBProgressHUD hideHUDForView:window animated:YES];
                    [self presentViewController:_rootTBC animated:YES completion:nil];
                } else {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", response[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [MBProgressHUD hideHUDForView:window animated:YES];
                    [alertView show];
                }
            }];

        }
    }
}

- (void)addAllClick
{
    [self.loginView.loginButton addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

/**
 *  登录按钮
 */
- (void)loginButtonClick:(UIButton *)sender
{
    
    if (self.loginView.usernameTextFiled.text.length == 0 || self.loginView.passwordTextFiled.text.length == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"账号、密码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    HttpClient *httpClient = [[HttpClient alloc] initWithLogin];
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [MBProgressHUD showHUDAddedTo:window animated:YES];
    [httpClient loginWithUsername:self.loginView.usernameTextFiled.text password:self.loginView.passwordTextFiled.text completion:^(id response, NSError *error) {
        if ([response[@"message"] isEqualToString:@"ok"]) {
           
            // 保存登陆信息
            [[NSUserDefaults standardUserDefaults] setObject:self.loginView.usernameTextFiled.text forKey:@"username"];
            [[NSUserDefaults standardUserDefaults] setObject:self.loginView.passwordTextFiled.text forKey:@"password"];
            [[NSUserDefaults standardUserDefaults] setObject:response[@"message"] forKey:@"loginMessage"];
            NSDictionary *dict = response[@"data"];
            NSString *user_code = dict[@"user_code"];
            NSString *user_name = dict[@"user_name"];
            NSString *user_uuid = dict[@"user_uuid"];
            NSArray *permissions = dict[@"permissions"];
            NSString *enterprise_name = dict[@"enterprise_name"];
            NSString *enterprise_uuid = dict[@"enterprise_uuid"];
            NSString *authenticode = dict[@"authenticode"];
            NSString *org_name = dict[@"org_name"];
            
            [[NSUserDefaults standardUserDefaults] setObject:enterprise_uuid forKey:@"enterprise_uuid"];
            [[NSUserDefaults standardUserDefaults] setObject:enterprise_name forKey:@"enterprise_name"];
            [[NSUserDefaults standardUserDefaults] setObject:org_name forKey:@"org_name"];
            [[NSUserDefaults standardUserDefaults] setObject:permissions forKey:@"permissions"];
            [[NSUserDefaults standardUserDefaults] setObject:user_code forKey:@"user_code"];
            [[NSUserDefaults standardUserDefaults] setObject:user_name forKey:@"user_name"];
            [[NSUserDefaults standardUserDefaults] setObject:user_uuid forKey:@"user_uuid"];
            [[NSUserDefaults standardUserDefaults] setObject:permissions forKey:@"permissions"];
            [[NSUserDefaults standardUserDefaults] setObject:authenticode forKey:@"authenticode"];
            
//            //极光别名
            NSSet *setTags = [NSSet setWithArray:@[@""]];
            [APService setTags:setTags alias:user_uuid callbackSelector:nil object:nil];
//            [APService setTags:setTags
//                         alias:user_uuid
//              callbackSelector:nil object:nil];
            

            // 进入RootTabBar
            self.rootTBC = [[RootTabBarController alloc] init];
            [MBProgressHUD hideHUDForView:window animated:YES];
            [self presentViewController:_rootTBC animated:YES completion:nil];
            
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", response[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [MBProgressHUD hideHUDForView:window animated:YES];
            [alertView show];
        }
    }];
}


#pragma mark - TableView Delegate/DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allUserDict.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kUsernameTableViewCell];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kUsernameTableViewCell];
    }
    cell.textLabel.text = _allUserDict.allKeys[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:self.dropTableView cellForRowAtIndexPath:indexPath];
    self.loginView.usernameTextFiled.text = cell.textLabel.text;
    NSString *key = _allUserDict.allKeys[indexPath.row];
    self.loginView.passwordTextFiled.text = _allUserDict[key];
    [_menu dismiss];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}


#pragma mark - UItextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([self.loginView.usernameTextFiled isFirstResponder]) {
        // 创建下拉菜单
        self.menu = [CustomDropMenuView defaultMenuView];
        _menu.showTop = 300;
        _menu.showLeft = 20;
        _menu.showRight = -20;
        _menu.showHeight = 40 * _allUserDict.count;
        
        _menu.delegate = self;
        _menu.content = self.dropTableView;
        
        // 显示
        [_menu showFrom:self.loginView.usernameView];
    }
}

#pragma mark - layz loading
- (LoginView *)loginView
{
    if (!_loginView) {
        _loginView = [[LoginView alloc] init];
    }
    return _loginView;
}

- (UITableView *)dropTableView
{
    if (!_dropTableView) {
        _dropTableView = [[UITableView alloc] init];
    }
    [_dropTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kUsernameTableViewCell];
    _dropTableView.translatesAutoresizingMaskIntoConstraints = NO;
    _dropTableView.delegate = self;
    _dropTableView.dataSource = self;
    return _dropTableView;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}



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

@end
