//
//  Web2ViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/12/23.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "Web2ViewController.h"
#import <WebKit/WebKit.h>
#import "Constants.h"
#import "YDAuthenticationHelper.h"
#import "GTCountSDK.h"


#define webLogin @"backLoginFromH5"

#import "WXApi.h"
#import "CZBInfoManager.h"


static NSString *redirectScheme = @"msdev.czb365.com";
@interface Web2ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler,WKUIDelegate>

@property (nonatomic,strong) WKWebView * webView;
@property (nonatomic,strong) UIProgressView *progressView;
@property (nonatomic, copy) NSString * endPayRedirectURL;
@end

@implementation Web2ViewController

static NSString *endPayRedirectURL = nil;

- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:webLogin];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"mqToMap"];
    self.webView.navigationDelegate = nil;
    self.webView.UIDelegate = nil;
    self.webView.scrollView.delegate = nil;
}

- (WKWebView *)webView   {
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        
        [userContentController addScriptMessageHandler:self name:webLogin];
        [userContentController addScriptMessageHandler:self name:@"mqToMap"];
        configuration.userContentController = userContentController;
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
//        preferences.minimumFontSize = 40.0;
        configuration.preferences = preferences;
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.delegate = self;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        NSMutableURLRequest*request = [[NSMutableURLRequest alloc] initWithURL:self.skipUrl];
        if ([self.title isEqualToString:@"智能问诊"]) {
           
            if (@available(iOS 12.0, *)) {
                NSString *baseAgent = [_webView valueForKey:@"applicationNameForUserAgent"];
                NSString *userAgent = [NSString stringWithFormat:@"%@ kksb_app",baseAgent];
                [_webView setValue:userAgent forKey:@"applicationNameForUserAgent"];
            }
            [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
                NSString *oldAgent = result;
                if ([oldAgent rangeOfString:@"kksb_app"].location !=NSNotFound) {
                    return;
                }
                
                // 给User-Agent添加额外的信息
                NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"kksb_app"];

                // 设置global User-Agent
                if (@available(iOS 9.0, *)) {
                    [self->_webView setCustomUserAgent:newAgent];
                }else{
                    [self->_webView setValue:newAgent forKey:@"applicationNameForUserAgent"];
                }
                
            }];
        }
        [_webView loadRequest:request];
    }
    return _webView;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   // self.navigationController.navigationBar.hidden = YES;
//    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webLogin];
    if ([self.title isEqualToString:@"平价药房"]) {
        if ([self.type isEqualToString:@"优惠券"]) {
            [GTCountSDK trackCustomKeyValueEventEnd:@"H5_PingMingYaoFangCo" withArgs:nil];
        }else{
            [GTCountSDK trackCustomKeyValueEventBegin:@"H5_PingMingYaoFang" withArgs:nil];
        }
        
    }else if ([self.title isEqualToString:@"万年历"]) {
        [GTCountSDK trackCountEvent:@"life_wannianli" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"快递查询"]) {
        [GTCountSDK trackCountEvent:@"life_expressQuery" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"医疗服务"] || [self.title isEqualToString:@"医院挂号"]) {
        [GTCountSDK trackCountEvent:@"home_yiyuanguahao" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"订单支付"]) {
        [GTCountSDK trackCountEvent:@"home_shebaojiaofei_orderPay" withArgs:@{}];//个推统计
    }
    
    if ([self.title isEqualToString:@"存钱罐"]) {
        [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
          
        [self.navigationController.navigationBar navBarBottomLineHidden:YES];
        
//        UIButton* inviteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        inviteBtn.frame = CGRectMake(0, 0, 80, 60);
//        [inviteBtn setTitle:@"邀请好友" forState:UIControlStateNormal];
//        [inviteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        inviteBtn.titleLabel.font = [UIFont systemFontOfSize:17];
//        [inviteBtn addTarget:self action:@selector(inviteClick) forControlEvents:UIControlEventTouchUpInside];
//
//        UIBarButtonItem* rightItem = [[UIBarButtonItem alloc]initWithCustomView:inviteBtn];
//
//        self.navigationItem.rightBarButtonItem = rightItem;
    }
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   // self.navigationController.navigationBar.hidden = NO;
//    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:webLogin];
    if ([self.title isEqualToString:@"平价药房"]) {
        if ([self.type isEqualToString:@"优惠券"]) {
            [GTCountSDK trackCustomKeyValueEventEnd:@"H5_PingMingYaoFangCo" withArgs:nil];
        }else{
            [GTCountSDK trackCustomKeyValueEventEnd:@"H5_PingMingYaoFang" withArgs:nil];
        }
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //init
    self.view.backgroundColor = [UIColor whiteColor];
    
     
    //webview
    [self.view addSubview:self.webView];
       
    //UIProgressView
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 0.5)];
    self.progressView.backgroundColor = [UIColor whiteColor];
    self.progressView.tintColor = [UIColor colorWithRed:233/255.0 green:71/255.0 blue:58/255.0 alpha:1];
    [self.view addSubview:self.progressView];
    [self.view bringSubviewToFront:self.progressView];
    
   
       
