//
//  KKFinancialViewController.m
//  Open
//
//  Created by qxy on 2021/11/4.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "KKFinancialViewController.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"
@interface KKFinancialViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong) NSDictionary *shareDic;
//@property (strong, nonatomic)  dispatch_source_t Counttimer;
@property (nonatomic, strong) UILabel *countdownLab;
@property (nonatomic, strong) UIView *SuspensionView;
@property (nonatomic) dispatch_source_t Counttimer;
@end

@implementation KKFinancialViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0xe42431] image:nil isOpaque:YES];//颜色
    
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:whiteView];
    [whiteView addSubview:self.webView];

    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
       }

    [self navConfig];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    [self.webView loadRequest:request];
    //获取抽奖次数状态
//    [self DrawStatus];
    
//    [self kefuUI];
    
    //悬浮倒计时闹钟
    if (self.TaskModel && self.TaskModel.clickeventFlag == 601 && self.TaskModel.taskStatus == 305) {
       [self SuspensionCountdown];
    }
}
#pragma mark - 悬浮倒计时闹钟
- (void)SuspensionCountdown{
    UIView *SuspensionView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 65, 0, 60, 80)];
    SuspensionView.centerY = self.view.centerY;
    [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 = [NSString stringWithFormat:@"浏览%d秒领取奖励", self.TaskModel.clickTime];
    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);
    _Counttimer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

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

        if (timeout <= 0)
        {
            //取消
            dispatch_source_cancel(wSelf.Counttimer);
            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(_Counttimer);
}
#pragma mark - 客服视图
- (void)kefuUI{
    UIButton *kefuBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 71, ScreenHeight -  290, 71, 39)];
    [kefuBtn setImage:[UIImage imageNamed:@"CustomerService"] forState:UIControlStateNormal];
    [kefuBtn setImage:[UIImage imageNamed:@"CustomerService"] forState:UIControlStateHighlighted];
    [self.view addSubview:kefuBtn];
    [kefuBtn addTarget:self action:@selector(kefu) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:kefuBtn];
}
#pragma mark -客服
- (void)kefu{
    [[clickEvent instance] clickEventRooterVC:self Content:@"weChatService" menuName:@"客服"];
    
    
//    WebVC *webvc = [[WebVC alloc]init];
//    webvc.url = @"https://nginx.weface.com.cn/appH5/piggyBankcl/saveMoney.html";
//    webvc.title = @"客服";
//    webvc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:webvc animated:YES];
}
//#pragma mark - 悬浮倒计时
//- (void)SuspensionCountdown{
//    UIView *SuspensionView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 84, ScreenHeight -  320, 84, 81)];
//    [self.view addSubview:SuspensionView];
//    [self.view bringSubviewToFront:SuspensionView];
//    UITapGestureRecognizer *tapTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Gesture)];
//    SuspensionView.userInteractionEnabled = NO;
//    [SuspensionView addGestureRecognizer:tapTouch];
//    self.SuspensionView = SuspensionView;
//
//    UIImageView *alarmImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 84, 81)];
//    alarmImgView.image = [UIImage imageNamed:@"Financialalarm"];
//    [SuspensionView addSubview:alarmImgView];
//
//    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(13, 46, 58, 30)];
//    [[SetGradient instance] setViewBackground:baseView fromColor:@"#ffa35a" toColor:@"#ff393a" fromCGPoint:CGPointMake(0, 0) toCGPoint:CGPointMake(0, 1)];
//    baseView.layer.masksToBounds = YES;
//    baseView.layer.cornerRadius = 15;
//    [SuspensionView addSubview:baseView];
//
//    UILabel *countdownLab = [[UILabel alloc]initWithFrame:CGRectMake(2, 0, 54, 30)];
//    countdownLab.textAlignment = NSTextAlignmentCenter;
//    countdownLab.text = @"浏览10秒可免费抽奖";
//    countdownLab.textColor = [UIColor whiteColor];
//    countdownLab.font = [UIFont boldSystemFontOfSize:9];
//    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         = 10;
//    dispatch_queue_t queue      = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    _Counttimer  = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//
//    // 每秒执行
//    dispatch_source_set_timer(_Counttimer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
//    dispatch_source_set_event_handler(_Counttimer, ^{
//
//        if (timeout <= 0)
//        {
//            //取消
//            dispatch_source_cancel(wSelf.Counttimer);
//            dispatch_async(dispatch_get_main_queue(), ^{
//                // 设置界面的按钮显示，根据自己需求设置
//                wSelf.countdownLab.text = @"立即抽奖";
//                wSelf.SuspensionView.userInteractionEnabled = YES;
//            });
//        }
//        else
//        {
//            NSString *strTime = [NSString stringWithFormat:@"浏览%i秒可免费抽奖", timeout];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                wSelf.countdownLab.text = strTime;
//            });
//            timeout--;
//        }
//    });
//    //恢复
//    dispatch_resume(_Counttimer);
//}
#pragma mark - 立即领取
- (void)Gesture{
    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:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    NSString *url1 = [NSString stringWithFormat:@"%@drawservice/plusdraw",[NetworkConfig ipCoinsConfig]];
//    NSString *url1 = [NSString stringWithFormat:@"%@scoreService/drawservice/plusdraw",@"http://172.16.10.215:8080/"];
    NSDictionary *params1 = @{
        @"uid":@([getPeopleID PeopleID]),
        @"telphone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"eventype":@(10011),
        @"frommodel":@"2"
    };
    typeof(self) wSelf = self;
    [KKLoadingAnimationView show];
    [NetworkRequest Post11:url1 Params:params1 Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"code"]];
            NSString *des = [NSString stringWithFormat:@"%@",objc[@"des"]];
            if ([state isEqualToString:@"0"]) {
                //抽奖页面
                [wSelf.SuspensionView removeFromSuperview];
                [[clickEvent instance] clickEventRooterVC:wSelf Content:@"mineLucky" menuName:@"金币抽奖"];
            }else{
                [XYProgressHUD showMessage:des];
            }
        }
    } Failure:^(NSError *error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
    }];
}
//判断是否同一天
- (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];
}
//- (void)dealloc{
//    if (_Counttimer) {
//        dispatch_source_cancel(_Counttimer);
//        _Counttimer = nil;
//    }
//}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0xe42431];
    [self.view addSubview:navView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 50, 25);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateHighlighted];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    

    //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.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}
