//
//  WKWebViewController.m
//  YHScrollView_Test
//
//  Created by Jim on 2021/9/4.
//

#import "WKWebViewController.h"
#import <WebKit/WebKit.h>

@interface WKWebViewController ()<WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate>{
    
}

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIView *progressBackView;
@property (nonatomic, strong) UIProgressView *myProgressView;

@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /* 加载WKWebView之前 先清空缓存 */
    [self clearWebViewCache];
    
    [self initProgressBackView];
    [self initView];
    
}

#pragma mark - private
-(void)initProgressBackView{
    self.progressBackView.hidden=NO;
    self.myProgressView.hidden=NO;
    [self.view bringSubviewToFront:self.progressBackView];
}

-(void)initView{
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 11.0){
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//        long long req_timestamp= [[NSDate date] timeIntervalSince1970]*1000;
//        NSString *req_timestampStr=[NSString stringWithFormat:@"%lld",req_timestamp];
        //参数拼接
        NSString* httpBody = [NSString stringWithFormat:@"uid=%@&channel=%@&version=%@&lang=%@&check_token=%@&tab_type=%@&req_timestamp=%@&sign=%@",@"",@"",@"",@"",@"",@"",@"",@""];
        
        [request setTimeoutInterval:10];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[httpBody dataUsingEncoding:NSUTF8StringEncoding]];
        [self.webView loadRequest:request];
    }else{
       /**
        long long req_timestamp= [[NSDate date] timeIntervalSince1970]*1000;
        NSString *req_timestampStr=[NSString stringWithFormat:@"%lld",req_timestamp];
        
        NSDictionary *param = @{@"uid":kUid,@"channel":channel,@"version":kAPPShortVersion,@"lang":language,@"check_token":accesstoken,@"tab_type":@(tab_type),@"req_timestamp":req_timestampStr};
        NSMutableString *sig = [[NSMutableString alloc] init];
        [sig appendFormat:@"%@%@",[YJJhikimotoxin sortDictionaryByKet:param],@"YTSaWAQhfMwGjX8ysdxfStEZvxAVOtRL"];
        NSString *sigStr = [Scorpionweed Fish_md5StringFromString:sig];
        
        NSDictionary *dataParam = @{@"uid":kUid,@"channel":channel,@"version":kAPPShortVersion,@"lang":language,@"check_token":accesstoken,@"tab_type":@(tab_type),@"req_timestamp":req_timestampStr,@"sign":sigStr};
        
        NSString * dataStr = [[[NSString alloc] initWithData:[dataParam jsonString] encoding:NSUTF8StringEncoding] base64EncodedString];
        NSString * urlStr = [NSString stringWithFormat:@"%@?data=%@",open_task_page,dataStr];
        */
        NSString * urlStr = [NSString stringWithFormat:@"%@?data=%@",@"",@""];
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [self.webView loadRequest:request];
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /** 刷新WebView*/
    if(_webView){
        [self refreshData];
    }
}

-(void)Fish_showWebView{
    self.webView.hidden=NO;
   
}
#pragma mark - WKNavigationDelegate 页面加载成功
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
    [self performSelector:@selector(Fish_showWebView) withObject:nil afterDelay:0];
}
//#pragma mark - 加载连接
- (void)webView:(WKWebView *)webView didFailLoadWithError:(nonnull NSError *)error{
    [self performSelector:@selector(Fish_showWebView) withObject:nil afterDelay:0];
}
#pragma mark - event response
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        
        if (newprogress >= 0.4f) {
            [self.progressBackView removeFromSuperview];
            [self Fish_showWebView];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - 代理方法
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
     /** js 调用OC方法*/
    if ([message.name caseInsensitiveCompare:@"GotoComplete"] == NSOrderedSame) {
        NSDictionary *taskDic = message.body;
        if(taskDic.allKeys.count){
            [self goToComplete:taskDic[@"list"]];
        }
    }
    if ([message.name caseInsensitiveCompare:@"showPoolsOverview"] == NSOrderedSame) {
        /** */
    }
}

#pragma mark --- OC调用JS方法，刷新数据
-(void)refreshData{
    NSLog(@"刷新============");
   
    NSString *javaScript=[NSString stringWithFormat:@"refreshData(%@)",@"0"];
    [_webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    }];
}
-(void)goToComplete:(NSDictionary *)taskDic{
    
}

#pragma mark --- GET
- (WKWebView *)webView{
    if (_webView == nil) {
        //注册js方法
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"GotoComplete"];
        [userContentController addScriptMessageHandler:self name:@"showPoolsOverview"];
        //webViewAppShare这个需保持跟服务器端的一致，服务器端通过这个name发消息，客户端这边回调接收消息，从而做相关的处理
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        config.userContentController = userContentController;
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0, 0.0, KScreenHeight, KScreenWidth) configuration:config];
        _webView.userInteractionEnabled = YES;
        _webView.backgroundColor = [UIColor blackColor];
        _webView.navigationDelegate=self;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_webView];
        _webView.hidden=YES;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [_webView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(KNavHeight);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(KScreenWidth);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];

    }
    return _webView;
}
- (UIView *)progressBackView
{
    if (_progressBackView == nil) {
        _progressBackView = [[UIView alloc] initWithFrame:CGRectMake(0,KNavHeight,KScreenWidth, KScreenHeight)];
        _progressBackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        [self.view addSubview:_progressBackView];
        
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0,KScreenWidth, 3)];
        _myProgressView.tintColor = UIColorFromRGB(0x00FF00);
        _myProgressView.trackTintColor = [UIColor clearColor];
        [_progressBackView addSubview:_myProgressView];
    }
    
    return _progressBackView;
}
// 记得取消监听
- (void)dealloc
{
    if (_webView) {
        [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
        [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"GotoComplete"];
        [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"showPoolsOverview"];
        
    }
}

#pragma mark --- 清理网页缓存
-(void)clearWebViewCache{
    
    WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
    [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray * __nonnull records) {
        for (WKWebsiteDataRecord *record in records) {
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{
                NSLog(@"Cookies for %@ deleted successfully",record.displayName);
            }];
        }
    }];
}

@end
