//
//  XXGWKBaseViewController.m
//  XXGPlayKit
//
//  Created by apple on 2025/3/12.
//

#import "XXGWKBaseViewController.h"
#import "XXGWKScriptMessageHandler.h"

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

@end

@implementation XXGWKBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.xxpk_closeButton.hidden = YES;
    self.xxpk_backButton.hidden = YES;
    [self xxpk_addWKWebView];
}

- (void)xxpk_addWKWebView
{
    WKUserContentController *xxpk_abonement = [[WKUserContentController alloc] init];
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:XXGUIDriver.xxpk_data_ui.xxpk_wk_abonementjs injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [xxpk_abonement addUserScript:userScript];
    
    WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preference = [[WKPreferences alloc]init];
    preference.javaScriptCanOpenWindowsAutomatically = YES;
    preference.minimumFontSize = 40.0;
    preference.javaScriptEnabled = YES;
    config.preferences = preference;
    config.selectionGranularity = WKSelectionGranularityDynamic;
    config.preferences.minimumFontSize = 18;
    config.preferences.javaScriptEnabled = YES;
    config.userContentController = xxpk_abonement;
    
    self.xxpk_wkview = [[WKWebView alloc] initWithFrame:CGRectZero];
    self.xxpk_wkview.backgroundColor = UIColor.clearColor;
    self.xxpk_wkview.scrollView.backgroundColor = UIColor.clearColor;
    self.xxpk_wkview.navigationDelegate = self;
    self.xxpk_wkview.opaque = YES;
    self.xxpk_wkview.scrollView.bounces = NO;
    self.xxpk_wkview.scrollView.showsVerticalScrollIndicator = NO;
    self.xxpk_wkview.scrollView.showsHorizontalScrollIndicator = NO;
    self.xxpk_wkview.UIDelegate = self;
    [self.view addSubview:self.xxpk_wkview];
    self.xxpk_wkview.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    // 使用弱引用代理
    XXGWKScriptMessageHandler *handler1 = [[XXGWKScriptMessageHandler alloc] initWithDelegate:self];
    XXGWKScriptMessageHandler *handler2 = [[XXGWKScriptMessageHandler alloc] initWithDelegate:self];
    
    [self.xxpk_wkview.configuration.userContentController addScriptMessageHandler:handler1 name:XXGUIDriver.xxpk_data_ui.xxpk_core_mt_coin_p];
    [self.xxpk_wkview.configuration.userContentController addScriptMessageHandler:handler2 name:XXGUIDriver.xxpk_data_ui.xxpk_core_mt_openUserCenterSidebar];
}

- (void)setXxpk_router:(NSString *)xxpk_router {
    _xxpk_router = xxpk_router;
    NSURL *url = [NSURL URLWithString:xxpk_router];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0];
    [request addValue:[XXGUIDriver xxpk_comeinedBoxToken] forHTTPHeaderField:XXGUIDriver.xxpk_data_ui.xxpk_wk_kds_token];
    [self.xxpk_wkview loadRequest:request];
}

- (void)xxpk_makeMethodActionOfAPPScheme:(NSURL *)URL {
    if ([self.xxpk_delegate respondsToSelector:@selector(xxpk_wkView:makeMethodAction:arg:)]) {
        [self.xxpk_delegate xxpk_wkView:self.xxpk_wkview makeMethodAction:URL.host arg:URL];
    }
}

// MARK: - WKWebViewDelegate
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 如果不添加这个，那么wkwebview跳转不了AppStore
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSLog(@"URL ---  %@",URL);
    if ([URL.scheme hasPrefix:XXGUIDriver.xxpk_data_ui.xxpk_app]) {
        [self xxpk_makeMethodActionOfAPPScheme:URL];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
//    [XXGLoadingView showLoadingOnView:self.view];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"wk-加载失败");
//    [XXGLoadingView hideLoadingFromView:self.view];
}

// 页面加载完成之后调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 禁止缩放
    [webView evaluateJavaScript:XXGUIDriver.xxpk_data_ui.xxpk_wk_injectionJSString completionHandler:nil];
    // 禁止长按选中
    [webView evaluateJavaScript:XXGUIDriver.xxpk_data_ui.xxpk_wk_touchCallout completionHandler:nil];
    [webView evaluateJavaScript:XXGUIDriver.xxpk_data_ui.xxpk_wk_UserSelect completionHandler:nil];
    
    [XXGLoadingView hideLoadingFromView:self.view];
    while (self.xxpk_wkview.isLoading) {
        return;
    }
}

// MARK: - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"name:%@",message.name);
    NSLog(@"body:%@",message.body);
    if ([self.xxpk_delegate respondsToSelector:@selector(xxpk_wkView:makeMethodAction:arg:)]) {
        [self.xxpk_delegate xxpk_wkView:self.xxpk_wkview makeMethodAction:message.name arg:message.body];
    }
}

-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@", message);
    [XXGAlertView xxpk_showAlertWithTitle:@"" message:message completion:^(NSInteger buttonIndex) {
        completionHandler();
    }];
}

// MARK: - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    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{
    completionHandler(XXGUIDriver.xxpk_data_ui.xxpk_wk_http);
}

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}

- (void)dealloc {
    self.xxpk_wkview.UIDelegate = nil;
    self.view = nil;
    [self.xxpk_wkview.configuration.userContentController removeAllUserScripts];
}

@end
