//
//  KKInsuranceViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/4/25.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "KKInsuranceViewController.h"

@interface KKInsuranceViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
{
    BOOL loadOK;
}


@end

@implementation KKInsuranceViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:whiteView];
    [whiteView addSubview:self.webView];
    
    
    
    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
       }
    

    //[self navConfig];
    
    
    
}

- (void)navConfig
{
    
    
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 50, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    //    [button_2 setBackgroundColor:[UIColor redColor]];
    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    
    
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (!loadOK) {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
        
        [_webView loadRequest:request];
    }
}



#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:页面开始加载");
}
//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:内容开始返回");
    
   
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    NSLog(@"WebVC:页面加载完成");
    
    loadOK = YES;
 
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"WebVC:页面加载失败");
}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:接收到服务器跳转请求");
}

// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSLog(@"WebVC:收到服务器响应,是否跳转");
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

static const NSString * CompanyFirstDomainByWeChatRegister = @"k.yaodouwang.com";
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"WebVC:发送请求之前,决定是否跳转");
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
//    NSString* reqUrl = navigationAction.request.URL.absoluteString;
    NSString * scheme = [navigationAction.request.URL scheme];

    NSURL  * url = navigationAction.request.URL;
    UIApplication *app = [UIApplication sharedApplication];
    //    appstore的外的包
        if ([url.absoluteString containsString:@"itms-appss://"]) {
            [app openURL:url options:@{} completionHandler:^(BOOL success) {

            }];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }


    ///打电话
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [navigationAction.request.URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@", resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }




     if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
           decisionHandler(WKNavigationActionPolicyCancel);

           if ([navigationAction.request.URL.absoluteString hasPrefix:@"weixin://"]) {
               [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
           }
           return;
       }

    
    
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}

#pragma mark - WKUIDelegate
//创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"WebVC:创建一个新的WebView");
     WKFrameInfo *frameInfo = navigationAction.targetFrame;
       if (![frameInfo isMainFrame]) {
           [webView loadRequest:navigationAction.request];
       }
       return nil;
}

//输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
    NSLog(@"WebVC:输入框");
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    NSLog(@"WebVC:确认框");
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"WebVC:警告框");
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);

}


#pragma mark - event response
- (void)backClick
{
    
    NSLog(@"%lu",self.webView.backForwardList.backList.count);
    
    if (self.webView.backForwardList.backList.count > 0) {
        WKNavigation *navigation = [self.webView goBack];
        NSInteger offset = 1;
        while (!navigation)
        {
            offset++;
            if (self.webView.backForwardList.backList.count >= offset)
            {
                WKBackForwardListItem *item1 = [self.webView.backForwardList itemAtIndex:-offset];
                navigation = [self.webView goToBackForwardListItem:item1];
            }
            else
            {
                break;
            }
        }
        NSLog(@"WKNavigation - %@",navigation);
    }else{
        [self.parentViewController.navigationController popViewControllerAnimated:YES];
    }
    
   
    
    return;
    
    if (self.webView.canGoBack==YES) {
       // [self.webView goBack];
        [self.webView goBack];
    }else{
        //[self.navigationController.tabBarController.navigationController popViewControllerAnimated:YES];
        
        //[self.parentViewController.navigationController popViewControllerAnimated:YES];
        
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }
}



#pragma mark - getters and setters
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
//        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc]initWithDelegate:self];
        
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        
        
      
        
       config.userContentController = wkUController;
        

      
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight,CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - cl_kNavigationBarHeight)  configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.scrollView.bounces = false;
        
    
        
    }
    return _webView;
}

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