//
//  WebViewController.m
//  Open
//
//  Created by gao on 2017/2/7.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "WebViewController.h"
//#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>

#import "WeakWebViewScriptMessageDelegate.h"

#import "Constants.h"


//社保缴费
#import "SSPaymenyViewController.h"
//药兜网
#import "YDAuthenticationHelper.h"
#import "YDTempUrlInstance.h"
#import "LoginVC.h"

//#import <YXLaunchAds/YXLaunchAds.h>
#import "GuideMoneyTreeAlertView.h"

//当前设备系统版本号
#define SYSTEMVersion [[[UIDevice currentDevice] systemVersion] floatValue]



static NSString *endPayRedirectURL = nil;
@interface WebViewController ()<UIScrollViewDelegate,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
{
    BOOL loadOk;
}

@property(nonatomic)BOOL failWeb;

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

@property (nonatomic, strong)UILabel *countdownLab;

@property (nonatomic) dispatch_source_t timer;
@end

@implementation WebViewController
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
   //这里是janalytics的分析页面的软件
    self.title =self.janalytics;
    if (self.URL != nil){}
        [MobClick beginLogPageView:self.janalytics];
    [JANALYTICSService startLogPageView:self.janalytics];
}

- (void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:animated];
    if (self.URL != nil){
        [MobClick endLogPageView:self.janalytics];
         [JANALYTICSService stopLogPageView:self.janalytics];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    if ([self.title isEqualToString:@"万年历"]) {
        [GTCountSDK trackCountEvent:@"life_wannianli" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"快递查询"]) {
        [GTCountSDK trackCountEvent:@"life_expressQuery" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"医院挂号"]) {
        [GTCountSDK trackCountEvent:@"home_yiyuanguahao" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"大病筹款"]) {
        [GTCountSDK trackCountEvent:@"home_dabingchoukuan" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"养老院"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_yanglaoyuan" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"救助热线"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_helpTel" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"民政信息"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_minzhengbu" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"医院"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_hosptial" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"社保机构"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_shebaojigou" withArgs:@{}];//个推统计
    }else if ([self.title isEqualToString:@"政务信息"]) {
        [GTCountSDK trackCountEvent:@"home_zhengwu_guojiarenshebu" withArgs:@{}];//个推统计
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    
    if ([self.janalytics isEqualToString:@"社保机构"]) {
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"shebaoDepartmentShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }else if ([self.janalytics isEqualToString:@"医院"]){
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"hospitalListShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }else if ([self.janalytics isEqualToString:@"养老院"]){
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"beadhouseShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }else if ([self.janalytics isEqualToString:@"大病筹款"]){
        NSDate *oldDate = [NSDate date];
        [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"seriousIllnessFundraisingShowLastTime"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }

    //悬浮倒计时闹钟
    if (self.TaskModel.clickeventFlag == 601 && self.TaskModel.taskStatus == 305) {
        [self SuspensionCountdown];
    }
}
#pragma mark - 悬浮倒计时闹钟
- (void)SuspensionCountdown{
    UIView *SuspensionView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 80, ScreenHeight -  200, 60, 80)];
    [self.view addSubview:SuspensionView];
    [self.view bringSubviewToFront:SuspensionView];
    UIPanGestureRecognizer   *panTouch    =   [[UIPanGestureRecognizer  alloc]initWithTarget:self action:@selector(handlePan:)];
    [SuspensionView addGestureRecognizer:panTouch];
    
    UIImageView *alarmImgView = [[UIImageView alloc]initWithFrame:CGRectMake(9.5, 0, 41, 46)];
    alarmImgView.image = [UIImage imageNamed:@"alarm"];
    [SuspensionView addSubview:alarmImgView];
    
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, 60, 30)];
    baseView.backgroundColor = [UIColor colorWithHex:0xff9126];
    baseView.layer.masksToBounds = YES;
    baseView.layer.cornerRadius = 15;
    [SuspensionView addSubview:baseView];
    
    UILabel *countdownLab = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 50, 30)];
    countdownLab.textAlignment = NSTextAlignmentCenter;
    countdownLab.text = @"浏览10秒领取奖励";
    countdownLab.textColor = [UIColor whiteColor];
    countdownLab.font = [UIFont boldSystemFontOfSize:10];
    countdownLab.numberOfLines = 0;
    [baseView addSubview:countdownLab];
    self.countdownLab = countdownLab;
    
    [self updateCountdownUI];
}
/**
 *  处理拖动手势
 *
 *  @param recognizer 拖动手势识别器对象实例
 */
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    //视图前置操作
    [recognizer.view.superview bringSubviewToFront:recognizer.view];
    
    CGPoint center = recognizer.view.center;
    CGFloat cornerRadius = recognizer.view.frame.size.width / 2;
    CGPoint translation = [recognizer translationInView:self.view];
    //NSLog(@"%@", NSStringFromCGPoint(translation));
    recognizer.view.center = CGPointMake(center.x + translation.x, center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
    
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        //计算速度向量的长度，当他小于200时，滑行会很短
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult); //e.g. 397.973175, slideMult: 1.989866
        
        //基于速度和速度因素计算一个终点
        float slideFactor = 0.1 * slideMult;
        CGPoint finalPoint = CGPointMake(center.x + (velocity.x * slideFactor),
                                         center.y + (velocity.y * slideFactor));
        //限制最小［cornerRadius］和最大边界值［self.view.bounds.size.width - cornerRadius］，以免拖动出屏幕界限
        finalPoint.x = MIN(MAX(finalPoint.x, cornerRadius),
                           self.view.bounds.size.width - cornerRadius);
        finalPoint.y = MIN(MAX(finalPoint.y, cornerRadius),
                           self.view.bounds.size.height - cornerRadius);
        
        //使用 UIView 动画使 view 滑行到终点
        [UIView animateWithDuration:slideFactor*2
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             recognizer.view.center = finalPoint;
                         }
                         completion:nil];
    }
}
- (void)updateCountdownUI{
    typeof(self) wSelf = self;
    // 倒计时时间
    __block int timeout         = self.TaskModel.clickTime;
    dispatch_queue_t queue      = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

    // 每秒执行
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{

        if (timeout <= 0)
        {
            //取消
            dispatch_source_cancel(wSelf.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 设置界面的按钮显示，根据自己需求设置
                wSelf.countdownLab.text = @"奖励已发放";
            });
        }
        else
        {
            NSString *strTime = [NSString stringWithFormat:@"浏览%i秒领取奖励", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                wSelf.countdownLab.text = strTime;
            });
            timeout--;
        }
    });
    //恢复
    dispatch_resume(_timer);
}
- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    //UIEdgeInsets insets = self.view.safeAreaInsets;
    //self.progressView.frame = CGRectMake(0, insets.top + 0.5, self.view.frame.size.width, 2);
}