//       NSArray * titles = @[@"<",@">"];
//       for (int i = 0; i<titles.count; i++) {
//           UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2*i, ScreenHeight - 30, ScreenWidth/2, 30)];
//           btn.tag = 10 + i;
//           [btn setTitle:titles[i] forState:UIControlStateNormal];
//           [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//           [btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
//           [self.view addSubview:btn];
//       }
    
  
       
    [self navConfig];
    
    [self cleanCacheAndCookie];
    
    if ([self.title isEqualToString:@"平价药房"]) {
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"CivilianPharmacyShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }else if ([self.title isEqualToString:@"专家义诊"]){
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"ExpertFreeclinicShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    _endPayRedirectURL = @"";
}


- (void)navConfig
{
//    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    button_2.frame = CGRectMake(-30, 0, 20, 25);
//    button_2.titleLabel.textAlignment =NSTextAlignmentLeft;
//    //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
//    [button_2 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];
//    [button_2 addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];
//
//    self.navigationItem.leftBarButtonItem = backButtonItem_2;
    
    
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = K_MainColor;
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(cl_kNavBarHeight);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.title;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(120);
        make.height.offset(cl_kNavBarHeight);
    }];
    
}

- (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];

    }
   
    
}


-(void)pressBtn:(UIButton *)button{
    if (button.tag == 10) {
        if (self.webView.canGoBack) {
            [self.webView goBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        if (self.webView.canGoForward) {
            [self.webView goForward];
        }
    }
}




#pragma mark - event response
-(void)buttonClick_1{

    if (self.webView.canGoBack==YES) {
       // [self.webView goBack];
        [self.webView goBack];
    }else{
       
        if ([self.title isEqualToString:@"救助热线"]) {
            
            NSDate *oldTime = [[NSUserDefaults       standardUserDefaults]objectForKey:@"seriousIllnessFundraisingShowLastTime"];

            if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
                
                [self.navigationController popViewControllerAnimated:YES];
                
                return;
            }
            
//            NSDate *oldDate = [NSDate date];
//            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"seriousIllnessFundraisingShowLastTime"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//            
//            WeakSelf
//            [GuideAlertView showWithImageName:@"guide_seeDoctor" VC:self Block:^(BOOL success) {
//                NSString * strA = @"https://www.shuidichou.com/tf/ads/business/register?channel=BD_cooperation_index_kankanshebao";
//                [weakSelf jumpToHTML5:strA andJAnalytics:@"大病筹款"];
//            }];
//            return;
        }
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}

- (void)bcAlertViewShow
{
    WeakSelf
    //1.创建UIAlertControler
       UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您确定要退出存钱罐吗" preferredStyle:UIAlertControllerStyleAlert];
       /*
        参数说明：
        Title:弹框的标题
        message:弹框的消息内容
        preferredStyle:弹框样式：UIAlertControllerStyleAlert
        */
       
       //2.添加按钮动作
       //2.1 确认按钮
       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           NSLog(@"点击了确认按钮");
           [weakSelf.navigationController popViewControllerAnimated:YES];
       }];
       //2.2 取消按钮
       UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           NSLog(@"点击了取消按钮");
       }];
    
       //3.将动作按钮 添加到控制器中
       [alert addAction:conform];
       [alert addAction:cancel];
       
       //4.显示弹框
       [self presentViewController:alert animated:YES completion:nil];
}

