//
//  GLoginController.m
//  aiim
//
//  Created by gan on 2025/2/27.
//
#import "GLoginController.h"
#import "UserNetApi.h"
#import "AppDelegate.h"
#import "UDManager.h"
#import "config.h"
#import "GSignController.h"
#import <AdSupport/AdSupport.h>
#import "FilePreviewer.h"
#import "GCoverController.h"

@interface GLoginController ()

@property (weak, nonatomic) IBOutlet UITextField *userId;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UIButton *loginBt;
@property (weak, nonatomic) IBOutlet UIButton *wangjiBt;
@property (weak, nonatomic) IBOutlet UIButton *signBt;
@property (weak, nonatomic) IBOutlet UILabel *meiyouzhlb;
@property (weak, nonatomic) IBOutlet UIButton *agreedBt;

@property (nonatomic)  BOOL isagreed;

@property (nonatomic)  NSInteger reLoginC;


@end

@implementation GLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    // Do any additional setup after loading the view.
    NSLog(@"GLoginController viewDidLoad");
    // 创建一个点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    // 将手势添加到主视图上
    [self.view addGestureRecognizer:tap];
    _isagreed=false;
    NSString *agreed = [UDManager.shareInstance getSDManager:dkagreed];
    if(agreed){
        if([agreed isEqualToString:@"1"]){
            _isagreed = true;
        }
    }
    [self initsubView];
    _reLoginC = 0;
    [self getUserinfo];
}


-(void)initsubView{
    _userId.borderStyle=UITextBorderStyleNone;
    _userId.layer.borderWidth = 1.0f;
    _userId.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _userId.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _userId.backgroundColor = [UIColor clearColor];
    _userId.textColor=[UIColor whiteColor];
    NSString *note = NSLocalizedString(@"login-usernme-note", @"");
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _userId.leftView = paddingView;
    _userId.leftViewMode = UITextFieldViewModeAlways;
    _userId.attributedPlaceholder = placeholder;
    
    _password.borderStyle=UITextBorderStyleNone;
    _password.layer.borderWidth = 1.0f;
    _password.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _password.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _password.backgroundColor = [UIColor clearColor];
    _password.textColor=[UIColor whiteColor];
    note = NSLocalizedString(@"login-passw-note", @"");
    NSMutableAttributedString *placeholder2 = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _password.leftView = paddingView2;
    _password.leftViewMode = UITextFieldViewModeAlways;
    _password.attributedPlaceholder = placeholder2;
    
    [_loginBt setTitle:NSLocalizedString(@"login-denglu", @"登录") forState:UIControlStateNormal];
    _loginBt.titleLabel.font = [UIFont systemFontOfSize: 19.0];
    [_loginBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_loginBt setBackgroundColor:globalColor(GCTypeGreen)];
    _loginBt.layer.cornerRadius = 27;
    _loginBt.layer.masksToBounds = YES; // 防止子视图超出圆角边界
    
    NSString *vendorIdentifier = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSLog(@"vendorIdentifier:%@",vendorIdentifier);
    
    _wangjiBt.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [_wangjiBt setTitleColor:globalColor(GCTypeGreen) forState:UIControlStateNormal];
    [_wangjiBt setTitle:NSLocalizedString(@"login-wangjimm", @"忘记密码?") forState:UIControlStateNormal];
    _signBt.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [_signBt setTitleColor:globalColor(GCTypeGreen) forState:UIControlStateNormal];
    [_signBt setTitle:NSLocalizedString(@"login-quzhuce", @"去注册") forState:UIControlStateNormal];
    _meiyouzhlb.text =NSLocalizedString(@"login-meiyouzh", @"没有账号？");
    
    if(_isagreed){
        [_agreedBt setImage:kImageMake(@"checkbox_selected") forState:UIControlStateNormal];
    }
    else{
        [_agreedBt setImage:kImageMake(@"checkbox_unselected") forState:UIControlStateNormal];
    }
    
}

-(void)dismissKeyboard{
    NSLog(@"dismissKeyboard");
    [self.view endEditing:YES];
}
- (IBAction)login:(id)sender {
    
    if(!_isagreed){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认"
                                                                      message:@"同意接受隱私政策"
                                                               preferredStyle:UIAlertControllerStyleAlert];
         
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"查看政策"
                                                               style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
            // 点击后的操作
            [[FilePreviewer shared] previewFileWithLocalPath:@"" remoteURL:getURL(privacyPolicy) fromViewController:self];
        }];
         
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"同意"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
            [UDManager.shareInstance setSDManager:@"1" key:dkagreed];
            self->_isagreed=YES;
            [self->_agreedBt setImage:kImageMake(@"checkbox_selected") forState:UIControlStateNormal];
            [self loginAct];
            // 点击确定后的操作
        }];
         
        [alert addAction:cancelAction];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }
    [MBProgressHUD showLoadingWithText:@"" inView:self.view];
    [self loginAct];
    
}

