//
//  KKCLFundViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/8/9.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "KKCLFundViewController.h"
#import "WKWebViewJavascriptBridge.h"
#import "PasswordAlertView.h"
#import "KKUserAuthViewController.h"

@interface KKCLFundViewController ()

@property WKWebViewJavascriptBridge* bridge;

@property (nonatomic, strong)WKWebView* webView;

@property (nonatomic, strong)UILabel *lb_content;

@property (nonatomic,assign)BOOL isPause;

@property (nonatomic, assign)BOOL isDestoryTimer;

@property (strong, nonatomic)  dispatch_source_t timer;

@property (nonatomic, strong)UIButton *taskBtn;

@end

@implementation KKCLFundViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (@available(iOS 11.0, *)) {
       self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
       self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    BOOL hidden =  [self.from isEqualToString:@"home"];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    if (_bridge) { return; }
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.allowsInlineMediaPlayback = YES;// 自动播放, 不需要用户采取任何手势开启播放
    if (@available(iOS 10.0, *)) {
        // WKAudiovisualMediaTypeNone 音视频的播放不需要用户手势触发, 即为自动播放
        config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
    } else {
        config.requiresUserActionForMediaPlayback = NO;
    }
    
    WKWebView* webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, hidden ?  ScreenHeight : ScreenHeight - cl_kTabBarHeight) configuration:config];
//    [[NSClassFromString(@"WKWebView") alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, hidden ?  ScreenHeight : ScreenHeight - cl_kTabBarHeight)];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    self.webView = webView;
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];
    
//    [_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
//        NSLog(@"testObjcCallback called: %@", data);
//        responseCallback(@"Response from testObjcCallback");
//    }];
    
    [_bridge registerHandler:@"getAppInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        
        NSDictionary *dic = @{
            @"appid":[NSString stringWithFormat:@"%@",@([getPeopleID PeopleID])],
            @"phone":[getPeopleID PeopleIphoneNmber]
        };
        NSString *jsonStr = [dic mj_JSONString];
        responseCallback(jsonStr);
    }];
    
    [_bridge registerHandler:@"closeWebView" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        BOOL hidden =  [self.from isEqualToString:@"home"];
        if (hidden) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self.tabBarController.navigationController popViewControllerAnimated:YES];
        }
        
       
    }];
    
    [_bridge registerHandler:@"showPwdDialog" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
       
        [PasswordAlertView showWithBlock:^(BOOL forget, NSString * _Nonnull password) {
            if (forget) {
                NSDictionary *dic = @{
                    @"forgetPassword": @(2),
                    @"password":@"123456"
                };
                NSString *jsonStr = [dic mj_JSONString];
                responseCallback(jsonStr);
            }else{
                NSDictionary *dic = @{
                    @"forgetPassword": @(1),
                    @"password":password
                };
                NSString *jsonStr = [dic mj_JSONString];
                responseCallback(jsonStr);
            }
        }];
       
    }];
    
    WeakSelf
    
    [_bridge registerHandler:@"realNameAuthentication" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        KKUserAuthViewController* vc = [KKUserAuthViewController new];
        vc.title = @"实名认证";
        vc.type = KKUserAuthFromVCTypeChangLiang;
        vc.block = ^(BOOL success) {
          
            [weakSelf.webView reload];
        };
        [weakSelf.tabBarController.navigationController pushViewController:vc animated:YES];
        
       
    }];
    

//    [_bridge callHandler:@"testJavascriptHandler" data:@{ @"foo":@"before ready" }];
  
    
    //[self renderButtons:webView];
    //[self loadExamplePage:webView];
    
    [self getChangLiangUrlRequest];
    [self creatStatusView];
    
    if (self.showTaskView) {
        [self addTaskView];
    }
    //[self showBtns];
}
#pragma mark - 显示悬浮按钮

- (void)showBtns
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-100, ScreenHeight- cl_kTabBarHeight - 120, 69, 63)];
    [button addTarget:self action:@selector(clickAddButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"CL悬浮"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [self.view bringSubviewToFront:button];
}
- (void)clickAddButton:(UIButton *)button{
    WebVC * vc = [WebVC new];
    vc.title= @"进群免费领";
    vc.url = @"https://nginx.weface.com.cn/appH5/piggyBankcl/index.html";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)creatStatusView
{
    UIView *statusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kStatusBarHeight)];
    statusView.backgroundColor = K_MainColor;
    [self.view addSubview:statusView];
}


#pragma mark - 通知绑定方法

///监听应用退到后台
 - (void)didEnterBackground
{
    if (!self.showTaskView) {
        return;
    }
   
    [self pauseTimer];
}
///恢复旋转
- (void)didBecomeActive
{
    if (!self.showTaskView) {
        return;
    }
    
    [self resumeTimer];
}