- (void)dealloc
{
    NSLog(@"webviewcontorller销毁");
    //移除观察者
    [_wkWebView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    self.wkWebView.navigationDelegate = nil;
    self.wkWebView.UIDelegate = nil;
    self.wkWebView.scrollView.delegate = nil;
    
    //移除定时器
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil; // OK
    }
}

#pragma mark - UI
- (void)configUI
{
    [self navConfig];
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
    //添加监测网页加载进度的观察者
    [self.wkWebView addObserver:self
                   forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                      options:0
                      context:nil];
    
    [self cleanCacheAndCookie];
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 50, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn 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];
    [backBtn addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.janalytics;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}


- (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];
        
    }
   
    
}
#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:页面加载完成");
    
     if([self.janalytics 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:(null_unspecified 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);
}
static const NSString * CompanyFirstDomainByWeChatRegister = @"k.yaodouwang.com";
// 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"WebVC:发送请求之前,决定是否跳转");
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
    NSURL  * url = navigationAction.request.URL;
    NSString * urlStr = navigationAction.request.URL.absoluteString;
    NSString * scheme = [navigationAction.request.URL scheme];
    UIApplication *app = [UIApplication sharedApplication];
    //    appstore的外的包
    if ([url.absoluteString containsString:@"itms-appss://"]) {
        [app openURL:url options:@{} completionHandler:^(BOOL success) {
            
        }];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    ///打电话
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [navigationAction.request.URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@", resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
    
    
    if ([urlStr isEqualToString:@"about:blank"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    NSLog(@"发送跳转请求：%@",urlStr);

    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;
            }
        }
     decisionHandler(WKNavigationActionPolicyAllow);
}

#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 - event response
-(void)buttonClick_1{
    if (self.wkWebView.canGoBack==YES) {
       // [self.webView goBack];
        [self.wkWebView goBack];
    }else{
//        if ([self.title isEqualToString:@"社保机构"]) {
//            NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"shebaoPayShowLastTime"];
//
//            if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//
//                [self.navigationController popViewControllerAnimated:YES];
//
//                return;
//            }
//
//            NSDate *oldDate = [NSDate date];
//            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"shebaoPayShowLastTime"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//
//            WeakSelf
//            [GuideAlertView showWithImageName:@"guide_jiaoshebao" VC:self Block:^(BOOL success) {
//                [weakSelf goToShebaoPayVC];
//            }];
//            return;
//        }else if ([self.title isEqualToString:@"医院"]){
//            NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"CivilianPharmacyShowLastTime"];
//
//            if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//
//                [self.navigationController popViewControllerAnimated:YES];
//
//                return;
//            }
//
//            NSDate *oldDate = [NSDate date];
//            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"CivilianPharmacyShowLastTime"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//
//            WeakSelf
//            [GuideAlertView showWithImageName:@"guide_pingjia" VC:self Block:^(BOOL success) {
//                [weakSelf goToYaoDouVCWithLoginUrl:@"https://k.yaodouwang.com/"];
//            }];
//            return;
//        }else if ([self.title isEqualToString:@"养老院"]){
//            NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"ExpertFreeclinicShowLastTime"];
//
//            if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//
//                [self.navigationController popViewControllerAnimated:YES];
//
//                return;
//            }
//
//            NSDate *oldDate = [NSDate date];
//            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"ExpertFreeclinicShowLastTime"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//
//            WeakSelf
//            [GuideAlertView showWithImageName:@"guide_yizhen" VC:self Block:^(BOOL success) {
//                [weakSelf jumpToHTML5:@"https://m.haodf.com/nopen/yzexpertlist?partnerkey=9b6a9ed2bbf5910c" andJAnalytics:@"专家义诊"];
//            }];
//            return;
//        }else if ([self.title isEqualToString:@"限时特惠"]){
//            NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"YQADShowLastTime"];
//
//            if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
//
//                [self.navigationController popViewControllerAnimated:YES];
//
//                return;
//            }
//
//            NSDate *oldDate = [NSDate date];
//            [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"YQADShowLastTime"];
//            [[NSUserDefaults standardUserDefaults]synchronize];
//
//            WeakSelf
//            [GuideMoneyTreeAlertView showWithImageName:@"guide_yaoqianshu" VC:self Block:^(BOOL success) {
//                [YXAdSDKManager defaultManager].channelID = @"kksh-ios";
//                [YXAdSDKManager defaultManager].vuid = [NSString stringWithFormat:@"kksh_%@",@([getPeopleID PeopleID])];//渠道号前缀+_+用户ID
//                [weakSelf getH52TaskWebViewWithPostID:@"kksh-wd-banner"];
//            }];
//            return;
//        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}

#pragma mark - 社保缴费
- (void)goToShebaoPayVC
{
    SSPaymenyViewController *vc = [[SSPaymenyViewController alloc]init];
    vc.title = @"社保缴费";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 药兜网
- (void)goToYaoDouVCWithLoginUrl:(NSString *)url
{
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
       
        [self unLoginTap];
        return;
    }
    if ([YDTempUrlInstance shareInstance].data && ![self compareWithLastDate:[YDTempUrlInstance shareInstance].lastDate]) {
        NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:[YDTempUrlInstance shareInstance].data andUrl:url];
        
        Web2ViewController * vc = [Web2ViewController new];
        vc.title= @"平价药房";
        vc.skipUrl = skipUrl;
        [self.navigationController pushViewController:vc animated:YES];
        [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
        return;
    }
    
    
    NSDictionary * params = @{@"appId":@"201912161758",
                                 @"phone":[getPeopleID PeopleIphoneNmber]};
       __weak typeof(self) weakSelf = self;
    __block NSString* tempUrl = url;
       [YDAuthenticationHelper authentication:@"https://kankan.yaodouwang.com/user/login/open" body:params success:^(id  _Nonnull response) {
           
           if ([response isKindOfClass:[NSDictionary class]]) {
               NSDictionary * data = response[@"data"];
               NSURL * skipUrl = [YDAuthenticationHelper jointUrlWithBody:data andUrl:tempUrl];
               [YDTempUrlInstance shareInstance].data = data;
               [YDTempUrlInstance shareInstance].lastDate = [NSDate date];
               
               Web2ViewController * vc = [Web2ViewController new];
               vc.title= @"平价药房";
               vc.skipUrl = skipUrl;
               [weakSelf.navigationController pushViewController:vc animated:YES];
               [GTCountSDK trackCountEvent:@"H5_PingMingYaoFang" withArgs:nil];
               
           }else{
               NSLog(@"数据格式不正确 ===> %@",response);
           }
          
       } fail:^(id  _Nonnull error) {
           
           NSLog(@"请求失败，请登录 ===> %@",error);
           [weakSelf alertShow:@"网络异常,请稍后重试"];
       }];
}

#pragma mark - 提示

- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}


- (void)getH52TaskWebViewWithPostID:(NSString *)postID {
    
//    [YXAdSDKManager getMaterialWithPostID:postID Success:^(id  _Nonnull json) {
//
//        if (json) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                NSLog(@"接口请求成功 data=%@",json);
//                NSDictionary *dataDict = (NSDictionary *)json;
//                NSDictionary *dict = dataDict[@"data"];
//                if (dict[@"material_path"]) {
//                    //活动入口 标题与logo
//                    //展示到页面时 上报report_url ，具体参考文档
//                }
//
//                if ([postID isEqualToString:@"kksh-wd-banner"]) {
//                    NSDate *oldDate = [NSDate date];
//                    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"YQADShowLastTime"];
//                    [[NSUserDefaults standardUserDefaults]synchronize];
//                }
//
//                SFWebTaskViewController *taskVC = [SFWebTaskViewController new];
//                taskVC.urlStr = dict[@"page_url"];
//                taskVC.posId = postID;
//                taskVC.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:taskVC animated:YES];
//            });
//        }
//    } fail:^(NSError * _Nonnull error) {
//        NSLog(@"接口请求失败 error=%@",error);
//    }];
}
#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 - 未登录跳转
- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}
#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 - 判断时间是否超过1.5分钟
- (BOOL)compareWithLastDate:(NSDate *)lastDate
{
    NSTimeInterval distanceBetweenDates = [[NSDate date] timeIntervalSinceDate:lastDate];
    distanceBetweenDates = fabs(distanceBetweenDates);
    CGFloat hoursBetweenDates = distanceBetweenDates / 60.0;

    if (hoursBetweenDates >= 1.5) {
        return YES;
    }else{
        return NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    NSLog(@"内存警告了");
}

#pragma mark - KVO
//kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _wkWebView) {
        
        NSLog(@"网页加载进度 = %f",_wkWebView.estimatedProgress);
        self.progressView.progress = _wkWebView.estimatedProgress;
        if (_wkWebView.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];
    }
}

#pragma mark - getters and setters
- (WKWebView *)wkWebView   {
    if (!_wkWebView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        config.allowsPictureInPictureMediaPlayback = YES;
        if (@available(iOS 10.0, *)) {
            // WKAudiovisualMediaTypeNone 音视频的播放不需要用户手势触发, 即为自动播放
            config.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
        } else {
            config.requiresUserActionForMediaPlayback = NO;
        }
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc]initWithDelegate:self];
        
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"kkshHelper"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"showSaveQRAlertVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        config.userContentController = wkUController;
        
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) configuration:config];
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        _wkWebView.scrollView.delegate = self;
        _wkWebView.scrollView.bounces = false;
        _wkWebView.scrollView.showsVerticalScrollIndicator = NO;
        _wkWebView.scrollView.showsHorizontalScrollIndicator = NO;
        [_wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        NSMutableURLRequest*request = [[NSMutableURLRequest alloc] initWithURL:self.URL];
        if (self.jsString) {
           [_wkWebView loadHTMLString:self.jsString baseURL:nil];
        }else{
            [_wkWebView loadRequest:request];
        }
        
    }
    return _wkWebView;
}