- (void)inviteClick
{
   // [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
    //NSString*urlStr = [NSString stringWithFormat:@"http://172.16.10.136/projects/html-nginx/html-nginx/appH5/Piggybank/index.html?tel=%ld&loginId=%@",[getPeopleID PeopleID],[getPeopleID PeopleIphoneNmber]];
    NSString*urlStr = [NSString stringWithFormat:@"http://nginx.weface.com.cn/appH5/Piggybank/index.html?tel=%ld&loginId=%@",[getPeopleID PeopleID],[getPeopleID PeopleIphoneNmber]];
    WebVC*vc = [WebVC new];
    vc.title = @"邀请好友";
    vc.url = urlStr;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}





#pragma mark - WKUIDelegate
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
       [webView loadRequest:navigationAction.request];
    }
     return nil;

}


#pragma mark - 监听加载进度
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
    [self.view bringSubviewToFront:self.progressView];
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = YES;
    
    if([self.title isEqualToString:@"社保计算器"]){
         NSString*jsStr = @"document.documentElement.getElementsByClassName('mc-button')[0].style.display = 'none';";
         [webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
             
         }];
    }
   
}
//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            self.progressView.hidden = YES;
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}



#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:webLogin]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    if ([message.name isEqualToString:@"mqToMap"]) {
        //支付
        if (![WXApi isWXAppInstalled]){
            [Tools showMessage:@"请安装微信APP后重试"];
            return;
        }
        NSDictionary *dic = message.body;
        if ([dic isKindOfClass:[NSDictionary class]]) {
            WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
            launchMiniProgramReq.userName = dic[@"userName"];  //拉起的小程序的username
            launchMiniProgramReq.path = dic[@"path"];    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
            [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                
            }];
        }
        
    }
}
#pragma mark - WKNavigationDelegate

