//
//  CustomerWebViewController.m
//  VclustersGemini
//
//  Created by 余衡武 on 2022/8/11.
//  Copyright © 2022 APPLE. All rights reserved.
//

#import "CustomerWebViewController.h"
#import <WebKit/WebKit.h>
#import "SafeForKey.h"
#import "iPhone.h"

@interface CustomerWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView                    *webView;

@end

@implementation CustomerWebViewController
@synthesize titleStr;
@synthesize needHidenNav;

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"share"];
}

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

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"share"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    /**导航栏显示*/

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self drawView];
}

- (void)drawView {
    
    [self.toolBar setHidden:YES];
    [self.navigationBar setHidden:YES];

    self.titleLabel.text = titleStr;
    
    // WKWebView
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:config];
    // 解决闪白问题
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];
    self.webView.opaque = NO;
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    //要配置点击事件
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        if (error == noErr) {
            if ([result isKindOfClass:[NSString class]]) {
                NSString *userAgent = result;
                NSString *appVersion = [iPhone appVersion];
                NSString *newUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@"iosVersionNumber/%@",appVersion]];
                [self.webView setCustomUserAgent:newUserAgent];
            }
        }
    }];
    
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (needHidenNav){
            make.top.mas_equalTo(0);
        }else{
            make.top.equalTo(self.navBarBGView.mas_bottom);
        }
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_W);
        make.bottom.mas_equalTo(0);
    }];

    // 加载网页
    NSURL *url = [NSURL URLWithString:self.webUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    if (needHidenNav){
        [self.navBarBGView setHidden:YES];
        [self.view addSubview:self.backBtn];
        [self.backBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(H_STATE_BAR + 12.f);
        }];
    }else{
        [self.navBarBGView setHidden:NO];
    }
}


#pragma mark 事件代理
// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self showWebView0];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题，动态改变
    [self removeNewIndicator];
    
    [self showWebView1];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [self removeNewIndicator];

    [self showWebView3];
}

#pragma mark - 解决wkwebView闪白问题
// 解决wkwebView闪白问题
- (void)showWebView0 {
    
    self.webView.hidden = YES;
    
    [self performSelector:@selector(showWebView1) withObject:self afterDelay:1];
    
    [self showNewIndicatorWithCanBack:YES canTouch:NO];
}
    
// 1改变网页内容背景颜色
- (void)showWebView1 {
    [self performSelector:@selector(showWebView2) withObject:self afterDelay:0.2];
}

// 2加载成功
- (void)showWebView2 {
    [self removeNewIndicator];
    self.webView.hidden = NO;
}

// 3加载失败
- (void)showWebView3 {
    [self removeNewIndicator];
}

// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
    NSArray *arrViewControllers = self.navigationController.viewControllers;
    NSInteger index = [arrViewControllers indexOfObject:self];
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    if (navigationAction.targetFrame == nil) {

        [webView loadRequest:navigationAction.request];

    }
    
    //这句是必须加上的，不然会异常
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    HLog(@"%@",message.body);
    HLog(@"%@",message.name);
    [[iToast makeText:@"已接收到消息"] show];

}


@end