- (UIProgressView *)progressView {
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight + 2, self.view.frame.size.width, 2)];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}
#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);
    if ([message.name isEqualToString:@"openUrl"]){
        NSArray *array = message.body;
        if ([array isKindOfClass:[NSArray class]]) {
            if (array.count == 2) {
                WebVC *webvc = [[WebVC alloc]init];
                webvc.url = array[1];
                webvc.title = array[0];
                webvc.fromName = self.title;
                webvc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webvc animated:YES];
            }
        }
    }else if ([message.name isEqualToString:@"showSaveQRAlertVC"]){
        NSString*urlString = message.body;
       
       [self showSaveQRAlertVC:urlString];
    }else if([message.name isEqualToString:@"InvokeToApp"]){
        //调用原生
        [[clickEvent instance] clickEventRooterVC:self Content:message.body menuName:@""];
    }
}
- (void)showSaveQRAlertVC:(NSString *)imgUrl
{
    UIAlertController*alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确实是否要保存图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction*confirmAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
        UIImage* image = [UIImage imageWithData:data];
               
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    
    if (error) {
        [Tools showMessage:@"保存失败"];
    }else{
        [Tools showMessage:@"保存成功"];
    }
    
    [self.wkWebView evaluateJavaScript:@"finGetImg('null')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value图片: %@ error: %@", response, error);
    }];
}
#pragma mark - json
/**
 *  字典转JSON字符串
 *
 *  @param dic 字典
 *
 *  @return JSON字符串
 */
- (NSString*) dictionaryToJson:(NSDictionary *)dic{
    NSString *json = nil;

    if ([NSJSONSerialization isValidJSONObject:dic]) {


      NSError *error;

      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];

      if(!error) {

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

      }

      else {

          NSLog(@"JSON parse error: %@", error);

      }
    }

    else {

      NSLog(@"Not a valid JSON object: %@", dic);
    }

    return json;
}
-(NSString *)noWhiteSpaceString:(NSString *)newString {
 //去除掉首尾的空白字符和换行字符
   newString = [newString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
   newString = [newString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
   newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符使用
   newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
//    可以去掉空格，注意此时生成的strUrl是autorelease属性的，所以不必对strUrl进行release操作！
   return newString;
}
@end
