//
//  NewsWebViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/1/29.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "NewsWebViewController.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"

//第三方
#import <Masonry.h>
#import <WXApi.h>

#import "CTToast.h"

//类别
#import "UIView+frameAdjust.h"
#import "UIImage+Custom.h"


//环境配置
#import "Constants.h"

//VC
#import "LoginVC.h"
#import "CoinsDetailListVC.h"

#import "NewsCoinsManager.h"

#import "KKShareView.h"

//小满
#import <BXMediaSDK/BXMediaMaterialManager.h>
#import "KKActivityViewController.h"



#define CircleWidth 40.0f

#define GIFImageWidth 25.0f

#define GIFImageHeight 25.0f

@interface NewsWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
    BOOL loadOk;
    int timeLength;
    
    BOOL isRequest;
    
    BOOL isStart;
    
    BOOL isPause;
    
    BOOL isResume;
    
    BOOL isBackground;
    
    BOOL isDelete;
    
    int coinCount;
}

@property (nonatomic, strong)WKWebView *webView;

@property (nonatomic, strong) CAShapeLayer *progressLayer;

@property (nonatomic, strong) CALayer *gradientLayer;


@property (strong, nonatomic)  dispatch_source_t timer;

@property (nonatomic, strong)  UIView*bg;

@property (nonatomic, strong) NewsCoinsManager *manager;

@property (nonatomic, strong)BXMMaterialModel *materialModel;

@end

@implementation NewsWebViewController
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];

    [self cleanCacheAndCookie];
    NSLog(@"页面已销毁");
    

    if (self.timer) {
        if (!isResume) {
            dispatch_resume(_timer);
        }
        
        dispatch_source_cancel(self.timer);
        self.timer = nil;// OK
    }

}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
         
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    BOOL success = [UserDefault boolForKey:@"quickLookNews"];
    if (success == NO) {
        [self startAnimation];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self navConfig];
    
    //init
    timeLength = 180;
    self.manager = [NewsCoinsManager sharedManager];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:whiteView];
    [whiteView addSubview:self.webView];
    
    __weak typeof(self) weakself = self;
    
    
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        
        self.navigationController.interactivePopGestureRecognizer.delegate = (id)weakself;
        
    }
    
    
    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
       }
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [self hiddenrequest];
    
}

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


- (void)navConfig {
    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button_2.frame = CGRectMake(-30, 0, 20, 25);
    button_2.titleLabel.textAlignment =NSTextAlignmentLeft;
    [button_2 setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button_2 addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];
    
    self.navigationItem.leftBarButtonItem = backButtonItem_2;
    
    
    UIBarButtonItem *coinsItem = [[UIBarButtonItem alloc]initWithCustomView:[self creatAnimaUI]];
    UIButton * shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(-30, 0, 20, 25);
    shareBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [shareBtn setImage:[UIImage imageNamed:@"news_share"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * shareBtnItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];

    BOOL success = [UserDefault boolForKey:@"quickLookNews"];
    if (success) {
        self.navigationItem.rightBarButtonItem = shareBtnItem;
    }else{
        self.navigationItem.rightBarButtonItems = @[shareBtnItem,coinsItem];
    }

   // self.navigationItem.rightBarButtonItem = shareBtnItem;
    
}

#pragma mark - 隐藏
- (void)hiddenrequest
{
     NSString * url =[NSString stringWithFormat:@"%@%@",[NetworkConfig ipSwitchConfig],SwitchRequest];
    
    NSString*version = nil;
           NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
           NSArray*vArr = [v componentsSeparatedByString:@"."];
           
           for (int i = 0; i < vArr.count; i++) {
               if (version == nil) {
                   version = [NSString stringWithFormat:@"kklife%@",vArr[i]];
               }else{
                   version = [version stringByAppendingFormat:@"%@",vArr[i]];
               }
           }
           
           NSDictionary*params = @{
               @"version":version
           };
              
      [NetworkRequest Get:url Params:params Success:^(id _Nonnull responseObject) {
          
          NSString* state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
          if ([state isEqualToString:@"200"]) {
              NSString* result = responseObject[@"result"];
              if ([result isEqualToString:@"0"]) {
                  
                  [self addRedPackage];
              }
          }
          
          
      } Failure:^(NSError* error) {
         
    }];
}

- (void)addRedPackage
{
    //素材使用代码
   //素材曝光,一般在素材加载完成的时候调用.如果不知道素材加载好的时机,可以在素材所在页面加载完成的时候调用
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   
   
   //加载素材6667
   //__weak typeof(self) weakSelf = self;
   [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"9194" thirdUserId:@"" success:^(BXMMaterialModel *model) {
       //weakSelf.model = model;
       if (model) {
           self.materialModel = model;
           [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"9194" userId:@"" materialModel:model];
           
           UIImageView *redPackageView = [[UIImageView alloc]init];
  
           redPackageView.frame = CGRectMake(ScreenWidth - 80, ScreenHeight  - 100, 60, 60);
           
           
           [redPackageView sd_setImageWithURL:[NSURL URLWithString:model.materialPath]];
           
           redPackageView.userInteractionEnabled = YES;
           
           [self.view addSubview:redPackageView];
           
           UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(redPackClick:)];
           
           [redPackageView addGestureRecognizer:ges];
  
       }
   } fail:^(NSString *error) {
       
   }];
}