#pragma mark - 定时器处理
-(void) pauseTimer{
    
    
    
    if (self.isPause) {
        return;
    }
    
    self.isPause = YES;
    
    if(self.timer){
        dispatch_suspend(_timer);
    }
}
-(void) resumeTimer{
    
    
    
    if (self.isPause == NO) {
        return;
    }
    
    self.isPause = NO;
    
    if(self.timer){
        dispatch_resume(_timer);
    }
}
-(void) stopTimer{
    if(self.timer){
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}


#pragma mark - 找工作
//进度视图
- (void)addTaskView
{
    UIView *taskView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 77 * WIDTHRADIU, ScreenHeight - cl_kTabBarHeight - 75 * WIDTHRADIU, 57 * WIDTHRADIU, 55 * WIDTHRADIU)];
    [self.view addSubview:taskView];
    
    UIImageView *taskImage = [[UIImageView alloc]init];
    taskImage.frame = taskView.bounds;
    taskImage.image = [UIImage imageNamed:@"littleGoldHouseWindow"];
    [taskView addSubview:taskImage];
    
    
    UILabel *lb_content = [[UILabel alloc]init];
    lb_content.numberOfLines = 0;
    lb_content.textColor = [UIColor whiteColor];
    lb_content.textAlignment = NSTextAlignmentCenter;
    lb_content.font = [UIFont systemFontOfSize:8 * WIDTHRADIU];
    
    lb_content.text = @"浏览5秒\n领取红包";
    [taskView addSubview:lb_content];
    
    [lb_content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(taskView);
        make.left.offset(2 * WIDTHRADIU);
        make.height.offset(22 * WIDTHRADIU);
    }];
    
    self.lb_content = lb_content;
    
    
    UIButton *taskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    taskBtn.frame = taskView.bounds;
    [taskBtn addTarget:self action:@selector(taskBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    taskBtn.userInteractionEnabled = NO;
    [taskView addSubview:taskBtn];
    
    self.taskBtn = taskBtn;
   
    [self startCount];
}

//定时器活动
- (void)startCount
{
    
    if (self.timer == nil) {
        
        __block NSInteger time = 5; //倒计时时间
        
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        

        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1*NSEC_PER_SEC, 0); //每秒执行
        

        WeakSelf
        dispatch_source_set_event_handler(timer, ^{

            if(time <= 0){ //倒计时结束，关闭

                if (weakSelf.isDestoryTimer == NO) {
                    dispatch_source_cancel(timer);
                    weakSelf.isDestoryTimer = YES;
                }
                

                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.lb_content.text = @"任务完成\n返回领奖励";
                    weakSelf.taskBtn.userInteractionEnabled = YES;
                    if (weakSelf.block) {
                        
                        weakSelf.block(YES);
                    }
                });

            }else{

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    weakSelf.lb_content.text = [NSString stringWithFormat:@"浏览%ld秒\n领取红包",time];
                   

                });
                NSLog(@"%ld",time);

                time--;
            }
        });

        dispatch_resume(timer);
        
        self.timer = timer;
        
    }
    
   
    
}
#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidStartLoad");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
}

- (void)renderButtons:(WKWebView*)webView {
    UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
    
    UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [callbackButton setTitle:@"Call handler" forState:UIControlStateNormal];
    [callbackButton addTarget:self action:@selector(callHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:callbackButton aboveSubview:webView];
    callbackButton.frame = CGRectMake(10, 400, 100, 35);
    callbackButton.titleLabel.font = font;
    
    UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [reloadButton setTitle:@"Reload webview" forState:UIControlStateNormal];
    [reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:reloadButton aboveSubview:webView];
    reloadButton.frame = CGRectMake(110, 400, 100, 35);
    reloadButton.titleLabel.font = font;
}

- (void)callHandler:(id)sender {
    id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
    [_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];
}

- (void)loadExamplePage:(WKWebView*)webView {
//    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"ExampleApp" ofType:@"html"];
//    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
//    [webView loadHTMLString:appHtml baseURL:baseURL];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];

    [webView loadRequest:request];

}


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



#pragma mark - 长量基金
- (void)getChangLiangUrlRequest
{
    
    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
//    NSString *url = [NSString stringWithFormat:@"%@dynamic/menu/get",@"http://172.16.10.18:8017/"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *params = @{
        @"configName":@"ChangLiangJiJin",
        @"appName":@"kksh",
        @"version":[app_Version stringByReplacingOccurrencesOfString:@"." withString:@""],
        @"systemType":@"iOS"
    };
    [KKLoadingAnimationView show];
    
    [NetworkRequest Post15:url Params:params Success:^(id _Nonnull objc) {
        
        [KKLoadingAnimationView dismiss];
        
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSArray *array = objc[@"result"];
                if ([array isKindOfClass:[NSArray class]] && array.count > 0) {
                    NSDictionary *dic = (NSDictionary *)array[0];
                    if ([dic isKindOfClass:[NSDictionary class]]) {
                        self.url = dic[@"content"];
                        [self loadExamplePage:self.webView];
                    }
                }
            } 
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
        [KKLoadingAnimationView dismiss];
        
    }];
    
}

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