//
//  WJWebVC.m
//  Open
//
//  Created by 雷俊博 on 2020/10/14.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "WJWebVC.h"
#import <WebKit/WebKit.h>
#import <Masonry.h>
#import "WeakWebViewScriptMessageDelegate.h"
#import "UIImage+Custom.h"

#import "SDImageCache.h"

#import "Globaltypedef.h"
#if TARGET_IPHONE_SIMULATOR == 0
#import "SCCaptureCameraController.h"
#endif

#import "HeathOrganViewController.h"




//WKUIDelegate:主要处理js脚本,确认框,警告框等
//WKNavigationDelegate:主要处理一些跳转、加载处理操作，

@interface WJWebVC ()
#if TARGET_IPHONE_SIMULATOR == 0
<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SCNavigationControllerDelegate>
#endif
{
    NSString*type;
    NSString*bankName;
    NSString*bankNum;
    UIImage*bankCardImg;
}
@property (nonatomic, strong)WKWebView *webView;

//网页加载进度视图
@property (nonatomic, strong) UIProgressView * progressView;

//@property (nonatomic, strong)WKUserContentController *userContentController;

@property (nonatomic,strong) UIImagePickerController *imagePicker;
@end

@implementation WJWebVC

#pragma mark - life cycle

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([self.title isEqualToString:@"高龄登记"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_gaoling" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"津贴申领"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_jintieshenling" withArgs:@{}];//个推统计
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];

    //添加监测网页加载进度的观察者
       [self.webView addObserver:self
                      forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                         options:0
                         context:nil];
    
    [self cleanCacheAndCookie];
    
    [self navConfig];
   
}

- (void)navConfig
{
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(-10, 0, 60, 44);
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* leftItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
}



//kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _webView) {
        
        NSLog(@"网页加载进度 = %f",_webView.estimatedProgress);
        self.progressView.progress = _webView.estimatedProgress;
        if (_webView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
        
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}




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


- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
}



- (void)dealloc
{
   // [self.userContentController removeScriptMessageHandlerForName:@"toNews()"];
    NSLog(@"WebVC:%@销毁了",self.title);
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

#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:页面加载完成");
    
    NSString *injectionJSString = @"var script = document.createElement('meta');"  "script.name = 'viewport';"    "script.content=\"width=device-width, user-scalable=no\";"    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    
    if([self.title isEqualToString:@"社保计算器"]){
        [webView evaluateJavaScript:@"document.documentElement.getElementsByClassName('mc-button')[0].style.display = 'none';" completionHandler:nil];
        
        
    }
    
    if ([self.title isEqualToString:@"津贴申领"] || [self.title isEqualToString:@"高龄登记"]) {
        
            NSData *data = [NSJSONSerialization dataWithJSONObject:self.params options:kNilOptions error:nil];
            NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 
         jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
         jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        
        NSLog(@"%@",jsonStr);
        //NSString* jsonStr = [self UIUtilsFomateJsonWithDictionary:self.params];
        
        
       
        
        
         NSString *inputValueJS = [NSString stringWithFormat:@"getMsg(%@)",jsonStr];
        
      
        
         [webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            //打印如果error为null，表示已调通
            NSLog(@"value: %@ error: %@", response, error);
         }];
    }
    

  
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"WebVC:页面加载失败");
    [self.progressView setProgress:0.0f animated:NO];
}
//接收到服务器跳转请求之后调用
- (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);
}

// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"WebVC:发送请求之前,决定是否跳转");
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    NSURL *URL = navigationAction.request.URL;
       NSString *scheme = [URL scheme];
       if ([scheme isEqualToString:@"tel"]) {
           NSString *resourceSpecifier = [URL resourceSpecifier];
           NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
           /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
       }
    
    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);
    //用message.body获得JS传出的参数体
    //JS调用OC
    if([message.name isEqualToString:@"getCamera"]){
        
        type = message.body;
        if ([type isEqualToString:@"5"]) {
            [self startOCR];
        }else{
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }
        
       
    }else if ([message.name isEqualToString:@"goHome"]){
        for (UIViewController*vc  in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[HeathOrganViewController class]]) {
                HeathOrganViewController*hvc = (HeathOrganViewController*)vc;
                [hvc clearText];
                break;
            }
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - UIImagePickerControllerDelegate
 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
        [picker dismissViewControllerAnimated:YES completion:nil];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
     
     
     NSString *inputValue = [NSString stringWithFormat:@"getImg('%@,%@')",type,[self changeBase64:image]];
     
     [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"value图片: %@ error: %@", response, error);
      }];
     
    
        
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
        [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - SCNavigationControllerDelegate
// 银行卡识别接口
- (void)sendBankCardInfo:(NSString *)bank_num BANK_NAME:(NSString *)bank_name BANK_ORGCODE:(NSString *)bank_orgcode BANK_CLASS:(NSString *)bank_class CARD_NAME:(NSString *)card_name
{
    bankNum = bank_num;
    bankName = bank_name;
}
- (void)sendBankCardImage:(UIImage *)BankCardImage
{
    bankCardImg = BankCardImage;
    
    
    [self performSelector:@selector(postBankInfo) withObject:nil afterDelay:0.2f];
    
}



#pragma mark - private methods

- (void)cleanCacheAndCookie{
    
    if ([[[UIDevice currentDevice]systemVersion]intValue ] >= 9.0) {
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
   
    
}


//渐变色
- (UIImage *)convertViewToImage:(UIView *)v
{
    CGSize s = v.bounds.size;
    //UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.opaque = NO;
    format.scale = [UIScreen mainScreen].scale;
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:s format:format];
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {

        NSLog(@"%@",error);

    }else{

        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;

}

- (NSString *)UIUtilsFomateJsonWithDictionary:(NSDictionary *)dic {

    NSArray *keys = [dic allKeys];

    NSString *string = [NSString string];

    

    for (NSString *key in keys) {

        NSString *value = [dic objectForKey:key];

 

        value = [NSString stringWithFormat:@"\"%@\"",value];

        NSString *newkey = [NSString stringWithFormat:@"\"%@\"",key];

        

        

        if (!string.length) {

            string = [NSString stringWithFormat:@"%@:%@}",newkey,value];

        }else {

            string = [NSString stringWithFormat:@"%@:%@,%@",newkey,value,string];

        }

    }

    string = [NSString stringWithFormat:@"{%@",string];

    return string;

}

-(NSString *)changeBase64:(UIImage*)image
{
    CGSize imagesize = image.size;
    NSLog(@"%lf",image.size.height);
    NSLog(@"%lf",image.size.width);
    imagesize.height =50;
    imagesize.width =50;
    //对图片大小进行压缩--
    
    //    UIImage *image1=   [SecondSocialViewController imageCompressFitSizeScale:image targetSize:CGSizeMake(image.size.width/4, image.size.height/4)];
    
    UIImage *image1=    [UIImage imageWithImage:image scale:0.5];
    //照片是对的完全没有问题,如果想加快速度必须让戴海峰配合的去弄,否则毫无办法,因为把他放在网上转base64是可以转出来的,如果想提速只要调用上面的这个方法即可.否则毫无办法,上面两个方法都是可以的
    //这里的0.3决定了照片认证的精确值
   // image1 =   [UIImage image:image1 rotation:UIImageOrientationLeft];
    NSData *str2=UIImageJPEGRepresentation(image1, 0.4);
    
   
    NSString *str3=[SecurityUtil encodeBase64Data:str2];

   
    return str3;
    
}

#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    if (self.webView.canGoBack==YES) {
       // [self.webView goBack];
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 启动ocr
- (void)startOCR
{
    
    #if TARGET_IPHONE_SIMULATOR == 0
    SCCaptureCameraController*con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDBANK; // 其他证件以此类推
    con.isDisPlayTxt = NO;
    con.ScanMode = TIDC_SCAN_MODE;
    con.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:con animated:YES completion:NULL];
    #endif
    
}

#pragma mark - postBank
- (void)postBankInfo
{
    if (bankName && bankNum && bankCardImg) {
        NSString *inputValue = [NSString stringWithFormat:@"getBankImg('%@,%@,%@,%@')",type,bankNum,bankName,[self changeBase64:bankCardImg]];
              
       [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                 NSLog(@"value图片: %@ error: %@", response, error);
       }];
    }
   
}

#pragma mark - getters and setters
- (UIView *)getNavBackView
{
    UIView*backView = [[UIView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth,cl_kNavigationBarHeight)];
    CAGradientLayer*gradientLayer = [CAGradientLayer layer];
    gradientLayer.locations = @[@0.0, @1.0];
    gradientLayer.startPoint = CGPointMake(1, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0xff5633] CGColor],(id)[[UIColor colorWithHex:0xf8502c] CGColor]]];//渐变数组
    gradientLayer.frame = backView.frame;
    [backView.layer addSublayer:gradientLayer];
    return backView;
}

- (UIProgressView *)progressView
{
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,  1, self.view.frame.size.width, 2)];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc]initWithDelegate:self];
        
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        
        
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"getCamera"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"goHome"];
       config.userContentController = wkUController;
        
        //以下代码适配文本大小
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        //用于进行JavaScript注入
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [config.userContentController addUserScript:wkUScript];

      
        _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.bounces = false;
    
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
            
            [_webView loadRequest:request];
    
        
        
    }
    return _webView;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    
    return _imagePicker;
}

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