#pragma mark - 通知绑定方法

///监听应用退到后台
 - (void)didEnterBackground
{
   
    //[self pausmeAnimation];
    //[self pauseTimer];
    
    [self pausmeAnimation];
}
///恢复旋转
- (void)didBecomeActive
{
    //[self resumeAnimation];
}


#pragma mark - 看新闻得金币
- (NSDictionary *)readNewsGetCoinsRequestPara {
    
    NSString *endTimeStr = [Tools getNowTimeTimestamp];
    NSDictionary* params = @{
        @"uid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
        @"telphone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"watchstarttime":self.manager.startTime ? self.manager.startTime :@"",
        @"watchendtime":endTimeStr ? endTimeStr : @"",
        @"currentpagetotalheight":@(0),
        @"currentNewsHeight":@(0),
        @"currentPageUrl":self.url,
        @"frommodel":[NSNumber numberWithInt:2],
        @"eventtype":[NSNumber numberWithInt:1001],
        
        @"slidingdistance":@(0),
        @"slidingTime":@(0)
    };
    
    return params;
}

- (void)readNewsGetCoinsRequest {
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@news/readnews",CoinsBaseUrl];//外网
    WeakSelf
    [NetworkRequest Get:url Params:[self readNewsGetCoinsRequestPara] Success:^(id _Nonnull objc) {
        __strong typeof(self) strongSelf = weakSelf;
        NSLog(@"objc:%@",objc);
        
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"code"]];
            if ([code isEqualToString:@"0"]) {
                strongSelf->coinCount++;
                if ([objc[@"result"] isKindOfClass:[NSDictionary class]]) {
                    NSString*score = [NSString stringWithFormat:@"+%@",objc[@"result"][@"score"]];
                    [CTToast showWithMessage:score image:@"readNews-coins-toastBackView" duration:1];
                    
                    [strongSelf startAnimation];
                }
            }
        }
        
    } Failure:^(NSError* error) {
        NSLog(@"error");
    }];
    
}



#pragma mark - 开始动画
- (void)startAnimation {
    
    if (coinCount >= 3) {
        return;
    }
    
    if (isStart) {
        return;
    }
    
    isStart = YES;
    isPause = NO;
    isResume = YES;
    NSLog(@"startAnimation");
    [self openCountdown];
}

- (void)pausmeAnimation {
    
    if (isPause) {
        return;
    }
    
    isPause = YES;
    isResume = NO;
    
    NSLog(@"pausmeAnimation");
    [self pauseTimer];
}