#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:页面加载完成");
}

// 页面加载失败时调用
- (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);
}

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://"] || [url.absoluteString containsString:@"downloadApp"]) {
//            [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:@"shareUrl"]){
        self.shareDic = message.body;
        if ([self.shareDic[@"type"] isEqualToString:@"好友"]) {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
        }else if([self.shareDic[@"type"] isEqualToString:@"朋友圈"]){
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
    }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:@""];
    }else if ([message.name isEqualToString:@"getBack"]){
        [self.tabBarController.navigationController popToRootViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"h5GetAppInfo"]){
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        app_Version = [app_Version stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSDictionary* dic = @{
            @"versionCode":app_Version,
            @"system":@"iOS",
            @"appName":@"kklife",
        };
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getAppInfo(%@)",jsonStr];
       [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                     NSLog(@"value图片: %@ error: %@", response, error);
       }];
    }
}
-(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 - event response
- (void)backClick:(UIButton *)sender {
    [self.tabBarController.navigationController popViewControllerAnimated:YES];
//    if (self.webView.canGoBack==YES) {
//        [self.webView goBack];
//    }else{
//        if (self.fromHome) {
//            [self.navigationController popViewControllerAnimated:YES];
//        }else{
//            [self.tabBarController.navigationController popViewControllerAnimated:YES];
//        }
//
//
//    }
}
- (void)taskBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#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;
}
#pragma mark - getters and setters
- (void)setFromHome:(BOOL)fromHome
{
    _fromHome = fromHome;
    
    if (fromHome) {
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(cl_kNavigationBarHeight);
            make.left.right.offset(0);
            make.bottom.offset(0);
        }];
    }
}
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        config.allowsPictureInPictureMediaPlayback = YES;
        
        //自定义的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:@"shareUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"getBack"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"h5GetAppInfo"];
        
        config.userContentController = wkUController;
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, (ScreenHeight - cl_kNavigationBarHeight - cl_kTabBarHeight)) configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.scrollView.bounces = false;
 
    }
    return _webView;
}
- (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.webView evaluateJavaScript:@"finGetImg('null')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value图片: %@ error: %@", response, error);
    }];
}
#pragma mark - 分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }

    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareDic[@"title"] descr:self.shareDic[@"describe"] thumImage:self.shareDic[@"imageUrl"]];
        //设置网页地址
    NSString *url = self.shareDic[@"url"];
    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);
            }
        }
        
    }];
}
- (void)dealloc {
    //移除定时器
    if (_Counttimer) {
        dispatch_source_cancel(_Counttimer);
        _Counttimer = nil; // OK
    }
}
//#pragma mark - 获取抽奖状态
//- (void)DrawStatus{
//    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:@"%@",vArr[i]];
//        }else{
//            version = [version stringByAppendingFormat:@"%@",vArr[i]];
//        }
//    }
//    NSString *url1 = [NSString stringWithFormat:@"%@drawservice/drawStatus",[NetworkConfig ipCoinsConfig]];
////    NSString *url1 = [NSString stringWithFormat:@"%@scoreService/drawservice/drawStatus",@"http://172.16.10.215:8080/"];
//    NSDictionary *params1 = @{
//        @"uid":@([getPeopleID PeopleID]),
//        @"eventype":@(10011),
//    };
//    typeof(self) wSelf = self;
//    [NetworkRequest Post11:url1 Params:params1 Success:^(id _Nonnull objc) {
//        if ([objc isKindOfClass:[NSDictionary class]]) {
//           NSString *state = [NSString stringWithFormat:@"%@",objc[@"code"]];
//           if ([wSelf.ID isEqualToString:@"cunqianguan_banner"]) {
//               if ([state isEqualToString:@"1026"]) {
//                   //倒计时
//                    [wSelf SuspensionCountdown];
//               }
//           }
//
//       }
//    } Failure:^(NSError *error) {
//        NSLog(@"error:%@",error);
//    }];
//}
@end