-(void)loginAct{

    [self.view endEditing:YES];
    NSString *userid = self.userId.text;
    NSString *password = self.password.text;
    NSDictionary *ps = @{@"username": userid,
                         @"password": password,
                         @"code": @"",
                         @"version":@"111",
                         @"uuid": @""};
    
    
    
    [UserNetApi login:ps succ:^(int code, NSDictionary * res) {
        NSLog(@"%@",res);
        self->_reLoginC=4;
        [MBProgressHUD hideAllTipsInView:self.view];
        NSString *codes = res[@"code"];
        if(codes.intValue!=200){
            [MBProgressHUD showWithText:res[@"msg"]];
            return;
        }
        NSLog(@"%@",res[@"token"]);
        NSString *token =res[@"token"];
        
        if(token){
            [UDManager.shareInstance setSDManager:res[@"token"] key:gkeytoken];
            [UDManager.shareInstance setSDManager:userid key:dkuserloginId];
            [self getUserinfo];
        }
        else{
            [MBProgressHUD showWithText:@"数据异常"];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"--%@",error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(self->_reLoginC<3){
                self->_reLoginC=self->_reLoginC+1;
                [self loginAct];
            }
            else{
                [MBProgressHUD hideAllTipsInView:self.view];
            }
        });
    }];
}




- (IBAction)wangjimm:(id)sender {
    GCoverController * resetPwdVc = [[GCoverController alloc] init];
    resetPwdVc.isLogin = YES;
    resetPwdVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:resetPwdVc animated:YES completion:nil];
}
- (IBAction)sign:(id)sender {
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    GSignController *chatctr = [board instantiateViewControllerWithIdentifier:@"GSignController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController :uiNavC animated:YES completion:nil];
}


#pragma mark private

-(void)getUserinfo{
    NSString *token = [UDManager.shareInstance getSDManager:gkeytoken];
    if([token isKindOfClass:[NSString class]]&&token.length>10){
        [UserNetApi getUserinfo:^(int code, NSDictionary * res) {
            NSLog(@"%d", code);
            NSNumber *gcode=res[@"code"];
            NSDictionary *data=res[@"data"];
            NSLog(@"%@", res);
            if([gcode intValue]!=200){
                NSLog(@"%@",res[@"msg"]);
                [MBProgressHUD showWithText:@"登录异常，请重新登录"];
                return;
            }
            NSDictionary *ps = @{@"avatar": data[@"avatar"]?:@"",
                                 @"deptId": data[@"deptId"]?:@"",
                                 //@"domainId":data[@"domainId"],
                                 @"email":data[@"email"]?:@"",
                                 @"id":data[@"id"]?:@"",
                                 @"mobile":data[@"mobile"]?:@"",
                                 @"name":data[@"name"]?:@"",
                                 //@"platformType":data[@"platformType"]?:@"",
                                 //@"registrationId":data[@"registrationId"]?:@"",
                                 @"sex":data[@"sex"]?:@"",
                                 //@"tgbotAdmin":data[@"tgbotAdmin"],
                                 //@"tgbotName":data[@"tgbotName"],
                                 //@"tgbotTk":data[@"tgbotTk"]?:@"",
                                 @"username":data[@"username"]?:@"",
                                 //@"uuid":data[@"uuid"],
                                 //@"voipTk":data[@"voipTk"]?:@""
                                };
            if([gcode intValue]==200){
                NSLog(@"ps:%@",ps);
                [MBProgressHUD showWithText:@"登录成功"];
                [MBProgressHUD hideAllTipsInView:self.view];
                [UDManager.shareInstance setSDManager:ps[@"id"] key:dkuserId];
                [UDManager.shareInstance setDDManager:ps key:dkuserinfo];
                [[NSNotificationCenter defaultCenter] postNotificationName: nkonLoginSucc object:nil];
            }
            
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"%@", error);
            // 使用GCD创建一个在3秒后执行的定时器
            [MBProgressHUD hideAllTipsInView:self.view];
        }];
    }
}

- (IBAction)agreedAct:(id)sender {
    _isagreed=!_isagreed;
    if(_isagreed){
        [_agreedBt setImage:kImageMake(@"checkbox_selected") forState:UIControlStateNormal];
        [UDManager.shareInstance setSDManager:@"1" key:dkagreed];
    }
    else{
        [_agreedBt setImage:kImageMake(@"checkbox_unselected") forState:UIControlStateNormal];
        [UDManager.shareInstance setSDManager:@"0" key:dkagreed];
    }
}

- (IBAction)yinsizhengc:(id)sender {
    [[FilePreviewer shared] previewFileWithLocalPath:@"" remoteURL:getURL(privacyPolicy) fromViewController:self];
}


@end