- (void)resumeAnimation {
    if (isPause == NO) {
        return;
    }
    
    if (isResume) {
        return;
    }
    
    NSLog(@"resumeAnimation");
    
    isPause = NO;
    isResume = YES;
    
    [self resumeTimer];
}



#pragma mark - 创建动画
- (UIView *)creatAnimaUI {
    
    
    //创建动画容器
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CircleWidth, CircleWidth)];
    bg.backgroundColor = [UIColor clearColor];
    
    
//    UIImageView* coinImage = [UIImageView new];
//    coinImage.bounds = CGRectMake(0, 0, GIFImageWidth, GIFImageHeight);
//    coinImage.center = bg.center;
//
//    coinImage.image = [JobUtil changeImageToGit:@"news_coins.gif"];
    
    UIButton *coinsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    coinsBtn.frame = CGRectMake(0, 0, GIFImageWidth, GIFImageHeight);
    coinsBtn.center = bg.center;

    [coinsBtn setImage:[JobUtil changeImageToGit:@"news_coins.gif"] forState:UIControlStateNormal];
    
    [coinsBtn addTarget:self action:@selector(coinsBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //[coinImage addSubview:coinsBtn];
    
    [bg addSubview:coinsBtn];
    
    
    //贝塞尔曲线画圆弧
    
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CircleWidth/2, CircleWidth/2) radius:(CircleWidth-6)/2.0 startAngle:-M_PI/2 endAngle:3*M_PI/2 clockwise:YES];
    //设置颜色
    [[UIColor colorWithHex:0xF6F6F9] set];
    circlePath.lineWidth = 2;
    //开始绘图
    [circlePath stroke];
    
    //创建背景视图
    CAShapeLayer *bgLayer = [CAShapeLayer layer];
    bgLayer.frame = bg.bounds;
    bgLayer.fillColor = [UIColor clearColor].CGColor;//填充色 - 透明
    bgLayer.lineWidth = 2;//线条宽度
    bgLayer.strokeColor = [UIColor colorWithHex:0xe5e5e5].CGColor;//线条颜色
    bgLayer.strokeStart = 0;//起始点
    bgLayer.strokeEnd = 1;//终点
    bgLayer.lineCap = kCALineCapRound;//让线两端是圆滑的状态
    bgLayer.path = circlePath.CGPath;//这里就是把背景的路径设为之前贝塞尔曲线的那个路径
    [bg.layer addSublayer:bgLayer];
    self.bg = bg;
    
    //创建进度条视图
    _progressLayer = [CAShapeLayer layer];
    _progressLayer.frame = bg.bounds;
    _progressLayer.fillColor = [UIColor clearColor].CGColor;
    _progressLayer.lineWidth = 2;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.strokeColor = [UIColor yellowColor].CGColor;
    _progressLayer.strokeStart = 0;
    _progressLayer.strokeEnd =   (1.0 - self.manager.timeLength/(float)timeLength);;
    _progressLayer.path = circlePath.CGPath;
    [bg.layer addSublayer:_progressLayer];
    
    
    return bg;
    
}


#pragma mark - 定时器
//开启倒计时效果

- (void)openCountdown {

//    WeakSelf
    
    if (self.timer == nil) {
       
        __weak __typeof(self) weakSelf = self;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        

        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,0.1*NSEC_PER_SEC, 0); //每秒执行
        

        dispatch_source_set_event_handler(timer, ^{
            __strong typeof(self) strongSelf = weakSelf;

            if(strongSelf.manager.time <= 0){ //倒计时结束，关闭
                strongSelf.manager.time = strongSelf.manager.timeLength;
               
               [strongSelf stopTimer];
                

                dispatch_async(dispatch_get_main_queue(), ^{
            
                    [strongSelf readNewsGetCoinsRequest];
        
                });

            }else{
//                if (time == 120) {
//                    //strongSelf->startTime = [NSString stringWithFormat:@"%@",@([strongSelf getNowTimeTimestamp3])];
//                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    strongSelf.progressLayer.strokeEnd = (1.0 - strongSelf.manager.time/(float)strongSelf.manager.timeLength);
                    NSLog(@">>>>>>%.2ld",(long)strongSelf.manager.time);

                });
                if (strongSelf.manager.timeCount <= 0) {
                    [strongSelf pausmeAnimation];
                    strongSelf.manager.timeCount = strongSelf.manager.timeCountLength;
                }

                strongSelf.manager.time--;
                strongSelf.manager.timeCount--;
                
            }
        });

        dispatch_resume(timer);
        self.manager.startTime = [Tools getNowTimeTimestamp];
         
         self.timer = timer;
    }
   
}