static const NSString * CompanyFirstDomainByWeChatRegister = @"m.yaodouwang.com";
static const NSString * CompanySecondDomainByWeChatRegister = @"shanp.com";
static const NSString * CompanyThirdDomainByWeChatRegister = @"ilaw66.com";
static const NSString * CompanyFourDomainByWeChatRegister = @"m.360kad.com";
static const NSString * CompanyFiveDomainByWeChatRegister = @"haodf.com";

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    NSString* reqUrl = navigationAction.request.URL.absoluteString;
    NSString * scheme = [navigationAction.request.URL scheme];
    NSURL *url = navigationAction.request.URL;

    if ([reqUrl containsString:@"http://h5.weface.com.cn/20200109/sb/result?"]) {
        NSArray *array = [reqUrl componentsSeparatedByString:@"&result="];
        NSString*result =  array.lastObject;
        if ([result isEqualToString:@"fail"]) {
            decisionHandler(WKNavigationActionPolicyAllow);
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }else if ([result isEqualToString:@"success"]){

        }
    }
    
    ///打电话
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [navigationAction.request.URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@", resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
    
    
    if ([self.title isEqualToString:@"平价药房"]) {
        if ([reqUrl hasPrefix:@"alipays://"] || [reqUrl hasPrefix:@"alipay://"]) {
             [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            //是否成功调起支付宝
            
            NSURL* alipayURL = [YDAuthenticationHelper changeURLSchemeStr:reqUrl];
            if (@available(iOS 10.0, *)) {
               [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
               }];
            } else {
               [[UIApplication sharedApplication] openURL:alipayURL];
            }
       }
    }
    
    
    if ([self.title isEqualToString:@"平价药房"]) {
        if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFirstDomainByWeChatRegister]]) {
               decisionHandler(WKNavigationActionPolicyCancel);
               NSString *redirectUrl = nil;
               if ([reqUrl containsString:@"redirect_url="]) {
                   NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                   endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
                 redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFirstDomainByWeChatRegister]];
                  
               }else {
                   redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",CompanyFirstDomainByWeChatRegister]];
                   
               }
               
             
             NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
             newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
             [newRequest setValue:[NSString stringWithFormat:@"%@://",CompanyFirstDomainByWeChatRegister] forHTTPHeaderField:@"Referer"];
             newRequest.URL = [NSURL URLWithString:redirectUrl];
             [webView loadRequest:newRequest];
             return;
              
              
              
           }
    }else if ([self.title isEqualToString:@"订单支付"]){
        
        if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",CompanySecondDomainByWeChatRegister]]) {
               decisionHandler(WKNavigationActionPolicyCancel);
               NSString *redirectUrl = nil;
               if ([reqUrl containsString:@"redirect_url="]) {
                   NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                   endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
                   redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",CompanySecondDomainByWeChatRegister]];
                  
               }else {
                    redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",CompanySecondDomainByWeChatRegister]];
                   
               }
               
             
            NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
                    newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
              [newRequest setValue:[NSString stringWithFormat:@"%@://",CompanySecondDomainByWeChatRegister] forHTTPHeaderField:@"Referer"];
              newRequest.URL = [NSURL URLWithString:redirectUrl];
              [webView loadRequest:newRequest];

             return;
           }
    }else if ([self.title isEqualToString:@"问律师"]){
        
        if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",CompanyThirdDomainByWeChatRegister]]) {
               decisionHandler(WKNavigationActionPolicyCancel);
               NSString *redirectUrl = nil;
               if ([reqUrl containsString:@"redirect_url="]) {
                   NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                   endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
                 redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",CompanyThirdDomainByWeChatRegister]];
                  
               }else {
                   redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",CompanyThirdDomainByWeChatRegister]];
                   
               }
               
             
             NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
             newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
             [newRequest setValue:[NSString stringWithFormat:@"%@://",CompanyThirdDomainByWeChatRegister] forHTTPHeaderField:@"Referer"];
             newRequest.URL = [NSURL URLWithString:redirectUrl];
             [webView loadRequest:newRequest];
             return;
              
              
              
           }
    }else if ([self.title isEqualToString:@"便民药房"]){
        
        if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFourDomainByWeChatRegister]]) {
               decisionHandler(WKNavigationActionPolicyCancel);
               NSString *redirectUrl = nil;
               if ([reqUrl containsString:@"redirect_url="]) {
                   NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                   endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
                 redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFourDomainByWeChatRegister]];
                  
               }else {
                   redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",CompanyFourDomainByWeChatRegister]];
                   
               }
               
             
             NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
             newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
             [newRequest setValue:[NSString stringWithFormat:@"%@://",CompanyFourDomainByWeChatRegister] forHTTPHeaderField:@"Referer"];
             newRequest.URL = [NSURL URLWithString:redirectUrl];
             [webView loadRequest:newRequest];
             return;
              
              
              
           }
    }else if ([self.title isEqualToString:@"医疗服务"] || [self.title isEqualToString:@"专家义诊"] || [self.title isEqualToString:@"医院挂号"] || [self.title isEqualToString:@"快速问诊"] || [self.title isEqualToString:@"极速义诊"]){
        
        if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFiveDomainByWeChatRegister]]) {
               decisionHandler(WKNavigationActionPolicyCancel);
               NSString *redirectUrl = nil;
               if ([reqUrl containsString:@"redirect_url="]) {
                   NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                   endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
                 redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",CompanyFiveDomainByWeChatRegister]];
                  
               }else {
                   redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",CompanyFiveDomainByWeChatRegister]];
                   
               }

             
             NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
             newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
             [newRequest setValue:[NSString stringWithFormat:@"%@://",CompanyFiveDomainByWeChatRegister] forHTTPHeaderField:@"Referer"];
             newRequest.URL = [NSURL URLWithString:redirectUrl];
             [webView loadRequest:newRequest];
             return;
           }
        
        
    }

    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
        if ([url.scheme isEqualToString:@"weixin"] || [url.scheme isEqualToString:@"alipay"]) {
            if ( [[UIApplication sharedApplication] canOpenURL:url]) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:nil];
                } else {
                    [[UIApplication sharedApplication] openURL:url];
                }
                
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
        }
    }
    
    BOOL isAllow = [CZBInfoManager webView:webView decidePolicyForNavigationAction:navigationAction];
    WKNavigationActionPolicy actionPolicy = isAllow ? WKNavigationActionPolicyAllow:WKNavigationActionPolicyCancel;
    decisionHandler(actionPolicy);
}

#pragma mark - 跳转到H5页面
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    
    Web2ViewController * vc = [Web2ViewController new];
    vc.title= janalytics;
    vc.skipUrl = [NSURL URLWithString:url];
    [self.navigationController pushViewController:vc animated:YES];
    

}


#pragma mark -  判断是否是同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}


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