-(void) pauseTimer{
    if(self.timer){
        dispatch_suspend(_timer);
    }
}
-(void) resumeTimer{
    if(self.timer){
        dispatch_resume(_timer);
    }
}
-(void) stopTimer{
    if(self.timer){
        if (isPause) {
            dispatch_resume(_timer);
            dispatch_source_cancel(_timer);
            _timer = nil;
            isStart = NO;
            isPause = NO;
            isResume = NO;
        }else{
            dispatch_source_cancel(_timer);
            _timer = nil;
            isStart = NO;
            isPause = NO;
            isResume = NO;
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate
// called when a gesture recognizer attempts to transition out of UIGestureRecognizerStatePossible. returning NO causes it to transition to UIGestureRecognizerStateFailed
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        if (loadOk) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(kkNewsDetailViewControllerDidClose:withTime:)]) {
                [self.delegate kkNewsDetailViewControllerDidClose:self withTime:[self getNowTimeTimestamp]];
            }
        }
    }
    
    return YES;
}



#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* startTimeStamp = [self getNowTimeTimestamp];
    loadOk = YES;
    if (self.delegate && [self.delegate respondsToSelector:@selector(kkNewsDetailViewControllerDidFirstFinishLoad:withTime:)]) {
        [self.delegate kkNewsDetailViewControllerDidFirstFinishLoad:self withTime:startTimeStamp];
    }
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"WebVC:页面加载失败");
}
//接收到服务器跳转请求之后调用
- (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";
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"WebVC:发送请求之前,决定是否跳转");
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
//    NSString* reqUrl = navigationAction.request.URL.absoluteString;
    NSString * scheme = [navigationAction.request.URL scheme];
    
    NSURL  * url = navigationAction.request.URL;
    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 (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
           decisionHandler(WKNavigationActionPolicyCancel);
           
           if ([navigationAction.request.URL.absoluteString hasPrefix:@"weixin://"]) {
               [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
           }
           return;
       }
       
    
    
    //允许跳转
    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);
    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:@"InvokeToApp"]){
        NSString *str = message.body;
        [[clickEvent instance] clickEventRooterVC:self Content:str menuName:@""];
    }else if ([message.name isEqualToString:@"shareUrl"]) {
        NSDictionary*dic = message.body;
        NSString*type = dic[@"type"];
        NSString*url = dic[@"url"];
        NSString*title = dic[@"title"];
        NSString*describe = dic[@"describe"];
        NSString*imageUrl = dic[@"imageUrl"];
        if ([type isEqualToString:@"好友"]) {
            [self share5WebPageToPlatformType:UMSocialPlatformType_WechatSession url:url title:title message:describe imageUrl:imageUrl];
        }else if ([type isEqualToString:@"朋友圈"]) {
            [self share5WebPageToPlatformType:UMSocialPlatformType_WechatTimeLine url:url title:title message:describe imageUrl:imageUrl];
        }
    }
}
- (void)share5WebPageToPlatformType:(UMSocialPlatformType)platformType url:(NSString *)url title:(NSString *)title message:(NSString *)message imageUrl:(NSString *)imageUrl
{
    
    if (![WXApi isWXAppInstalled]) {
           [Tools showMessage:@"请先安装微信!!!"];
           return;
       }
    
//    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = nil;
    
    if ([title isEqualToString:@"元旦红包大放送"]) {
        shareObject = [UMShareWebpageObject shareObjectWithTitle:@"元旦红包大放送" descr:@"存款领现金，最高100元" thumImage:[UIImage imageNamed:@"cqgAcitvity"]];
    }else if ([title isEqualToString:@"集牛气赢大奖，牛气冲天过大年"]){
        shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:message thumImage:[UIImage imageNamed:@"shareMowIcon"]];
        
    } else{
        if (imageUrl.length > 0) {
            shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:message thumImage:imageUrl];
        }else{
            shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:message thumImage:[UIImage imageNamed:@"login_icon"]];
        }
    }
   
      
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
            
           // [weakSelf loadData2:@"1015"];
        }
        
    }];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self resumeAnimation];
}


#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    
    if (loadOk) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(kkNewsDetailViewControllerDidClose:withTime:)]) {
            [self.delegate kkNewsDetailViewControllerDidClose:self withTime:[self getNowTimeTimestamp]];
        }
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)shareBtnClick:(UIButton *)sender {
    
    
    
    [KKShareView showShareAlertViewWithBlock:^(NSInteger tag) {
            
        switch (tag) {
            case 1:
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
            }
                break;
            case 2:
            {
                [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
            }
                break;
                
            default:
                break;
        }
        
    }];
    
    return;
    
    
}

- (void)coinsBtnClick:(UIButton *)sender {
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        

        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
              return;
          }
    
    
    CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
    vc.title = @"金币明细";
    vc.type = ListVCTypeCoinsDetail;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)redPackClick:(UIGestureRecognizer *)ges
{
    [NetworkRequest statisticsWithEventName:@"dialog_News_Envelope"];
//    NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"9194" userId:@"" materialModel:self.materialModel];
    
    KKActivityViewController *vc = [KKActivityViewController new];
    vc.title = @"幸运红包";
    vc.placeId = @"9194";
//    vc.buId = @"947689995";
//    vc.gdtAdId = @"9002117197798706";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 分享
//网页分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
//    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
    NSString *imageIconUrl = self.model.news_pic;
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"看看生活" descr:self.model.title thumImage:imageIconUrl];
    
    
    
    
    
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"安全认证 轻松领钱" descr:@"限时抢购补贴口罩，就差你啦！" thumImage:[UIImage imageNamed:@"login_icon"]];
    //设置网页地址
    NSString *url = [NSString stringWithFormat:@"%@&from=app_share",self.model.news_url];//外网
    //NSString *url = [NSString stringWithFormat:@"http://172.16.10.144/projects/html-nginx/html-nginx/lesson/award/share/index.html?userid=%ld&telephone=%@",(long)[getPeopleID PeopleID],[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];//内网
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
            
            
        }
        
    }];
}


#pragma mark - private methods

-(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 imageByScalingAndCroppingForSize:CGSizeMake(483, 644) and:image];
    //照片是对的完全没有问题,如果想加快速度必须让戴海峰配合的去弄,否则毫无办法,因为把他放在网上转base64是可以转出来的,如果想提速只要调用上面的这个方法即可.否则毫无办法,上面两个方法都是可以的
    //这里的0.3决定了照片认证的精确值
    image1 =   [SecondSocialViewController image:image1 rotation:UIImageOrientationLeft];
    NSData *str2=UIImageJPEGRepresentation(image1, 0.4);
    
   
    NSString *str3=[EnercryTool encryptBase64:str2];

   
    return str3;
    
}

/**
 *  字典转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;
}

#pragma mark - 获取当前时间戳
//精确到毫秒
-(NSString * )getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString* timeSp = [NSString stringWithFormat:@"%ld",(long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}



#pragma mark - getters and setters
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc]initWithDelegate:self];
        
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shareUrl"];
      
        
       config.userContentController = wkUController;

        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.scrollView.bounces = false;

        _webView.scrollView.delegate = self;
        
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
        
        [_webView loadRequest:request];
        
        
    }
    return _webView;
}
#pragma mark - 清理缓存
- (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 - 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
