//
//  WebVC.m
//  Open
//
//  Created by 雷俊博 on 2019/8/18.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "WebVC.h"
#import <WebKit/WebKit.h>
#import <Masonry.h>
#import "WeakWebViewScriptMessageDelegate.h"
#import "UIView+frameAdjust.h"
#import "UIImage+Custom.h"
#import "Constants.h"

#import "MyPrizeListVC.h"
#import "CoinsDetailListVC.h"

#import "SDImageCache.h"
#import "PrizeInfoCommitSuccessAlertView.h"
#import "CTAPIBaseManager.h"

#import "ShareViewController.h"
#import "OnFootEarnCoinsViewController.h"

//个数统计
#import "GTCountSDK.h"
#import "UINavigationBar+handle.h"

//腾讯广点通
#import <GDTRewardVideoAd.h>
#import <GDTSDKConfig.h>

#import <WXApi.h>

#import "CTToast.h"
#import "UINavigationBar+handle.h"
#import "SaveProductListController.h"
#import "HomeViewController.h"
#import "MyAssetsController.h"
#import "SaveTabBarController.h"
#import "LoginVC.h"

#import "BCNewActivityShareView.h"

#import "SaveProductListController.h"
#import "KKCLFundViewController.h"


#import "NewsViewController.h"
#import "CoinsCenterViewController.h"

#import "KKSaveBankRedPackageOPenedView.h"
#import "UIDocumentPickerViewController+Swizzling.h"


//免费果园
#import "MyFruitViewController.h"
//摇钱树
//#import <YXLaunchAds/YXLaunchAds.h>
//小满
#import <BXMediaSDK/BXMediaMaterialManager.h>
#import "KKActivityViewController.h"
#import "HeadLineViewController.h"

#import "Tools.h"

#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>
#import <AVFoundation/AVFoundation.h>
#import "UIColor+LVAdd.h"
#import "LivenessViewController.h"
#import "FaceImageModel.h"
//充话费
//static NSString *redirectScheme = @"local.weface.com.cn";
static NSString *redirectScheme = @"nginx.weface.com.cn";

@interface WebVC () <CNContactPickerDelegate>

@end

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

@interface WebVC ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate,GDTRewardedVideoAdDelegate,UIScrollViewDelegate,AVCaptureMetadataOutputObjectsDelegate,SCNavigationControllerDelegate,passImagesDelegate>
{
    UIView *m_popView;
    NSString*type;
    
    BOOL loadFinish;
    
    BOOL loadOk;
    
    BOOL loadSuccess;
    
}

@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic,strong) UIImagePickerController *imagePicker;

//腾讯
@property (nonatomic, strong) GDTRewardVideoAd *rewardVideoAd;

@property (nonatomic, strong)UILabel *lb_content;

@property (nonatomic,assign)BOOL isPause;

@property (nonatomic, assign)BOOL isDestoryTimer;

@property (strong, nonatomic)  dispatch_source_t timer;

@property (strong, nonatomic)  dispatch_source_t Counttimer;

@property (nonatomic, strong)UIButton *taskBtn;

@property (nonatomic,strong) UIProgressView *progressView;

@property (nonatomic, strong)UILabel *countdownLab;
@property (nonatomic, copy) NSString * endPayRedirectURL;
//@property (nonatomic, strong)WKUserContentController *userContentController;
//显示图层
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *layer;
//捕捉会话
@property(nonatomic,strong)AVCaptureSession *session;
//辅助区域框
@property(nonatomic,strong)UIView * cyanView;
@property(nonatomic,strong)UIButton * lightBtn;
//状态栏
@property(nonatomic,strong)UIView *phoneNavView;
@property(nonatomic,strong)UIView *normalNavView;

@property(nonatomic,strong)NSString *bx_name;
@property(nonatomic,strong)NSString *bx_id;
@property(nonatomic,strong)NSString *bx_nation;
@property(nonatomic,strong)NSString *bx_address;

@property(nonatomic,strong)NSString *bx_sign;
@property(nonatomic,strong)NSString *bx_valid;

@property(nonatomic)bool bx_ok;
@property(nonatomic)Boolean iosHide;

@property(nonatomic)NSString *iosHideTopColor;
@end

@implementation WebVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    [self cleanCacheAndCookie];
    
    //UIProgressView
//    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 0.5)];
//    self.progressView.progressViewStyle=UIProgressViewStyleBar;
//    self.progressView.backgroundColor = [UIColor whiteColor];
//    self.progressView.tintColor = [UIColor colorWithRed:233/255.0 green:71/255.0 blue:58/255.0 alpha:1];
//    [self.view addSubview:self.progressView];
//    [self.view bringSubviewToFront:self.progressView];
    
    
        //self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        //self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    if ([self.title isEqualToString:@"金币抽奖"]) {

        [self navConfig];
        
        [self setupUI];
    }else if ([self.title isEqualToString:@"基金活动"]) {
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setTitle:@"基金活动" forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [rightBtn addTarget:self action:@selector(watchClick:) forControlEvents:UIControlEventTouchUpInside];
        rightBtn.frame = CGRectMake(0, 0, 60, 44);
        UIBarButtonItem* rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
        
        self.navigationItem.rightBarButtonItem = rightItem;
    }else if ([self.title isEqualToString:@"话费充值"]) {
        [self PhonenavConfig];
    }
    
    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
       }
    
    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button_2.frame = CGRectMake(-30, 0, 20, 5);
    button_2.titleLabel.textAlignment =NSTextAlignmentLeft;
    //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
    if ([self.title isEqualToString:@"存钱罐活动"] || [self.title isEqualToString:@"存钱罐拉新"]) {
        [button_2 setImage:[UIImage imageNamed:@"fuliBack"] forState:UIControlStateNormal];
        [button_2 setTitle:@"返回" forState:UIControlStateNormal];
        [button_2 setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
        [button_2 layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:8];
    }else {
        [button_2 setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    }
   
    //    [button_2 setBackgroundColor:[UIColor redColor]];
    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
    [button_2 addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];
    
    self.navigationItem.leftBarButtonItem = backButtonItem_2;
            
    
    if (self.showTaskView) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    
    //悬浮倒计时闹钟
    if (self.TaskModel.clickeventFlag == 601 && self.TaskModel.taskStatus == 305) {
        [self SuspensionCountdown];
    }
    if ([self.title isEqualToString:@"众邦银行"] || [self.title isEqualToString:@"锡商银行"]) {
        [self kefuUI];
    }
}


- (void)handleNavigationTransition:(UIGestureRecognizer *)gap{
       NSLog(@"用户左滑了手势");
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }else{
        NSLog(@"此时退出当前页面");
        //[self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 客服视图
- (void)kefuUI{
    UIButton *kefuBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 71, ScreenHeight -  215, 71, 39)];
    [self.view bringSubviewToFront:kefuBtn];
    [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];
}
#pragma mark -客服
- (void)kefu{
    [[clickEvent instance] clickEventRooterVC:self Content:@"weChatService" menuName:@"客服"];
}
#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);
}


- (void)setupUI
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"shareLastTime2"];
    
    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }
    
    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"shareLastTime2"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    UIWindow* keyWindow = [UIApplication sharedApplication].keyWindow;
    UIImageView *popView = [[UIImageView alloc]init];
    popView.image = [UIImage imageNamed:@"PopMenuView_bg"];
    [keyWindow addSubview:popView];
    UILabel *lb_message = [[UILabel alloc]init];
    lb_message.text = @"分享赚金币";
    lb_message.textColor = [UIColor whiteColor];
    lb_message.font = [UIFont systemFontOfSize:12];
    lb_message.textAlignment = NSTextAlignmentCenter;
    [popView addSubview:lb_message];
    
    [lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(2);
        make.right.offset(-2);
        make.top.offset(8);
        
    }];
    
    [popView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kNavigationBarHeight - 10);
        make.right.offset(-10);
    }];
    
    m_popView = popView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (popView) {
            [popView removeFromSuperview];
             self->m_popView = nil;
        }
        
    });
    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if ([self.title isEqualToString:@"金币抽奖"]) {
        [GTCountSDK trackCountEvent:@"home_jinbichoujiang" withArgs:@{}];
        [GDTSDKConfig registerAppId:@"1111094678"];
       [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0x1b5eea] image:nil isOpaque:YES];//颜色
        [self.navigationController.navigationBar navBarBottomLineHidden:YES];
        //[self.navigationController setNavigationBarHidden:YES animated:animated];
         [self.navigationController setNavigationBarHidden:YES];
        //self.navigationController.navigationBar.translucent = NO;
    }else if ([self.title isEqualToString:@"快递"]){
        [self.navigationController setNavigationBarHidden:NO];
        self.navigationController.navigationBar.barTintColor = K_MainColor;
        [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            self.navigationController.navigationBar.barTintColor = K_MainColor;
            //         [self.navigationController.navigationBar setBackgroundImage:[self convertViewToImage:[self getNavBackView]] forBarMetrics:UIBarMetricsDefault];
            
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            //         [self.navigationController.navigationBar setBackgroundImage:[self convertViewToImage:[self getNavBackView]] forBarMetrics:UIBarMetricsDefault];
        }];
    }else if ([self.title isEqualToString:@"养老机构"] || [self.title isEqualToString:@"云闪付"] || [self.title isEqualToString:@"教学视频"]){
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }else if ([self.title isEqualToString:@"存钱罐活动"]) {
        [self.navigationController setNavigationBarHidden:NO];
        UIButton* titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setTitle:@"存钱罐活动" forState:UIControlStateNormal];
        [titleBtn setImage:[UIImage imageNamed:@"save_fire"] forState:UIControlStateNormal];
        [titleBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
        [titleBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:10];
        self.navigationItem.titleView = titleBtn;
        [self.navigationController.navigationBar navBarBackGroundColor:[UIColor whiteColor] image:nil isOpaque:YES];
        UIButton* shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        shareBtn.frame = CGRectMake(0, 0, 80, 44);
        [shareBtn setImage:[UIImage imageNamed:@"share_icon"] forState:UIControlStateNormal];
        [shareBtn setTitle:@"   " forState:UIControlStateNormal];
        [shareBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:25];
        [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* rightItem = [[UIBarButtonItem alloc]initWithCustomView:shareBtn];
        self.navigationItem.rightBarButtonItem = rightItem;
        
    }else if ([self.title isEqualToString:@"存钱罐拉新"]){
        [self.navigationController setNavigationBarHidden:NO];
        
        UIButton* titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setTitle:@"存钱罐拉新" forState:UIControlStateNormal];
        [titleBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
        [titleBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:10];
        
        self.navigationItem.titleView = titleBtn;
        
        [self.navigationController.navigationBar navBarBackGroundColor:[UIColor whiteColor] image:nil isOpaque:YES];
    }else if ([self.title isEqualToString:@"0元领"]) {
        [GTCountSDK trackCountEvent:@"home_shihuibaoxian" withArgs:@{}];
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }else if ([self.title isEqualToString:@"找工作"]) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }else if([self.fromName isEqualToString:@"银行存款"]){
        [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0xe42431] image:nil isOpaque:YES];//颜色
        [self.navigationController setNavigationBarHidden:NO animated:animated];
    }else if ([self.title isEqualToString:@"话费充值"]) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }else if ([self.title isEqualToString:@"养老钱包"]){
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(cl_kStatusBarHeight);
            //make.centerX.equalTo(self.view);
            //make.width.offset(0);
            make.height.offset(ScreenHeight);
        }];
        if(self.normalNavView!=nil){
            self.normalNavView.hidden=YES;
        }
        if(self.phoneNavView!=nil){
            self.phoneNavView.hidden=YES;
        }
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, 0 , ScreenWidth, cl_kStatusBarHeight)];
        if(self.iosHideTopColor==nil){
            self.iosHideTopColor=@"#000000";
        }
        view.backgroundColor = [UIColor colorWithHexString:self.iosHideTopColor];
        [self.view addSubview:view];
        // handleNavigationTransition:为系统私有API,即系统自带侧滑手势的回调方法，我们在自己的手势上直接用它的回调方法
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleNavigationTransition:)];
        panGesture.delegate = self; // 设置手势代理，拦截手势触发
        [self.view addGestureRecognizer:panGesture];
    }else{
        if(self.title!=nil&&self.title.length>0){
            NSLog(@"web_title:%@",self.title);
            if([self.title containsString:@"百信"]){
                [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0x147EF6] image:nil isOpaque:YES];//颜色
                [self.navigationController setNavigationBarHidden:NO animated:animated];
            }else{
                if(!_iosHide){
                    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0x147EF6] image:nil isOpaque:YES];//颜色
                    [self.navigationController setNavigationBarHidden:NO animated:animated];
                }else{
                    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.view).offset(cl_kStatusBarHeight);
                        //make.centerX.equalTo(self.view);
                        //make.width.offset(0);
                        make.height.offset(ScreenHeight);
                    }];
                    if(self.normalNavView!=nil){
                        self.normalNavView.hidden=YES;
                    }
                    if(self.phoneNavView!=nil){
                        self.phoneNavView.hidden=YES;
                    }
                    [self.navigationController setNavigationBarHidden:YES animated:YES];
                    UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, 0 , ScreenWidth, cl_kStatusBarHeight)];
                    if(self.iosHideTopColor==nil){
                        self.iosHideTopColor=@"#000000";
                    }
                    view.backgroundColor = [UIColor colorWithHexString:self.iosHideTopColor];
                    [self.view addSubview:view];
                   
                }
                
            }
        }
        
    }
    NSString *jsString = @"backToApp()";
    [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        NSLog(@"加载页面%@",error);
    }];
    
    
    if ([self.from isEqualToString:@"newsList"]) {
        //禁止手势返回
           id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
           UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
           [self.view addGestureRecognizer:pan];
    }
    
    
}

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

     self.navigationController.navigationBar.translucent = YES;
    
    if (m_popView) {
        [m_popView removeFromSuperview];
        m_popView = nil;
    }
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if ([self.title isEqualToString:@"金币抽奖"]) {
        [JANALYTICSService startLogPageView:@"金币抽奖"];
        [MobClick beginLogPageView:@"金币抽奖"];
    }
  
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    if ([self.title isEqualToString:@"金币抽奖"]) {
        [JANALYTICSService stopLogPageView:@"金币抽奖"];
        [MobClick endLogPageView:@"金币抽奖"];
    }

}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if ([self.title isEqualToString:@"找工作"]) {
        
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.top.offset(cl_kStatusBarHeight);
            
            make.bottom.equalTo(self.view);
        }];
    }else{
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.top.offset(cl_kNavigationBarHeight);

            make.bottom.equalTo(self.view);
        }];
    }
   
    
}

- (void)dealloc
{
   // [self.userContentController removeScriptMessageHandlerForName:@"toNews()"];
    NSLog(@"WebVC:%@销毁了",self.title);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    if (self.showTaskView) {
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
        
        
        NSLog(@"页面已销毁");
        
        if (_timer) {
            if (self.isDestoryTimer == NO) {
                dispatch_source_cancel(_timer);
                self.isDestoryTimer = YES;
            }
            
        }
        _timer =nil;// OK
    }

    [self cleanCacheAndCookie];
    
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    
     [self cleanCacheAndCookie];
    
    self.webView.navigationDelegate = nil;
    self.webView.UIDelegate = nil;
    self.webView.scrollView.delegate = nil;
    
    //移除定时器
    if (_Counttimer) {
        dispatch_source_cancel(_Counttimer);
        _Counttimer = nil; // OK
    }
}
- (void)PhonenavConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0x1b5eea];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel* lb_title = [UILabel new];
    lb_title.text = self.title;
    lb_title.font = [UIFont boldSystemFontOfSize:17];
    lb_title.textAlignment = NSTextAlignmentCenter;
    lb_title.textColor = [UIColor whiteColor];
    [navView addSubview:backBtn];
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.centerX.equalTo(navView);
        make.height.offset(44);
    }];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"充值历史" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    [rightBtn addTarget:self action:@selector(TopupHistoryClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.right.offset(-10);
        make.height.offset(44);
    }];
    [self.view addSubview:navView];
    self.phoneNavView=navView;
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0x1b5eea];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel* lb_title = [UILabel new];
    lb_title.text = self.title;
    lb_title.font = [UIFont boldSystemFontOfSize:17];
    lb_title.textAlignment = NSTextAlignmentCenter;
    lb_title.textColor = [UIColor whiteColor];
    [navView addSubview:backBtn];
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.centerX.equalTo(navView);
        make.height.offset(44);
    }];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"分享" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightBtn setImage:[UIImage imageNamed:@"prize_share"] forState:UIControlStateNormal];
    [rightBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    [rightBtn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.right.offset(-10);
        make.height.offset(44);
    }];
    [self.view addSubview:navView];
    self.normalNavView=navView;
}


#pragma mark - 通知绑定方法

///监听应用退到后台
 - (void)didEnterBackground
{
    if (!self.showTaskView) {
        return;
    }
   
    [self pauseTimer];
}
///恢复旋转
- (void)didBecomeActive
{
    if (!self.showTaskView) {
        return;
    }
    
    [self resumeTimer];
}


#pragma mark - 定时器处理
-(void) pauseTimer{
    
    
    
    if (self.isPause) {
        return;
    }
    
    self.isPause = YES;
    
    if(self.timer){
        dispatch_suspend(_timer);
    }
}
-(void) resumeTimer{
    
    
    
    if (self.isPause == NO) {
        return;
    }
    
    self.isPause = NO;
    
    if(self.timer){
        dispatch_resume(_timer);
    }
}
-(void) stopTimer{
    if(self.timer){
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}
#pragma mark - 再领一次红包
//兑换码接口
- (void)makePackageAgainWithSysorderNo:(NSString *)sysorderNo
{
    //[KKLoadingAnimationView show];
    
    NSString *url = [NSString stringWithFormat:@"%@score/excharge",CoinsBaseUrl];
    
    NSDictionary *dic = @{
                          @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"sysorderNo":[Tools isBlankString:sysorderNo] ? @"" : sysorderNo,
                          @"userId":[NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]],
                          @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]]
                          };
    
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&kk#d12",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
       //[KKLoadingAnimationView dismiss];
        
        if (error) {
            [self alertShowMessage:@"无网络"];
            return ;
        }
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {

            NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            NSString *des = [NSString stringWithFormat:@"%@",responseObject[@"des"]];
            if ([code isEqualToString:@"0"]) {
                
                NSString *moneyDetail = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"moneyDetail"]];
                [KKSaveBankRedPackageOPenedView showAlertViewWithVC:self Title:@"“随机现金红包”" number:moneyDetail message:@"浏览“存钱罐”奖励" btnTitle:@"立即领取" block:^{
                    
                }];
                
                return;
                
            }else{
                [self alertShowMessage:des];
            }
            
        }else{
            [self alertShowMessage:@"服务器异常"];
        }
        
    }];
}


#pragma mark - 任务得金币接口
- (void)increaseScoreWithType:(NSString *)type
{
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone":[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":type,
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          
                          @"fromModel":@"2"
                          };
    
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
//    WeakSelf
   
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            if (code.integerValue == 1006) {
                
                
                if (self.block) {
                    self.block(YES);
                }
                
                //[weakSelf loadData];
                

                NSString*score = [NSString stringWithFormat:@"+%@",responseObject[@"result"][@"score"]];
                
                
                //(ScreenHeight - 288) / 2 - 20
                //299, 288
//                WeakSelf
                [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self Number:score block:^(CTShareType type) {
                    
                    
                }];
                
                
            }
        }
       
        
    }];
}



#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:页面开始加载");
    //self.progressView.hidden = NO;
    //[self.view bringSubviewToFront:self.progressView];
    [KKLoadingAnimationView show];
    if (!([self.title isEqualToString:@"0元购"] || [self.title isEqualToString:@"快递"])) {
        //[SVProgressHUD shows];
    }
    
    
}
//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:内容开始返回");
    
   
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //self.progressView.hidden = YES;
    [KKLoadingAnimationView dismiss];
    NSLog(@"WebVC:页面加载完成");
    if (!loadSuccess) {
        loadSuccess = YES;
        if (self.showTaskView) {
            if (self.TaskModel.taskStatus == 305) {
                [self addTaskView];
            }
        }
    }

    
//    NSString *injectionJSString = @"var script = document.createElement('meta');"   "script.name = 'viewport';"    "script.content=\"width=device-width, user-scalable=no\";"    "document.getElementsByTagName('head')[0].appendChild(script);";
//    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    
    if (!([self.title isEqualToString:@"0元购"] || [self.title isEqualToString:@"快递"])) {
         //[SVProgressHUD doneShow];
           //[SVProgressHUD dismiss];
    }
    
    if ([self.title isEqualToString:@"新闻资讯"]) {
        NSString*jsStr = @"javascript:function setTop(){document.querySelector('.wrap-header').style.display=\"none\";document.querySelector(\".container\").style.marginTop=\"-30px\";document.querySelector(\".article-title\").style.fontSize=\"22px\";document.querySelector(\".sub-line\").style.marginBottom='5px';document.querySelector(\".article-title\").style.marginBottom='5px';document.querySelector(\"._7lscudbyhf5\").firstChild.style.height='0';document.querySelector(\"._7lscudbyhf5\").firstChild.style.overflow=\"hidden\";}setTop();";
        [webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable htmlStr, NSError * _Nullable error) {
            
        }];
    }
    
    
    if ([self.title isEqualToString:@"转账攻略"] && self.infoModel.cardList.count > 0) {
        BCCardListModel* cardModel = self.infoModel.cardList[0];
        NSString*name = nil;
        if (self.infoModel.realName) {
            for (int i = 0; i < (self.infoModel.realName.length - 1); i++) {
                if ( i == 0) {
                    name = @"*";
                }else{
                    name = [NSString stringWithFormat:@"%@*",name];
                }
                
            }
            
            name = [NSString stringWithFormat:@"%@%@",name,[self.infoModel.realName substringFromIndex:self.infoModel.realName.length - 1]];
        }else{
            name = @"";
        }
        
        NSDictionary* dic = @{
            @"bankName":cardModel.bankCardName ? cardModel.bankCardName :@"",
            @"bankNameNumber":cardModel.lastFourCardNo ? cardModel.lastFourCardNo :@"",
            @"myBankUrl":cardModel.bankLogoUrl ? cardModel.bankLogoUrl :@"",
            @"eleBankName":self.infoModel.orgName ? self.infoModel.orgName :@"",
            @"eleBankUrl":self.infoModel.orgLogo ? self.infoModel.orgLogo :@"",
            @"eleBankNumber":self.infoModel.bankElecAccountNum ? self.infoModel.bankElecAccountNum :@"",
            @"name":name,
        };
        
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
       // jsonStr = [SecurityUtil encodeBase64String:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getBcInfo(%@)",jsonStr];
       
       
       [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                     NSLog(@"value图片: %@ error: %@", response, error);
               }];
    }
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
         NSString *inputValue = [NSString stringWithFormat:@"YD_getMessage('%@,%@,%@')",[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],[NSNumber numberWithInteger:[getPeopleID PeopleID]],[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        
        
        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                      NSLog(@"value图片: %@ error: %@", response, error);
                }];
        
    }
    
   
  
   
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"])
        {
            NSString *inputValue1 = [NSString stringWithFormat:@"AD_getMessage('%@,%@,%@')",[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue,[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
            [self.webView evaluateJavaScript:inputValue1 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                   NSLog(@"value图片: %@ error: %@", response, error);
             }];
        }
    
   
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        NSString *inputValue1 = [NSString stringWithFormat:@"NbJsToDsInfo('%@,%@')",[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],@"200"];
        [self.webView evaluateJavaScript:inputValue1 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
               NSLog(@"value图片: %@ error: %@", response, error);
         }];
        
        
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
        currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
        
        
        
        NSDictionary* dic = @{
            @"userId":@([getPeopleID PeopleID]),
            @"phone": [getPeopleID PeopleIphoneNmber],
            @"versionCode":currentVersion,
            @"system":@"iOS",
            @"head":[getPeopleID PeoplePhoto].absoluteString ? [getPeopleID PeoplePhoto].absoluteString :@""
        };
        
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
       // jsonStr = [SecurityUtil encodeBase64String:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getAppMsg(%@)",jsonStr];
       
       
       [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                     NSLog(@"value图片: %@ error: %@", response, error);
        }];
        
        if ([self.title isEqualToString:@"领钱答疑群"]) {
            
            if (self.fromSuccess) {
                NSDictionary* dic2 = @{
                    @"telephone": [getPeopleID PeopleIphoneNmber],
                    @"fromapps":@"kksh",
                    @"provincename":self.provincename ?self.provincename :@"",
                    @"cityname":self.cityname ? self.cityname :@"",
                    @"countryname":self.countryname ? self.countryname : @"",
                    @"townname":@"",
                    @"verytype":@(self.verytype)
                };
                
                NSString*jsonStr2 = [self dictionaryToJson:dic2];
                jsonStr2 = [self noWhiteSpaceString:jsonStr2];
               // jsonStr = [SecurityUtil encodeBase64String:jsonStr];
                NSString *inputValue2 = [NSString stringWithFormat:@"getAppInfo(%@)",jsonStr2];
               
               
               [self.webView evaluateJavaScript:inputValue2 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                             NSLog(@"value图片: %@ error: %@", response, error);
                }];
            }
            
            
        }
        
    }
    
    if ([self.title isEqualToString:@"找工作"]){
        
        if (loadOk) {
            return;
        }
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
        currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
        
        NSString *province = [Tools isBlankString:[UserDefault objectForKey:@"locationProvince"]] ? @"" : [UserDefault objectForKey:@"locationProvince"];
        NSString *city = [Tools isBlankString:[UserDefault objectForKey:@"locationCity"]] ? @"" : [UserDefault objectForKey:@"locationCity"];
        NSString *county = [Tools isBlankString:[UserDefault objectForKey:@"locationCounty"]] ? @"" : [UserDefault objectForKey:@"locationCounty"];
        
        NSDictionary* dic = @{
            @"userid":@([getPeopleID PeopleID]),
            @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
            @"fromapp":@"kksh",
            @"version":currentVersion,
            @"frommodel":@"2",
            @"headerUrl":[getPeopleID PeoplePhoto].absoluteString ? [getPeopleID PeoplePhoto].absoluteString :@"",
            @"userName": [getPeopleID Peopletitle] ? [getPeopleID Peopletitle] :  @"",
            @"localCountyName":county,
            @"localCityName":city,
            @"localProvinceName":province
        };
        
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
       // jsonStr = [SecurityUtil encodeBase64String:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getMsgFromApp(%@)",jsonStr];

       [webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                     NSLog(@"value图片: %@ error: %@", response, error);
        }];
        
    }
    if ([self.title isEqualToString:@"金币兑换"]){

        if (loadOk) {
            return;
        }
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
        currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSDictionary* dic = @{
            @"fromapp":@"kksh",
            @"userid":@([getPeopleID PeopleID]),
            @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
            @"version":currentVersion,
            @"frommodel":@"2",
        };
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getMsgFromApp(%@)",jsonStr];

        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//                 NSLog(@"value图片: %@ error: %@", response, error);
         }];
    }
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
        currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];

        NSString *locationCoordinate = [UserDefault objectForKey:@"locationCoordinate"];
        NSArray  *locationArray = nil;
        if (locationCoordinate) {
           locationArray =  [locationCoordinate componentsSeparatedByString:@","];
        }
        NSString *clientLng = locationArray ?locationArray[0] :@"121.48";
        NSString *clientLat = locationArray ?locationArray[1] :@"31.22";
        NSDictionary* dic = @{
            @"userid":@([getPeopleID PeopleID]),
            @"lng":clientLng,
            @"lat":clientLat,
            @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
            @"version":currentVersion,
            @"fromapp":@"kksh",
            @"frommodel":@"ios",
        };
        NSString*jsonStr = [self dictionaryToJson:dic];
        jsonStr = [self noWhiteSpaceString:jsonStr];
        NSString *inputValue = [NSString stringWithFormat:@"getInfoFromApp(%@)",jsonStr];
        //typeof(self) wSelf = self;
        [webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                NSLog(@"getInfoFromApp: %@ error: %@", response, error);

         }];
    }
    
    loadOk = YES;
  
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"WebVC:页面加载失败");
    //self.progressView.hidden = YES;
    [KKLoadingAnimationView dismiss];
     if (!([self.title isEqualToString:@"0元购"] || [self.title isEqualToString:@"快递"])) {
           // [SVProgressHUD doneShow];
             // [SVProgressHUD dismiss];
       }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
//        self.progressView.progress = self.webView.estimatedProgress;
//        if (self.progressView.progress == 1) {
//            self.progressView.hidden = YES;
//        }
        [KKLoadingAnimationView dismiss];
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
//接收到服务器跳转请求之后调用
- (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"]) {
          
         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;
                 }
         }else if ([url.scheme isEqualToString:@"bxbank"]){
             //[self openBxBank:url];
             if (@available(iOS 10.0, *)) {
                 [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:nil];
             } else {
                 [[UIApplication sharedApplication] openURL:url];
             }

             decisionHandler(WKNavigationActionPolicyCancel);
             return;
         }
       }
    if ([scheme isEqualToString:@"kankan"]) {
        CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
        vc.title = @"金币中心";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([self.title isEqualToString:@"话费充值"]||[self.title rangeOfString:@"电费"].location!=NSNotFound) {
        
    }
    if ([reqUrl hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![reqUrl hasSuffix:[NSString stringWithFormat:@"redirect_url=%@://",redirectScheme]]) {
           decisionHandler(WKNavigationActionPolicyCancel);
           NSString *redirectUrl = nil;
           if ([reqUrl containsString:@"redirect_url="]) {
               NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
               endPayRedirectURL =  [reqUrl substringFromIndex:redirectRange.location+redirectRange.length+1];
               redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=%@://",redirectScheme]];
              
           }else {
                redirectUrl = [reqUrl stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@://",redirectScheme]];
               
           }
           
          NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
                newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
          [newRequest setValue:[NSString stringWithFormat:@"%@://",redirectScheme] forHTTPHeaderField:@"Referer"];
          newRequest.URL = [NSURL URLWithString:redirectUrl];
          [webView loadRequest:newRequest];

         return;
       }
        //解决微信支付返回后白屏问题
        if ([navigationAction.request.URL.scheme containsString:redirectScheme] && [webView canGoBack]) {
            [webView goBack];
        }

    ////////////////************************* 处理请求
//    BOOL isAllow = [CZBInfoManager webView:webView decidePolicyForNavigationAction:navigationAction];
//    WKNavigationActionPolicy actionPolicy = isAllow ? WKNavigationActionPolicyAllow:WKNavigationActionPolicyCancel;
//    decisionHandler(actionPolicy);
    //允许跳转
    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 - WKScriptMessageHandler
//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    //用message.body获得JS传出的参数体
    //JS调用OC
    
    if([message.name isEqualToString:@"jsToOcNoPrams"]){
        
        self.navigationController.tabBarController.selectedIndex = 1;
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }else if ([message.name isEqualToString:@"toMyawardListVc"]){
        MyPrizeListVC *vc = [[MyPrizeListVC alloc]init];
        vc.title = @"我的奖品";
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }else if ([message.name isEqualToString:@"toMyWallet"]){
        CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
        vc.title = @"我的钱包";
        vc.type = ListVCTypeMyWallet;
                       
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([message.name isEqualToString:@"sharePrize"]){
        
        [PrizeInfoCommitSuccessAlertView showSuccessViewWithNumber:@"200" block:^(CTShareType type) {
        if (type == CTShareTypeWX) {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
        }else if (type == CTShareTypeFriend){
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
           }];
        
        return;
    }else if ([message.name isEqualToString:@"toShare"]){
        
         BOOL isContainVC = NO;
        
        NSMutableArray *vcArr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
              
              for (UIViewController* vc in vcArr) {
                  if ([vc isKindOfClass:[ShareViewController class]]) {
                      [self.navigationController popToViewController:vc animated:YES];
                      isContainVC = YES;
                      break;

                  }
              }
        
        if (isContainVC) {
                   return;
               }
            
        
        ShareViewController *shareVC = [[ShareViewController alloc]init];
        shareVC.title = @"邀请好友";
        shareVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:shareVC animated:YES];
        
        [GTCountSDK trackCountEvent:@"mask_inviteFriendsCl" withArgs:@{}];
        
    }else if ([message.name isEqualToString:@"maskShare"]){
        [self share3WebPageToPlatformType:UMSocialPlatformType_WechatSession];
    }else if ([message.name isEqualToString:@"toStep"]){
        
        BOOL isContainVC = NO;
        
        NSMutableArray *vcArr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
                     
                     for (UIViewController* vc in vcArr) {
                         if ([vc isKindOfClass:[OnFootEarnCoinsViewController class]]) {
                             [self.navigationController popToViewController:vc animated:YES];
                             isContainVC = YES;
                             break;
                            
                         }
            }
        
        if (isContainVC) {
            return;
        }
        
        OnFootEarnCoinsViewController *vc = [[OnFootEarnCoinsViewController alloc]init];
        vc.title = @"走路赚金币";
        vc.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([message.name isEqualToString:@"getImg"]){
        type = message.body;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }else if ([message.name isEqualToString:@"getBack"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"getUserId"]){
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            NSString *inputValue = [NSString stringWithFormat:@"getUserId('%@')",[NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]]];
            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                   NSLog(@"value图片: %@ error: %@", response, error);
             }];
        }else{
            [self unLoginTap];
        }
    }else if ([message.name isEqualToString:@"getPhoneNumber"]){
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            NSString *inputValue = [NSString stringWithFormat:@"getPhoneNumber('%@')",[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];
            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                   NSLog(@"value图片: %@ error: %@", response, error);
             }];
        }else{
            [self unLoginTap];
        }
    }else if ([message.name isEqualToString:@"getVersionId"]){
        NSString *inputValue = [NSString stringWithFormat:@"getVersionId('%@')",[NSString stringWithFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]]];
        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
               NSLog(@"value图片: %@ error: %@", response, error);
         }];
    }else if ([message.name isEqualToString:@"isOpenInApp"]){//富民判断
        NSString *inputValue = [NSString stringWithFormat:@"isOpenInApp('%@')",@"fm_in_kksh"];
        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
               NSLog(@"value:isOpenInApp: %@ error: %@", response, error);
         }];
    }else if ([message.name isEqualToString:@"getLoginInfo"]){//获取登录信息
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            NSDictionary* dic = @{
                @"id":[NSString stringWithFormat:@"%d",[getPeopleID PeopleID]],
                @"unTel":[getPeopleID PeopleIphoneNmber],
                @"tel":[getPeopleID PeopleUnPhoneNmber],
                @"headUrl":[[getPeopleID PeoplePhoto] absoluteString],
                @"nickName":[getPeopleID Peopletitle]
            };
            NSString*json = [self dictionaryToJson:dic];
            json = [self noWhiteSpaceString:json];
            NSString *inputValue = [NSString stringWithFormat:@"appToJs('%@')",json];
            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                   NSLog(@"value图片: %@ error: %@", response, error);
             }];
        }else{
            [self unLoginTap];
        }
    }else if ([message.name isEqualToString:@"getPhoto"])
    {
        NSURL *photoUrl = [getPeopleID PeoplePhoto];
        NSString *inputValue = [NSString stringWithFormat:@"getPhoto('%@')",photoUrl.absoluteString];
        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
               NSLog(@"value图片: %@ error: %@", response, error);
         }];
    }else if ([message.name isEqualToString:@"fromPlatform"])
    {
        NSString *inputValue = [NSString stringWithFormat:@"fromPlatform('%@')",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
               NSLog(@"value图片: %@ error: %@", response, error);
         }];
    }else if ([message.name isEqualToString:@"shareMoneyPot"]){
        [self share4WebPageToPlatformType:UMSocialPlatformType_WechatSession];
    }else if ([message.name isEqualToString:@"backToHomePage"]){
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"showRewardVideoAd"]){
        self.rewardVideoAd = [[GDTRewardVideoAd alloc] initWithPlacementId:@"5081234635108553"];
        self.rewardVideoAd.delegate = self;
        //self.rewardVideoAd.videoMuted = NO; // 设置激励视频是否静音
        [self.rewardVideoAd loadAd];
    }else if ([message.name isEqualToString:@"showSaveQRAlertVC"]){
        NSString*urlString = message.body;
       
       [self showSaveQRAlertVC:urlString];
    }else if ([message.name isEqualToString:@"toPiggyBank"]) {
        
        NSArray *vcs = self.navigationController.viewControllers;
        if (vcs.count > 1) {
            UIViewController*vc = self.navigationController.viewControllers[vcs.count - 2];
            if ([vc isKindOfClass:[SaveProductListController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
            }else if ([vc isKindOfClass:[HomeViewController class]] || [vc isKindOfClass:[SearchCollectionViewController class]]) {
                
                //UITabBarController*tabVC = [self getTabVC];
                
//                [self judgeSaveAmountRequest];
                //[self jumpVC:tabVC];
                
                [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
            }
        }
        
        
    }else if ([message.name isEqualToString:@"shareBcWelfareUrl"]) {
        NSDictionary*dic = message.body;
        NSString*type = dic[@"type"];
        NSString*url = dic[@"url"];
        NSString*title = dic[@"title"];
        NSString*describe = dic[@"describe"];
        if ([type isEqualToString:@"好友"]) {
            [self share5WebPageToPlatformType:UMSocialPlatformType_WechatSession url:url title:title message:describe imageUrl:@""];
        }else if ([type isEqualToString:@"朋友圈"]) {
            [self share5WebPageToPlatformType:UMSocialPlatformType_WechatTimeLine url:url title:title message:describe imageUrl:@""];
        }
    }else if ([message.name isEqualToString:@"shareSmallProgram"]) {//分享小程序
        NSDictionary*dic = message.body;
        NSString*defaultUrl = dic[@"defaultUrl"];
        NSString*url = dic[@"url"];
        NSString*title = dic[@"title"];
        NSString*des = dic[@"des"];
        NSString *userName = dic[@"id"];
        NSString*path = dic[@"path"];
        [self shareMiniProgramToPlatformType:UMSocialPlatformType_WechatSession defaultUrl:defaultUrl url:url title:title message:des userName:userName path:path];
      
    }else if ([message.name isEqualToString:@"currencyActivity"]) {//通用活动分享
        NSDictionary*dic = message.body;
        [self shareCurrencyActivity:dic];
      
    }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];
        }
    }else if ([message.name isEqualToString:@"toMineGold"]) {
        CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
        vc.title = @"我的钱包";
        vc.type = ListVCTypeMyWallet;
                       
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([message.name isEqualToString:@"bcCopyBankNumber"]) {
        NSString*bankNo = message.body;
        
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        pab.string = bankNo;
        if (pab == nil) {
            [Tools showMessage:@"复制失败"];
        } else {
            [Tools showMessage:@"已复制"];
        }
    }else if ([message.name isEqualToString:@"bcToMS"]){
        NSArray *vcs = self.navigationController.viewControllers;
        if (vcs.count > 1) {
            UIViewController*vc = self.navigationController.viewControllers[vcs.count - 2];
            if ([vc isKindOfClass:[SaveProductListController class]]) {
                SaveProductListController* proVC = (SaveProductListController *)vc;
                proVC.showFunActivity = YES;
                proVC.orgId = message.body[@"orgId"];
                proVC.prdId = message.body[@"prdId"];
                [self.navigationController popToViewController:proVC animated:YES];
            }else if ([vc isKindOfClass:[HomeViewController class]] || [vc isKindOfClass:[SearchCollectionViewController class]]) {
                
                [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
            }
        }
        
    }else if ([message.name isEqualToString:@"MoneyCattle"]){
        NSArray *vcs = self.navigationController.viewControllers;
        if (vcs.count > 1) {
            UIViewController*vc = self.navigationController.viewControllers[vcs.count - 2];
            if ([vc isKindOfClass:[SaveProductListController class]]) {
                [self.navigationController popToViewController:vc animated:YES];
            }else if ([vc isKindOfClass:[HomeViewController class]] || [vc isKindOfClass:[SearchCollectionViewController class]]) {
                [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
            }
        }
    }else if ([message.name isEqualToString:@"NewsCattle"]){
        [self goToNewsVC];
    }else if ([message.name isEqualToString:@"foucsCattle"]){
        NSString*bankNo = message.body;
        
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        pab.string = bankNo;
        if (pab == nil) {
            [Tools showMessage:@"复制失败"];
        } else {
            [self openWechat];
            
            //[Tools showMessage:@"已复制"];
        }
       
    }else if ([message.name isEqualToString:@"toGoldCenter"]){
        
        CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
        vc.title = @"金币明细";
        vc.type = ListVCTypeCoinsDetail;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([message.name isEqualToString:@"lookJdDouble"]){
        //存钱罐
        [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
        
    }else if ([message.name isEqualToString:@"clickBackBtn"]){
        if ([self.webView canGoBack]) {
            [self.webView goBack];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else if ([message.name isEqualToString:@"toWorkVC"]){
        
        
        
    }else if ([message.name isEqualToString:@"toSmallProgram"]){
        NSString*path = message.body;
        NSArray *array = [path componentsSeparatedByString:@","];
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName =array[0];  //拉起的小程序的username
        if(array.count>1){
            launchMiniProgramReq.path = array[1];    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        }
        launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
        [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
            
        }];
    }else if ([message.name isEqualToString:@"cashCow"]){
        [self goToShakeMoneyTreeVC];//摇钱树
    }else if ([message.name isEqualToString:@"freeFruit"]){
        [self goToFreeFruitVC];//免费果园
    }else if ([message.name isEqualToString:@"shearingWool"]){
        [self goToShearingWoolVC];//剪羊毛
    }else if ([message.name isEqualToString:@"goToPhoneRedPackageVC"]){
        [self goToPhoneRedPackageVC];//5元话费劵
    }else if ([message.name isEqualToString:@"saveCurrentWeb"]){
        [self showSaveQRAlertVC2];
    }else if ([message.name isEqualToString:@"kkshHelper"]) {
        if ([message.body isKindOfClass:[NSString class]]) {
            NSString *type = message.body;
            if ([type isEqualToString:@"1026"]) {
                [self goToFreeJobVC];//找工作
            }
        }
    }else 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:@"h5BindWechat"]){
        if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
            [self unLoginTap];
            return;
        }
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
            NSLog(@">>>>>wx>>result:%@, error:%@",result,error);
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"微信授权失败!"];
                return;
            }
            UMSocialUserInfoResponse *resp = result;
            if(resp.uid ){
                if (!resp.name) {
                    resp.name =@"";
                }
                if (!resp.iconurl) {
                    resp.iconurl=@"";
                }
            }
            // 第三方平台SDK原始数据
            NSLog(@" originalResponse: %@", resp.originalResponse);
            
            NSDictionary *dic = @{
                                  @"iconurl":resp.iconurl ? resp.iconurl :@"",
                                  @"openid":resp.openid ? resp.openid : @"",
                                  @"uid":resp.uid ? resp.uid : @"",
                                  @"token":resp.accessToken ? resp.accessToken : @"",
                                  @"screenname":resp.name ? resp.name : @"",
                                  };
            NSString *url = [NSString stringWithFormat:@"%@scorepay/accountBind",CoinsBaseUrl];
            NSDictionary *dic2 = @{
                                  @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                  @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                                  @"accounttype":[NSNumber numberWithInt:1],
                                  @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                                  @"fromModel":@"2"
                                  };
            NSMutableDictionary *dic3 = [[NSMutableDictionary alloc]initWithDictionary:dic];
            [dic3 addEntriesFromDictionary:dic2];
            NSArray *result1 = [dic3.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
                return [obj1 compare:obj2]; //升序
            }];
            NSString *sign = nil;
            for (int i = 0; i < result1.count; i++) {
                NSString *key = result1[i];
                if (i==0) {
                    sign = [NSString stringWithFormat:@"%@=%@",key,dic3[key]];
                }else{
                    
                    sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic3[key]];
                }
            }
            sign = [NSString stringWithFormat:@"%@&weface9578",sign];
            NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic3];
            NSString *signString = [[MyMD5 md5:sign] lowercaseString];
            [params setObject:signString forKey:@"sign"];
            [params setObject:@"506" forKey:@"appIdType"];
            [params setObject:@"kklife" forKey:@"terminal"];
            NSString *username = dic3[@"screenname"];
            [params setObject:[username stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]] forKey:@"screenname"];
            [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                if (error) {
                    [SVProgressHUD showInfoWithStatus:@"无网络"];
                    return ;
                }
                if (responseObject) {
                    NSNumber *code = responseObject[@"code"];
                    //NSString *des = responseObject[@"des"];
                    if ([code isKindOfClass:[NSNumber class]]) {
                        if (code.integerValue == 0) {
                            NSDictionary* back = @{
                                @"isBind":@"200"
                            };
                            NSString*json = [self dictionaryToJson:back];
                            json = [self noWhiteSpaceString:json];
                            NSString *inputValue = [NSString stringWithFormat:@"h5BindWehat('%@')",json];
                            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                                   NSLog(@"webView_h5BindWehat: %@ error: %@", response, error);
                             }];
                        }else if (code.integerValue == 1019){
                             //[SVProgressHUD showInfoWithStatus:@"该微信号已绑定"];
                            NSDictionary* back = @{
                                @"isBind":@"201"
                            };
                            NSString*json = [self dictionaryToJson:back];
                            json = [self noWhiteSpaceString:json];
                            NSString *inputValue = [NSString stringWithFormat:@"h5BindWehat('%@')",json];
                            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                                   NSLog(@"webView_h5BindWehat: %@ error: %@", response, error);
                             }];
                        }else{
                            //[SVProgressHUD showInfoWithStatus:des];
                            NSDictionary* back = @{
                                @"isBind":@"202"
                            };
                            NSString*json = [self dictionaryToJson:back];
                            json = [self noWhiteSpaceString:json];
                            NSString *inputValue = [NSString stringWithFormat:@"h5BindWehat('%@')",json];
                            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                                   NSLog(@"webView_h5BindWehat: %@ error: %@", response, error);
                             }];
                        }
                    }else{
                        [SVProgressHUD showInfoWithStatus:@"服务器错误"];
                    }
                }
            }];
            
        }];
    }else if ([message.name isEqualToString:@"unionLogin"]){
        NSString *str = message.body;
        [[clickEvent instance]clickEventRooterVC:self getFederatedLoginRequestWithUrl:str menuName:@""];
    }else if ([message.name isEqualToString:@"InvokeToApp"]){
        NSString *str = message.body;
        [[clickEvent instance] clickEventRooterVC:self Content:str menuName:@""];
    }else if([message.name isEqualToString:@"getContactInfo"]){
        //[self alertShowMessage:@"测试通讯录"];
//        NSDictionary* dic = @{
//            @"number":@"17775005838",
//        };
//        NSString*jsonStr = [self dictionaryToJson:dic];
//        jsonStr = [self noWhiteSpaceString:jsonStr];
//        NSString *inputValue = [NSString stringWithFormat:@"getContactInfo('%@')",jsonStr];
//
//        [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//               NSLog(@"通讯录返回: %@ error: %@", response, error);
//         }];
        CNContactPickerViewController *_peoplePickVC=[[CNContactPickerViewController alloc] init];
        //_peoplePickVC.delegate=self;
        //[self showViewController:_peoplePickVC sender:(nil)];
    }else if([message.name isEqualToString:@"hideTitleBar"]){//隐藏头

    }else if([message.name isEqualToString:@"iosHideTitleBar"]){//隐藏头
        NSString*path = message.body;
        NSLog(@"iosHideTitleBar:%@",path);
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(cl_kStatusBarHeight);
            //make.centerX.equalTo(self.view);
            //make.width.offset(0);
            make.height.offset(ScreenHeight);
        }];
        if(self.normalNavView!=nil){
            self.normalNavView.hidden=YES;
        }
        if(self.phoneNavView!=nil){
            self.phoneNavView.hidden=YES;
        }
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, 0 , ScreenWidth, cl_kStatusBarHeight)];
        view.backgroundColor = [UIColor colorWithHexString:path];
        self.iosHideTopColor=path;
        [self.view addSubview:view];
        self.iosHide=YES;
    }else if([message.name isEqualToString:@"openOcrFront"]){//ocr正面
        NSString*path = message.body;
        NSLog(@"openOcrFront:%@",path);
        
        SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
        con.scNaigationDelegate = self;
        con.iCardType = TIDCARD2;
        con.isDisPlayTxt = NO;
        //con.TimeKey = TimeKeyS;
        con.ScanMode = TIDC_SCAN_MODE;
        [self presentViewController:con animated:YES completion:NULL];
        
    }else if([message.name isEqualToString:@"openOcrBack"]){//ocr背面
        SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
        con.scNaigationDelegate = self;
        con.iCardType = TIDCARD2;
        con.isDisPlayTxt = NO;
        //con.TimeKey = TimeKeyS;
        con.ScanMode = TIDC_SCAN_MODE;
        [self presentViewController:con animated:YES completion:NULL];
        
        NSString*path = message.body;
        NSLog(@"openOcrBack:%@",path);
    }else if ([message.name isEqualToString:@"startDetectFace"]){//百信拍摄人脸照
        LivenessViewController* dvc = [[LivenessViewController alloc] init];
        dvc.delegate = self;
        NSArray *array_ =nil;
        array_ =[[NSArray alloc]initWithObjects:@1, nil];
        [dvc livenesswithList:array_ order:YES numberOfLiveness:0];
        __weak typeof(self) weakSelf = self;
        [weakSelf presentViewController:dvc animated:YES completion:nil];
        
    }else if ([message.name isEqualToString:@"finishThisPage"]){
        //[self.navigationController popToRootViewControllerAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"h5OpenScan"]){
        
        AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if(authStatus==AVAuthorizationStatusAuthorized){
                //开始扫描二维码
                [self startScan];
            }else{
                 [Tools showMessage:@"未开启相机权限，请前往设置中开启"];
            }
    }
}
#pragma mark - passImagesDelegate,图片回调
- (void)passImages:(NSArray *)imagesArray {
    if(imagesArray==nil||imagesArray.count!=4){
        [Tools showMessage:@"识别失败,请重新尝试!"];
        return;
    }
    FaceImageModel*imageModel = imagesArray[2];
    NSString *base64=[self imageChangeType:imageModel.image];
    NSDictionary* face = @{
        @"face":base64
    };
    NSString*json = [self dictionaryToJson:face];
    json = [self noWhiteSpaceString:json];
    NSString *inputValue = [NSString stringWithFormat:@"startDetectFace('%@')",json];
    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
           NSLog(@"webView_startDetectFace: %@ error: %@", response, error);
     }];
    
}
#pragma mark - 图片处理
-(NSString*)imageChangeType:(UIImage*)selfImage{
    UIImage *  flippedImage= selfImage;
    //这里做了修改2017年6月27日
    //先获取图片的镜面图像
    flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                        scale:1.0 orientation: UIImageOrientationUpMirrored];
    //2017年6月27日
    //2017年7月17日 (483,664)  -->  (360,270)
    //压缩到某一尺寸
    flippedImage=  [self imageByScalingAndCroppingForSize:CGSizeMake(360, 270) and:flippedImage];
    //压缩
    NSData  *dateImage1 =UIImageJPEGRepresentation( flippedImage,0.86);
    //编码
    NSString *str3=[EnercryTool encryptBase64:dateImage1];
    return str3;
}


#pragma mark - SCNavigationControllerDelegate
- (void)sendAllValue:(NSString *)text{
    NSLog(@"all  = %@",text);
}

- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num{
    if (![IDCardNumber_Validate isValidateIDCardString:num]) {
        [SVProgressHUD showInfoWithStatus:@"身份证号识别错误,请重新拍摄"];
        _bx_ok=NO;
        return;
    }
    if(name==nil||[name isEqualToString:@""]){
        [SVProgressHUD showInfoWithStatus:@"姓名识别错误,请重新拍摄"];
        _bx_ok=NO;
        return;
    }
    self.bx_id=num;
    self.bx_name=name;
    self.bx_nation=folk;
    self.bx_address=address;
    _bx_ok=YES;
}

 - (void)sendIDCBackValue:(NSString *)issue PERIOD:(NSString *) period  IDCPASSNUM:(NSString *)passnum{
    NSLog(@"idcback  = %@%@",issue,period);
     if(period==nil||[period isEqualToString:@""]){
         [SVProgressHUD showInfoWithStatus:@"国徽面识别错误,请重新拍摄"];
         _bx_ok=NO;
         return;
     }
     self.bx_sign=issue;
     self.bx_valid=period;
     _bx_ok=YES;
}

- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage{
    NSLog(@"sendTakeImage = %d %@\n",iCardType,cardImage);
    NSData *small =UIImageJPEGRepresentation([self imageByScalingAndCroppingForSize:CGSizeMake(667, 375) and:cardImage], 1.0);
    NSString *ocrBase64 = [small base64EncodedStringWithOptions:0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       // 在延迟1秒后执行代码
        if(_bx_ok){
            if(iCardType==TIDCARD2){//正面
                NSDictionary* front = @{
                    @"name":self.bx_name,
                    @"id":self.bx_id,
                    @"nation":self.bx_nation,
                    @"address":self.bx_address,
                    @"front":ocrBase64
                };
                NSString*json = [self dictionaryToJson:front];
                json = [self noWhiteSpaceString:json];
                NSString *inputValue = [NSString stringWithFormat:@"openOcrFront('%@')",json];
                [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                       NSLog(@"webView_openOcrFront: %@ error: %@", response, error);
                 }];
            }else if (iCardType==TIDCARDBACK){
                NSDictionary* back = @{
                    @"sign":self.bx_sign,
                    @"valid":self.bx_valid,
                    @"back":ocrBase64
                };
                NSString*json = [self dictionaryToJson:back];
                json = [self noWhiteSpaceString:json];
                NSString *inputValue = [NSString stringWithFormat:@"openOcrBack('%@')",json];
                [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                       NSLog(@"webView_openOcrBack: %@ error: %@", response, error);
                 }];
            }
        }
    });
    

}


-(void)startScan{
    //[Tools showMessage:@"扫描结果"];
    self.session=[[AVCaptureSession alloc] init];
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [self.session addInput:input];
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //设置能扫描的区域，这里注意，CGRectMake的x,y和width,height的值是互换位置
    output.rectOfInterest=CGRectMake(150/self.view.frame.size.height, 100/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width);
    [self.session addOutput:output];
    //设置输入元数据的类型(类型是二维码,条形码数据,注意，这个一定要写在添加到session后面，不然要崩溃，如果只需要扫描二维码只需要AVMetadataObjectTypeQRCode，如果还需要扫描条形码，那么全部添加上)
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,
                                        AVMetadataObjectTypeEAN8Code,
                                        AVMetadataObjectTypeEAN13Code,
                                        AVMetadataObjectTypeCode39Code,
                                        AVMetadataObjectTypeCode39Mod43Code,
                                        AVMetadataObjectTypeCode93Code,
                                        AVMetadataObjectTypeCode128Code,
                                        AVMetadataObjectTypePDF417Code,
                                        AVMetadataObjectTypeAztecCode,
                                        AVMetadataObjectTypeUPCECode,
                                        AVMetadataObjectTypeInterleaved2of5Code,
                                        AVMetadataObjectTypeITF14Code,
                                        AVMetadataObjectTypeDataMatrixCode,]];
       //4.添加扫描图层
       self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
       self.layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
       self.layer.frame = self.view.bounds;
       [self.view.layer addSublayer:self.layer];
       //5.创建view,通过layer层进行设置边框宽度和颜色,用来辅助展示扫描的区域
       _cyanView=[[UIView alloc] initWithFrame:CGRectMake(75, 250, self.view.frame.size.width-150, self.view.frame.size.width-150)];
       _cyanView.layer.borderWidth=2;
       _cyanView.layer.borderColor =[UIColor cyanColor].CGColor;
       [self.view addSubview:_cyanView];
    
    //6添加关闭按钮
    self.lightBtn=[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-75, 150, 40, 40)];
       //self.lightBtn.backgroundColor=[UIColor grayColor];
    [self.lightBtn setTitle:@"关闭" forState:0];
       [self.lightBtn addTarget:self action:@selector(lightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
       [self.view addSubview:self.lightBtn];
    
     [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    [self.session startRunning];
}
-(void)lightBtnClick:(UIButton*)sender{
    [self.session stopRunning];
    [self.layer removeFromSuperlayer];
    [self.lightBtn removeFromSuperview];
    [_cyanView removeFromSuperview];
}
//实现扫描的回调代理方法
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection{
//如果数组metadataObjects中有数据，metadataObjects是个数组类型
    if(metadataObjects.count>0) {
        // 获取最终的读取结果，获取数组中最后一个元素，数组中是AVMetadataMachineReadableCodeObject类型对象
        AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
        NSLog(@"%@",object.stringValue);
    
    NSString *inputValue = [NSString stringWithFormat:@"h5OpenScan('%@')",object.stringValue];
    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
           NSLog(@"value图片: %@ error: %@", response, error);
     }];
        //停止扫描
        [self.session stopRunning];
        //移除扫描层layer
        [self.layer removeFromSuperlayer];
    [self.lightBtn removeFromSuperview];
    [_cyanView removeFromSuperview];
    }else{
       NSLog(@"没有扫描到数据");
    }
}



- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    NSLog(@"取消");
}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {

    //遍历
    for (CNContact * contact in contacts) {
        //姓名
        NSString * firstName = contact.familyName;
        NSString * lastName = contact.givenName;
        //电话
        NSArray * phoneNums = contact.phoneNumbers;
        CNLabeledValue *labelValue = phoneNums.firstObject;
        NSString *phoneValue = [labelValue.value stringValue];
        NSLog(@"姓名：%@%@ 电话：%@", firstName, lastName, phoneValue);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)jumpVC:(UIViewController *)vc{

    NSArray *vcs = self.navigationController.viewControllers;

    NSMutableArray *newVCS = [NSMutableArray array];

    if ([vcs count] > 0) {

        for (int i=0; i < [vcs count]-1; i++) {

            [newVCS addObject:[vcs objectAtIndex:i]];

        }

    }

    [newVCS addObject:vc];
    
    [self.navigationController setViewControllers:newVCS animated:YES];
    

}


#pragma mark 跳转到比财
- (void)goToSaveVC
{
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstlog"]) {
        
//        [GTCountSDK trackCountEvent:@"CQG_PUSH_click" withArgs:nil];
//        UITabBarController*tabVC = [self getTabVC];
//        [tabVC.navigationController setNavigationBarHidden:YES];
//        tabVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:tabVC animated:YES];
        
//        [self judgeSaveAmountRequest];
        [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];

        return;
    }else{
        
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
    }
}


#pragma mark - 跳转到新闻
- (void)goToNewsVC {
//    NewsViewController*newsVC = [NewsViewController new];
//    newsVC.title = @"新闻";
//    newsVC.from = @"home";
//    newsVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:newsVC animated:YES];
    
    HeadLineViewController*newsVC = [HeadLineViewController new];
    newsVC.title = @"新闻";
    newsVC.from = @"home";
    newsVC.currentIndex = 0;
    newsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:newsVC animated:YES];
    
    return;
}


//#pragma mark - 跳转到子视图tabcontroller
//- (UITabBarController *)getTabVC:(BOOL)showBC
//{
//    //2.设置窗口的根控制器
//      SaveTabBarController *tabBarVC = [[SaveTabBarController alloc] init];
//      tabBarVC.showBC = showBC;
//      //添加子控制器
//      //默认显示的第一个添加的子控制器的View
//      //tabBarVC里面有多少个子控制器,tabBar当中就有多少个平分的按钮
//
//      //UITabBarController中的tabBar的内容是有对应按钮的控制器来决定的.
//      //tabBar的内容是有对应按钮的控制器的tabBarItem来决定
//
////    if (showBC) {
////
////        SaveProductListController *oneVC = [[SaveProductListController alloc] init];
////        oneVC.title = @"产品列表";
////        oneVC.view.backgroundColor = [UIColor whiteColor];
////        oneVC.tabBarItem = [self getCustomItemWithTitle:@"产品列表" image:@"product_unselected" selectedImage:@"product_selected"];
////        UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
////        [tabBarVC addChildViewController:nav1];
////
////    }else{
////        LittleGoldHouseWebVC *oneVC = [[LittleGoldHouseWebVC alloc] init];
////        oneVC.title = @"小金库";
////        oneVC.view.backgroundColor = [UIColor whiteColor];
////        oneVC.url = @"https://lc.jr.jd.com/ck/xjkHold/index/?channel=a00308";
////        oneVC.tabBarItem = [self getCustomItemWithTitle:@"小金库" image:@"product_unselected" selectedImage:@"product_selected"];
////        UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
////        [tabBarVC addChildViewController:nav1];
////    }
//
//
//    KKCLFundViewController *oneVC = [[KKCLFundViewController alloc]init];
//    oneVC.title = @"存钱罐";
//    oneVC.view.backgroundColor = [UIColor whiteColor];
//    oneVC.tabBarItem = [self getCustomItemWithTitle:@"存钱罐" image:@"product_unselected" selectedImage:@"product_selected"];
//    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
//    [tabBarVC addChildViewController:nav1];
//
//
//
//    LittleGoldHouseWebVC *twoVC = [[LittleGoldHouseWebVC alloc] init];
//    twoVC.title = @"小金库";
//    twoVC.view.backgroundColor = [UIColor whiteColor];
//    twoVC.url = @"https://lc.jr.jd.com/ck/xjkHold/index/?channel=a00308";
//    twoVC.tabBarItem = [self getCustomItemWithTitle:@"小金库" image:@"xiaojinku_unselected" selectedImage:@"xiaojinku_selected"];
//    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:twoVC];
//    [tabBarVC addChildViewController:nav2];
//
//
//      MyAssetsController *threeVC = [[MyAssetsController alloc] init];
//    threeVC.title = @"其他资产";
//    threeVC.view.backgroundColor = [UIColor whiteColor];
//    threeVC.tabBarItem = [self getCustomItemWithTitle:@"其他资产" image:@"myAssets_unselected" selectedImage:@"myAssets_selected"];
//      UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:threeVC];
//      [tabBarVC addChildViewController:nav3];
//
//
//
//
//      //修改主题的颜色
//      tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
//
//
//
//    return tabBarVC;
//}







//- (UITabBarController *)getTabVC2
//{
//    SaveTabBarController *tabBarVC = [[SaveTabBarController alloc] init];
//
//    KKCLFundViewController *oneVC = [[KKCLFundViewController alloc]init];
//    oneVC.title = @"存钱罐";
//    oneVC.view.backgroundColor = [UIColor whiteColor];
//    oneVC.tabBarItem = [self getCustomItemWithTitle:@"存钱罐" image:@"product_unselected" selectedImage:@"product_selected"];
//    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
//    [tabBarVC addChildViewController:nav1];
//
//
//
//    LittleGoldHouseWebVC *twoVC = [[LittleGoldHouseWebVC alloc] init];
//    twoVC.title = @"小金库";
//    twoVC.view.backgroundColor = [UIColor whiteColor];
//    twoVC.url = @"https://lc.jr.jd.com/ck/xjkHold/index/?channel=a00308";
//    twoVC.tabBarItem = [self getCustomItemWithTitle:@"小金库" image:@"xiaojinku_unselected" selectedImage:@"xiaojinku_selected"];
//    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:twoVC];
//    [tabBarVC addChildViewController:nav2];
//
//    //修改主题的颜色
//    tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
//
//
//
//
//    return tabBarVC;
//
//}
//
//
//- (UITabBarController *)getTaskTabVCWithId:(NSString *)orderId
//{
//    //2.设置窗口的根控制器
//      SaveTabBarController *tabBarVC = [[SaveTabBarController alloc] init];
//      //添加子控制器
//      //默认显示的第一个添加的子控制器的View
//      //tabBarVC里面有多少个子控制器,tabBar当中就有多少个平分的按钮
//
//      //UITabBarController中的tabBar的内容是有对应按钮的控制器来决定的.
//      //tabBar的内容是有对应按钮的控制器的tabBarItem来决定
//
//    WeakSelf
//    KKCLFundViewController *oneVC = [[KKCLFundViewController alloc]init];
//    oneVC.title = @"存钱罐";
//    oneVC.view.backgroundColor = [UIColor whiteColor];
//    oneVC.showTaskView = YES;
//    oneVC.block = ^(BOOL success) {
//        [weakSelf makePackageAgainWithSysorderNo:orderId];
//    };
//    oneVC.tabBarItem = [self getCustomItemWithTitle:@"存钱罐" image:@"product_unselected" selectedImage:@"product_selected"];
//    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
//    [tabBarVC addChildViewController:nav1];
//
//
//
//    LittleGoldHouseWebVC *twoVC = [[LittleGoldHouseWebVC alloc] init];
//    twoVC.title = @"小金库";
//    twoVC.view.backgroundColor = [UIColor whiteColor];
//    twoVC.url = @"https://lc.jr.jd.com/ck/xjkHold/index/?channel=a00308";
//    twoVC.tabBarItem = [self getCustomItemWithTitle:@"小金库" image:@"xiaojinku_unselected" selectedImage:@"xiaojinku_selected"];
//    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:twoVC];
//    [tabBarVC addChildViewController:nav2];
//
//
//      MyAssetsController *threeVC = [[MyAssetsController alloc] init];
//    threeVC.title = @"其他资产";
//    threeVC.view.backgroundColor = [UIColor whiteColor];
//    threeVC.tabBarItem = [self getCustomItemWithTitle:@"其他资产" image:@"myAssets_unselected" selectedImage:@"myAssets_selected"];
//      UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:threeVC];
//      [tabBarVC addChildViewController:nav3];
//
//
//
//
//      //修改主题的颜色
//      tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
//
//
//
//    return tabBarVC;
//}
//
//
//- (UITabBarController *)getTaskTabVC2WithId:(NSString *)orderId
//{
//    SaveTabBarController *tabBarVC = [[SaveTabBarController alloc] init];
//
//
//    WeakSelf
//
//    KKCLFundViewController *oneVC = [[KKCLFundViewController alloc]init];
//    oneVC.title = @"存钱罐";
//    oneVC.view.backgroundColor = [UIColor whiteColor];
//    oneVC.showTaskView = YES;
//    oneVC.block = ^(BOOL success) {
//        [weakSelf makePackageAgainWithSysorderNo:orderId];
//    };
//    oneVC.tabBarItem = [self getCustomItemWithTitle:@"存钱罐" image:@"product_unselected" selectedImage:@"product_selected"];
//    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:oneVC];
//    [tabBarVC addChildViewController:nav1];
//
//
//
//    LittleGoldHouseWebVC *twoVC = [[LittleGoldHouseWebVC alloc] init];
//    twoVC.title = @"小金库";
//    twoVC.view.backgroundColor = [UIColor whiteColor];
//    twoVC.url = @"https://lc.jr.jd.com/ck/xjkHold/index/?channel=a00308";
//    twoVC.tabBarItem = [self getCustomItemWithTitle:@"小金库" image:@"xiaojinku_unselected" selectedImage:@"xiaojinku_selected"];
//    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:twoVC];
//    [tabBarVC addChildViewController:nav2];
//
//    //修改主题的颜色
//    tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
//
//
//
//
//    return tabBarVC;
//
//}



//
//- (UITabBarItem *)getCustomItemWithTitle:(NSString *)title image:(NSString *)imageName selectedImage:(NSString *)selectedImageName
//{
//    UIImage *image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    UIImage* selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//     UITabBarItem *tabbarItem = [[UITabBarItem alloc] initWithTitle:title image:image selectedImage:selectedImage];
//    [tabbarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHex:0x137ef6], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
//    [tabbarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHex:0x7a7a7a], NSForegroundColorAttributeName,[UIFont systemFontOfSize:15],NSFontAttributeName, nil] forState:UIControlStateNormal];
//
//    return tabbarItem;
//}


#pragma mark - 跳转到微信公众号
//跳转微信
-(void)openWechat {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL * url = [NSURL URLWithString:@"weixin://"];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
    //先判断是否能打开该url
    if (canOpen)
    {   //打开微信
        //WeakSelf
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                [application openURL:url options:@{} completionHandler:^(BOOL success) {
                        //[weakSelf increaseScoreWithType:scoreType];
                }];
            } else {
                [application openURL:url];
                 //[weakSelf increaseScoreWithType:scoreType];
            }
            
        });
        
        
    }else {
        [SVProgressHUD showInfoWithStatus:@"您的设备未安装微信APP"];
    }
}


#pragma mark - 跳转到百信银行
-(void)openBxBank :(NSURL *)bxUrl{
    UIApplication *application = [UIApplication sharedApplication];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:bxUrl];
    //先判断是否能打开该url
    if (canOpen){   //打开
        //WeakSelf
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                [application openURL:bxUrl options:@{} completionHandler:^(BOOL success) {
                        //[weakSelf increaseScoreWithType:scoreType];
                }];
            } else {
                [application openURL:bxUrl];
                 //[weakSelf increaseScoreWithType:scoreType];
            }
        });
    }else {
        //[SVProgressHUD showInfoWithStatus:@"您的设备未安装微信APP"];
        NSLog(@"%@",@"您的设备未安装百信APP");
    }
}

#pragma mark - 跳转小金库
- (void)goToLittleGoldHouseVCWithId:(NSString *)orderId
{
    __block NSString *tempId = orderId;
    LittleGoldHouseWebVC *oneVC = [[LittleGoldHouseWebVC alloc] init];
    oneVC.title = @"浏览小金库";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.fromHome = YES;
    oneVC.showTaskView = YES;
    oneVC.taskType = LittleGoldHouseTaskTypePackage;
    WeakSelf
    oneVC.block = ^(BOOL success) {
        [weakSelf makePackageAgainWithSysorderNo:tempId];
    };
    oneVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:oneVC animated:YES];
}




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


#pragma mark - GDTRewardedVideoAdDelegate
- (void)gdt_rewardVideoAdDidLoad:(GDTRewardVideoAd *)rewardedVideoAd
{
    [self.rewardVideoAd showAdFromRootViewController:self];
}

/**
 视频播放页关闭回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidClose:(GDTRewardVideoAd *)rewardedVideoAd
{
    
    
}

/**
 视频广告信息点击回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidClicked:(GDTRewardVideoAd *)rewardedVideoAd
{
    
}

/**
 视频广告各种错误信息回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 @param error 具体错误信息
 */
- (void)gdt_rewardVideoAd:(GDTRewardVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error
{
    
}

/**
 视频广告播放达到激励条件回调

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidRewardEffective:(GDTRewardVideoAd *)rewardedVideoAd
{
    NSString *inputValue1 = @"late()";
    [self.webView evaluateJavaScript:inputValue1 completionHandler:^(id _Nullable response, NSError * _Nullable error) {
           NSLog(@"value图片: %@ error: %@", response, error);
     }];
    
    [self getCoinsByWhatVideos];
}

/**
 视频广告视频播放完成

 @param rewardedVideoAd GDTRewardVideoAd 实例
 */
- (void)gdt_rewardVideoAdDidPlayFinish:(GDTRewardVideoAd *)rewardedVideoAd
{
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

#pragma mark - 看视频得金币
- (void)getCoinsByWhatVideos{
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":@"1017",
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    
    
    
    
    
    
//     WeakSelf
       [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
           
           if (responseObject) {
               NSNumber *code = responseObject[@"code"];
               if ([code isKindOfClass:[NSNumber class]]) {
                   if (code.integerValue == 1006) {
                       //@1缩放s动画
                       NSNumber *score = responseObject[@"result"][@"score"];
                       if ([score isKindOfClass:[NSNumber class]]) {
                           
                           [CTToast showWithMessage:[NSString stringWithFormat:@"+%@",score] image:@"readNews-coins-toastBackView" duration:1];
                            NSString *inputValue = [NSString stringWithFormat:@"getGold('%ld')",score.integerValue];
                           [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                                 NSLog(@"value: %@ error: %@", response, error);
                            }];
                          
                           return ;
      
                       }
                       
                       
                       
                   }
                   
                  
                   
               }
               
              
           }
       }];
    
}


#pragma mark - 免费招工
- (void)goToFreeGiveJobVCWithId:(NSString *)orderId
{
    __block NSString *tempId = orderId;
    WebVC *webvc = [[WebVC alloc]init];
    webvc.url = @"https://nginx.weface.com.cn/appH5/workApp/#/home";
    webvc.title = @"找工作";
    webvc.showTaskView = YES;
    webvc.taskType = LittleGoldHouseTaskTypePackage;
    WeakSelf
    webvc.block = ^(BOOL success) {
        [weakSelf makePackageAgainWithSysorderNo:tempId];
    };
    webvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webvc animated:YES];
}

#pragma mark - 跳转找工作
- (void)goToFreeJobVC
{
    WebVC *webvc = [[WebVC alloc]init];
    webvc.url = @"https://nginx.weface.com.cn/appH5/workApp/#/home";
    webvc.title = @"找工作";
    [self.navigationController pushViewController:webvc animated:YES];
}

#pragma mark - 找工作
//进度视图
- (void)addTaskView
{
    UIView *taskView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 77 * WIDTHRADIU, ScreenHeight - cl_kTabBarHeight - 40 * WIDTHRADIU, 57 * WIDTHRADIU, 55 * WIDTHRADIU)];
    [self.view addSubview:taskView];
    
    UIImageView *taskImage = [[UIImageView alloc]init];
    taskImage.frame = taskView.bounds;
    taskImage.image = [UIImage imageNamed:@"littleGoldHouseWindow"];
    [taskView addSubview:taskImage];
    
    
    UILabel *lb_content = [[UILabel alloc]init];
    lb_content.numberOfLines = 0;
    lb_content.textColor = [UIColor whiteColor];
    lb_content.textAlignment = NSTextAlignmentCenter;
    lb_content.font = [UIFont systemFontOfSize:8 * WIDTHRADIU];
    
    lb_content.text = @"浏览5秒\n领199金币";
    if (self.taskType == LittleGoldHouseTaskTypeCoins) {
        lb_content.text = @"浏览5秒\n领199金币";
        
        if ([self.title isEqualToString:@"在线兼职"]) {
            lb_content.text = @"浏览10秒\n领60金币";
        }
        
    }else if (self.taskType == LittleGoldHouseTaskTypePackage) {
        lb_content.text = @"浏览5秒\n领取红包";
    }
    [taskView addSubview:lb_content];
    
    [lb_content mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(taskView);
        make.left.offset(2 * WIDTHRADIU);
        make.height.offset(22 * WIDTHRADIU);
    }];
    
    self.lb_content = lb_content;
    
    
    UIButton *taskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    taskBtn.frame = taskView.bounds;
    [taskBtn addTarget:self action:@selector(taskBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    taskBtn.userInteractionEnabled = NO;
    [taskView addSubview:taskBtn];
    
    self.taskBtn = taskBtn;
   
    [self startCount];
}

//定时器活动
- (void)startCount
{
    
    if (self.timer == nil) {
        
        __block NSInteger time = 5; //倒计时时间
        
        if ([self.title isEqualToString:@"在线兼职"]) {
            time = 10;
        }
        
        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,1*NSEC_PER_SEC, 0); //每秒执行
        

        WeakSelf
        dispatch_source_set_event_handler(timer, ^{

            if(time <= 0){ //倒计时结束，关闭

                if (weakSelf.isDestoryTimer == NO) {
                    dispatch_source_cancel(timer);
                    weakSelf.isDestoryTimer = YES;
                }
                

                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.lb_content.text = @"任务完成\n返回领奖励";
                    weakSelf.taskBtn.userInteractionEnabled = YES;
                    if (weakSelf.block) {
                        
//                        if ([self.title isEqualToString:@"在线兼职"]) {
//                            if (self.taskId) {
//                                [self increaseScoreWithType:self.taskId];
//                                return;
//                            }
//
//                        }
                        
                        weakSelf.block(YES);
                    }
                });

            }else{

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (weakSelf.taskType == LittleGoldHouseTaskTypeCoins) {
                        if ([self.title isEqualToString:@"在线兼职"]) {
                            weakSelf.lb_content.text = [NSString stringWithFormat:@"浏览%ld秒\n领60金币",time];
                        }else{
                            weakSelf.lb_content.text = [NSString stringWithFormat:@"浏览%ld秒\n领199金币",time];
                        }
                        
                    }else if (weakSelf.taskType == LittleGoldHouseTaskTypePackage) {
                        weakSelf.lb_content.text = [NSString stringWithFormat:@"浏览%ld秒\n领取红包",time];
                    }
                   

                });
                NSLog(@"%ld",time);

                time--;
            }
        });

        dispatch_resume(timer);
        
        self.timer = timer;
        
    }
    
   
    
}

#pragma mark - 摇钱树
- (void)goToShakeMoneyTreeVC
{
//    [YXAdSDKManager defaultManager].channelID = @"kksh-ios";
//    [YXAdSDKManager defaultManager].vuid = [NSString stringWithFormat:@"kksh_%@",@([getPeopleID PeopleID])];//渠道号前缀+_+用户ID
//
//    [self getH52TaskWebViewWithPostID:@"kksh-wd-banner"];
}

#pragma mark - 云晴跳转
- (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;
//                [self.navigationController pushViewController:taskVC animated:YES];
//            });
//        }
//    } fail:^(NSError * _Nonnull error) {
//        NSLog(@"接口请求失败 error=%@",error);
//    }];
}




#pragma mark - 剪羊毛
- (void)goToShearingWoolVC
{
    [self loadXMImageData];
}
//小满
- (void)loadXMImageData
{
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
//    __weak typeof(self) weakSelf = self;
    [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6668" thirdUserId:@"" success:^(BXMMaterialModel *model) {
        
        
        [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6668" userId:@"" materialModel:model];
        
        [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6668" userId:@"" materialModel:model];
        
        KKActivityViewController *vc = [KKActivityViewController new];
        vc.title = @"剪羊毛";
        vc.placeId = @"6668";
        vc.buId = @"946405771";
        vc.gdtAdId = @"2082218177897738";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    } fail:^(NSString *error) {
    
       
        
    }];
}


#pragma mark - 免费果园
- (void)goToFreeFruitVC
{
    MyFruitViewController *fruitVC = [MyFruitViewController new];
    fruitVC.title = @"免费果园";
    fruitVC.placeId = @"6666";
    fruitVC.buId = @"946405751";
    fruitVC.gdtAdId = @"2062615177198724";
    fruitVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:fruitVC animated:YES];
    
//    NSInteger i = [UserDefault integerForKey:@"fruitVC"];
//    if (i >= 3) {
//        [self addRedPackage];
//    }else{
//        MyFruitViewController *fruitVC = [MyFruitViewController new];
//        fruitVC.title = @"免费果园";
//        fruitVC.placeId = @"6666";
//        fruitVC.buId = @"946405751";
//        fruitVC.gdtAdId = @"2062615177198724";
//        fruitVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:fruitVC animated:YES];
//        return;
//    }
    
   
}

- (void)addRedPackage
{
    //素材使用代码
   //素材曝光,一般在素材加载完成的时候调用.如果不知道素材加载好的时机,可以在素材所在页面加载完成的时候调用
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   
   
   //加载素材
   //__weak typeof(self) weakSelf = self;
   [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6666" thirdUserId:@"" success:^(BXMMaterialModel *model) {
       //weakSelf.model = model;
       if (model) {
           
           [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6666" userId:@"" materialModel:model];
           
           [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6666" userId:@"" materialModel:nil];
           
           
           KKActivityViewController *vc = [KKActivityViewController new];
           vc.title = @"免费果园";
           vc.placeId = @"6666";
           vc.buId = @"946405751";
           vc.gdtAdId = @"2062615177198724";
       //    vc.placeId = @"6666";
       //    vc.buId = @"946405751";
       //    vc.gdtAdId = @"2062615177198724";
           [self.navigationController pushViewController:vc animated:YES];
           
           
       }
   } fail:^(NSString *error) {
       
   }];
}


#pragma mark - 5元红包劵
- (void)goToPhoneRedPackageVC
{
//    WebVC *webvc = [[WebVC alloc]init];
//    NSString  *phone = [getPeopleID PeopleIphoneNmber];
//    if (phone.length > 0) {
//        webvc.url = [NSString stringWithFormat:@"http://www.qld02.com/t/blackcard/callFee/callFeeForH5.html?channel=shebao&mobile=%@",[getPeopleID PeopleIphoneNmber]];
//    }else{
//        webvc.url = @"http://www.qld02.com/t/blackcard/callFee/callFeeForH5.html?channel=shebao";
//    }
//    //webvc.url = @"http://priv.icmad.cn/pages/modules/hf/index/hfczsix";
//    webvc.title = @"话费劵";
//    webvc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:webvc animated:YES];
    [[clickEvent instance] clickEventRooterVC:self getFederatedLoginRequestWithUrl:@"https://web.kanface.com:444/common/forward/FamilyChargeForwardUrl" menuName:@"话费充值"];
}

#pragma mark - 截图
#pragma mark - WKWebView 滚动生成长图
- (void)ZTWKWebViewScrollCaptureCompletionHandler:(void(^)(UIImage *capturedImage))completionHandler{
    // 制作了一个UIView的副本
    UIView *snapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];

    snapShotView.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y, snapShotView.frame.size.width, snapShotView.frame.size.height);

    [self.webView.superview addSubview:snapShotView];

    // 获取当前UIView可滚动的内容长度
    CGPoint scrollOffset = self.webView.scrollView.contentOffset;

    // 向上取整数 － 可滚动长度与UIView本身屏幕边界坐标相差倍数
    float maxIndex = ceilf(self.webView.scrollView.contentSize.height/self.webView.bounds.size.height);

    // 保持清晰度
    //UIGraphicsBeginImageContextWithOptions(self.webView.scrollView.contentSize, false, [UIScreen mainScreen].scale);
    UIGraphicsImageRendererFormat *format = [[UIGraphicsImageRendererFormat alloc] init];
    format.opaque = NO;
    format.scale = [[UIScreen mainScreen] scale];
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:self.webView.scrollView.contentSize format:format];
    // 滚动截图
    [self ZTContentScrollPageDraw:0 maxIndex:(int)maxIndex drawCallback:^{
        UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        // 恢复原UIView
        [self.webView.scrollView setContentOffset:scrollOffset animated:NO];
        [snapShotView removeFromSuperview];

        completionHandler(capturedImage);
    }];
}

// 滚动截图
- (void)ZTContentScrollPageDraw:(int)index maxIndex:(int)maxIndex drawCallback:(void(^)(void))drawCallback{
    [self.webView.scrollView setContentOffset:CGPointMake(0, (float)index * self.webView.frame.size.height)];
    CGRect splitFrame = CGRectMake(0, (float)index * self.webView.frame.size.height, self.webView.bounds.size.width, self.webView.bounds.size.height);

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.webView drawViewHierarchyInRect:splitFrame afterScreenUpdates:YES];
        if(index < maxIndex){
            [self ZTContentScrollPageDraw: index + 1 maxIndex:maxIndex drawCallback:drawCallback];
        }else{
            drawCallback();
        }
    });
}





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

- (void)watchClick:(UIButton *)sender {
    WebVC *vc = [[WebVC alloc]init];
    
    vc.title = @"基金介绍";
    vc.url = @"https://vd2.bdstatic.com/mda-kk9bpj8jufz5yhej/sc/mda-kk9bpj8jufz5yhej.mp4?playlist=%5B%22hd%22%2C%22sc%22%5D&v_from_s=sz_videoui_4135&auth_key=1610079022-0-0-b4b4aa0a54123b39414df8e927a62c37&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=8010_3-8656_2";
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)shareClick:(UIButton *)sender
{
    
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
    sender.userInteractionEnabled = NO;
    [PrizeInfoCommitSuccessAlertView showShareViewWithNumber:@"100" block:^(CTShareType type) {
        sender.userInteractionEnabled = YES;
        if (type == CTShareTypeWX) {
            [self share2WebPageToPlatformType:UMSocialPlatformType_WechatSession];
        }else if (type == CTShareTypeFriend){
            [self share2WebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
    }];
}

- (void)shareBtnClick:(UIButton *)sender {
    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* url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/appH5/Piggybank/activity/lib/invite.html?userId=%@&phone=%@&version=%@&appName=kksh",@([getPeopleID PeopleID]),[getPeopleID PeopleIphoneNmber],version];
    [BCNewActivityShareView showWithVC:self block:^(KKSaveActivityShareType type) {
    
        switch (type) {
            case KKSaveActivityShareTypeWX:
                [self share5WebPageToPlatformType:UMSocialPlatformType_WechatTimeLine url:url title:@"元旦红包大放送" message:@"存款领现金，最高100元" imageUrl:@""];
                break;
            case KKSaveActivityShareTypeFriend:
                [self share5WebPageToPlatformType:UMSocialPlatformType_WechatTimeLine url:url title:@"元旦红包大放送" message:@"存款领现金，最高100元" imageUrl:@""];
                break;
                
            default:
                break;
        }
        
    }];
    
}

- (void)taskBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


//雷俊博,中奖分享赠送
- (void)loadData2:(NSString*)scoreType{
    
    
    
    
    NSString *url = [NSString stringWithFormat:@"%@score/increateScore",CoinsBaseUrl];
    NSDictionary *dic = @{
                          @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"scoreType":scoreType,
                          @"reqTimesTamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2"
                          };
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&Kanwf574",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    
    
    
    
    
    
    
    [self extracted:params url:url];
    
}
#pragma mark - 返回
-(void)buttonClick_1{
    if (self.webView.canGoBack==YES) {
        [self.webView goBack];
    }else{
        if ([self.url containsString:@"bankactive/index.html?"]) {
            NSString *jsString = @"backToApp()";
            [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
                NSLog(@"加载页面%@",error);
            }];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)extracted:(NSMutableDictionary *)params url:(NSString *)url {
    WeakSelf
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 1006) {
                    //@1缩放s动画
                    
                    NSDate *oldDate = [NSDate date];
                    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"shareLastTime"];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    
                    NSNumber *score = responseObject[@"result"][@"score"];
                    if ([score isKindOfClass:[NSNumber class]]) {
                        
                        
                        [weakSelf alertWithScore:score];
                       
                    }
                    
                    
                    
                }
                
               
                
            }
            
           
        }
    }];
}


- (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)showSaveQRAlertVC2
{
    UIAlertController*alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确实是否要保存图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
       
       [self.webView evaluateJavaScript:@"finGetImg('null')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                     
           NSLog(@"value图片: %@ error: %@", response, error);
               
       }];
        
    }];
    WeakSelf
    UIAlertAction*confirmAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
               
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        [weakSelf ZTWKWebViewScrollCaptureCompletionHandler:^(UIImage *capturedImage) {
            UIImageWriteToSavedPhotosAlbum(capturedImage, 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 - h5页面适配
-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    if ([janalytics isEqualToString:@"0元购"]  || [janalytics isEqualToString:@"找工作"]) {
        WebVC *webvc = [[WebVC alloc]init];
        webvc.url = url;
        webvc.title = janalytics;
        [self.navigationController pushViewController:webvc animated:YES];
        return;
    }
    
    
    WebViewController *tc=[WebViewController new];
    tc.URL =[NSURL URLWithString:url];
            tc.hidesBottomBarWhenPushed =YES;
    tc.janalytics = janalytics;
    [self.navigationController pushViewController:tc animated:YES];

}


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

- (void)alertWithScore:(NSNumber *)score
{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"每日分享成功"
                                                    message:[NSString stringWithFormat:@"赠送%@金币",score]
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"确定", @"确定")
                                          otherButtonTitles:nil];
    [alert show];
}


#pragma mark - 分享
//中奖分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }
    
    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
    //NSString* thumbURL =  UMS_THUMB_IMAGE;
   //UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"安全认证 轻松领钱" descr:@"邀您一起拿金币,赢大奖" thumImage:[UIImage imageNamed:@"login_icon"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"就差你啦！我刚刚在看看生活抽到大奖了，快来看看吧" descr:@"签到0元抽，奖品免费拿，还有更多惊喜在等你哟~" thumImage:[UIImage imageNamed:@"login_icon"]];
        //设置网页地址
        NSString *url = [NSString stringWithFormat:@"https://nginx.weface.com.cn/appH5/share5000/index.html?userid=%ld&telephone=%@&appName=kksh",[getPeopleID PeopleID],[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]];//外网
//            NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/lesson/award/shareapp/index.html?userid=%ld&telephone=%@&appName=kksh",[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);
            }
            
            [weakSelf loadData2:@"1015"];
        }
        
    }];
}

//转盘分享
- (void)share2WebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
           [Tools showMessage:@"请先安装微信!!!"];
           return;
       }
    
     WeakSelf
       //创建分享消息对象
       UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
       
       
       //创建网页内容对象
       //NSString* thumbURL =  UMS_THUMB_IMAGE;
       //UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"就差你啦！我刚刚在看看生活抽到大奖了，快来看看吧" descr:@"签到0元抽，奖品免费拿，还有更多惊喜在等你哟~" thumImage:[UIImage imageNamed:@"login_icon"]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"签到0元抽，大奖免费拿" descr:@"让领钱更简单，还有更多福利等你来拿" thumImage:[UIImage imageNamed:@"login_icon"]];
       //设置网页地址
      NSString *url = @"http://nginx.weface.com.cn/lesson/share/src/award.html?appName=kksh";//外网
//       NSString *url = @"http://172.16.10.133/projects/html-nginx/html-nginx/lesson/share/src/award.html";//内网
      
       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"];
           }
           
       }];
}

- (void)share3WebPageToPlatformType:(UMSocialPlatformType)platformType
{
    if (![WXApi isWXAppInstalled]) {
           [Tools showMessage:@"请先安装微信!!!"];
           return;
       }
    
//    WeakSelf
     //创建分享消息对象
     UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
     
     
     //创建网页内容对象
//     NSString* thumbURL =  UMS_THUMB_IMAGE;
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"安全认证 轻松领钱" descr:@"限时抢购补贴口罩，就差你啦！" thumImage:[UIImage imageNamed:@"login_icon"]];
         //设置网页地址
         NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/lesson/award/share/index.html?userid=%ld&telephone=%@&appName=kksh",[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);
             }
             
         }
         
     }];
}

- (void)share4WebPageToPlatformType:(UMSocialPlatformType)platformType
{
    
    if (![WXApi isWXAppInstalled]) {
           [Tools showMessage:@"请先安装微信!!!"];
           return;
       }
    
//    WeakSelf
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    //创建网页内容对象
//    NSString* thumbURL =  UMS_THUMB_IMAGE;
   UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"您有一个红包待领取!" descr:@"赚钱好帮手，看看生活让领钱更简单" thumImage:[UIImage imageNamed:@"login_icon"]];
        //设置网页地址
    //http://172.16.10.136/projects/html-nginx/html-nginx/appH5/Piggybank/index.html?tel=15674168490&loginId=2579309
        NSString *url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/appH5/Piggybank/invite/invite.html?loginId=%ld&tel=%@&appName=kksh",[getPeopleID PeopleID],[getPeopleID PeopleIphoneNmber]];//外网
      
    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"];
        }
        
    }];
}

- (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 - 未登录跳转
- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}

//通用活动分享
-(void)shareCurrencyActivity:(NSDictionary *) dic{
    NSString *shareMedia= dic[@"shareMedia"];
    if ([shareMedia intValue]==101) {//微信
        int isShareImage =[dic[@"isShareImage"]intValue];
        if (isShareImage==101) {//分享图片
            NSString *imageUrl=dic[@"imageString"];
            UMSocialMessageObject *messageObject=[UMSocialMessageObject messageObject];
            UMShareImageObject *shareObject=[[UMShareImageObject alloc]init];
            [shareObject setShareImage:imageUrl];
            messageObject.shareObject=shareObject;
            [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:nil completion:^(id result, NSError *error) {
                if (error) {
                    NSLog(@"share fail%@",error);
                    [Tools showMessage:@"分享失败了！"];
                }else{
                    NSLog(@"share data%@",result);
                    NSString *inputValue = [NSString stringWithFormat:@"backToApp('%@')",@""];
                    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                           NSLog(@"value分享: %@ error: %@", response, error);
                     }];
                }
            }];
        }else{//其他分享
            UMSocialMessageObject *messageObject=[UMSocialMessageObject messageObject];
            UMShareWebpageObject *shareObject=[UMShareWebpageObject shareObjectWithTitle:dic[@"title"] descr:dic[@"describe"] thumImage:dic[@"imageUrl"]];
            shareObject.webpageUrl=dic[@"url"];
            messageObject.shareObject=shareObject;
            [[UMSocialManager defaultManager]shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:nil completion:^(id result, NSError *error) {
                if (error) {
                    [Tools showMessage:@"分享失败了！"];
                }else{
                    NSString *inputValue = [NSString stringWithFormat:@"backToApp('%@')",@""];
                    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                           NSLog(@"value分享: %@ error: %@", response, error);
                     }];
                }
            }];
        }
        
    }else if ([shareMedia intValue]==102){//小程序
        [self shareMiniProgramToPlatformType:UMSocialPlatformType_WechatSession defaultUrl:@"http://www.weface.com.cn/" url:dic[@"url"] title:dic[@"title"] message:dic[@"describe"] userName:dic[@"id"] path:dic[@"path"]];
    }
}


//分享小程序
- (void)shareMiniProgramToPlatformType:(UMSocialPlatformType)platformType defaultUrl:(NSString *)defaultUrl url:(NSString *)url title:(NSString *)title message:(NSString *)message userName:(NSString *)userName path:(NSString*)path
{
    
    if (![WXApi isWXAppInstalled]) {
           [Tools showMessage:@"请先安装微信!!!"];
           return;
       }
    UMSocialMessageObject *msgObject=[UMSocialMessageObject messageObject];
    UMShareMiniProgramObject *shareObject=[UMShareMiniProgramObject shareObjectWithTitle:title descr:message thumImage:url];
    shareObject.webpageUrl=defaultUrl;
    shareObject.userName=userName;
    shareObject.path=path;
    shareObject.hdImageData=[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"logo" ofType:@"png"]];
    shareObject.miniProgramType=UShareWXMiniProgramTypeRelease;
    msgObject.shareObject=shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:msgObject currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            NSLog(@"error:%@",error);
            [Tools showMessage:@"分享失败了！"];
        }else{
            NSLog(@"data:%@",result);
            NSString *inputValue = [NSString stringWithFormat:@"backToApp('%@')",@""];
            [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                   NSLog(@"value分享: %@ error: %@", response, error);
             }];
        }
    }];
    

}


#pragma mark - 提示
- (void)alertShowMessage:(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];
    }
}


#pragma mark - private methods
// 判断是否是同一天
- (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)cleanCacheAndCookie{
    
    if ([[[UIDevice currentDevice]systemVersion]intValue ] >= 9.0) {
        NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSLog(@"%@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        
    }
   
    
}


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

{

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

    NSString *jsonString;

    if (!jsonData) {

        NSLog(@"%@",error);

    }else{

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

    }

    return jsonString;

}



#pragma mark - getters and setters
- (UIView *)getNavBackView
{
    UIView*backView = [[UIView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth,cl_kNavigationBarHeight)];
    CAGradientLayer*gradientLayer = [CAGradientLayer layer];
    gradientLayer.locations = @[@0.0, @1.0];
    gradientLayer.startPoint = CGPointMake(1, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0xff5633] CGColor],(id)[[UIColor colorWithHex:0xf8502c] CGColor]]];//渐变数组
    gradientLayer.frame = backView.frame;
    [backView.layer addSublayer:gradientLayer];
    return backView;
}
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = 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:@"jsToOcNoPrams"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toMyawardListVc"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toMyWallet"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"sharePrize"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toShare"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"maskShare"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toStep"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getImg"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getBack"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getUserId"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getPhoneNumber"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getVersionId"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getPhoto"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"fromPlatform"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shareMoneyPot"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"backToHomePage"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"showRewardVideoAd"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"showSaveQRAlertVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toPiggyBank"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shareBcWelfareUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shareUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toMineGold"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"bcCopyBankNumber"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"bcToMS"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"MoneyCattle"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"NewsCattle"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"foucsCattle"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toGoldCenter"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"lookJdDouble"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"clickBackBtn"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toWorkVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"toSmallProgram"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"cashCow"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"freeFruit"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shearingWool"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"goToPhoneRedPackageVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"saveCurrentWeb"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"kkshHelper"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"unionLogin"];//lianhedenglu
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"lifeZJZ"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"getContactInfo"];//亲情冲，打开通讯录列表
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"hideTitleBar"];//隐藏导航栏
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"iosHideTitleBar"];//隐藏导航栏
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"finishThisPage"];//关闭
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"h5OpenScan"];//扫描功能
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"shareSmallProgram"];//分享小程序到微信
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"currencyActivity"];//通用活动分享
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"isOpenInApp"];//富民银行
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"getLoginInfo"];//获取登录信息
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openOcrFront"];//ocr正面
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openOcrBack"];//ocr背面
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"startDetectFace"];//百信人脸
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"h5BindWechat"];//H5唤醒微信绑定
        
       config.userContentController = wkUController;
        
        
        //以下代码适配文本大小
       // NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
       // NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
        //用于进行JavaScript注入
        //WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        //[config.userContentController addUserScript:wkUScript];

      
        _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        _webView.scrollView.bounces = false;
        if ([self.from isEqualToString:@"newsList"]) {
            _webView.scrollView.delegate = self;
        }
        
        if ([self.title isEqualToString:@"智能问诊"]) {
            [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
                  NSString *oldAgent = result;
                  
                  // 给User-Agent添加额外的信息
                  NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"kksb_app"];

                  // 设置global User-Agent
                  self->_webView.customUserAgent = newAgent;
            }];
        }
       
        
        
        NSDictionary *dic = [getPeopleID totalCoins];
        NSString *score = [NSString stringWithFormat:@"%@",[dic[@"totalScore"] stringValue]];
        
        NSURL *photoUrl = [getPeopleID PeoplePhoto];
        
        
//        NSString* version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        
        if ([self.title isEqualToString:@"金币抽奖"]) {
            NSString *url = [NSString stringWithFormat:@"%@?UserId=%@&gold=%@&tel=%@&headPic=%@&versionCode=%@.0.0&appName=kksh",self.url,[NSNumber numberWithInteger:[getPeopleID PeopleID]],score,[EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],photoUrl.absoluteString ?photoUrl.absoluteString :@"",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
            
            
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            
            [_webView loadRequest:request];
        }else{
            
            
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
            
            [_webView loadRequest:request];
        }
        
        
    }
    return _webView;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    
    return _imagePicker;
}
#pragma mark - 充值历史
- (void)TopupHistoryClick:(UIButton *)button{
//    NSString *url = [NSString stringWithFormat:@"https://nginx.weface.com.cn/appH5/Prepaid/#/historyPage?uid=%ld",[getPeopleID PeopleID]];
//    WebVC *webvc = [[WebVC alloc]init];
//    webvc.url = url;
//    webvc.title = @"充值历史";
//    webvc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:webvc animated:YES];
    NSString *inputValue = [NSString stringWithFormat:@"torecord()"];
    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
           NSLog(@"value历史: %@ error: %@", response, error);
     }];
}
//- (WKUserContentController *)userContentController
//{
//    if (!_userContentController) {
//        _userContentController = [[WKUserContentController alloc]init];
//                //注册一个name为toNews()的js方法 设置处理接收JS方法的对象
//        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
//        //注册方法
//        WKDelegateController * delegateController = [[WKDelegateController alloc]init];
//        delegateController.delegate = self;
//        [_userContentController addScriptMessageHandler:delegateController name:@"jsToOcWithPrams"];
//    }
//    return _userContentController;
//}

/*
#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.
}
*/
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize and:(UIImage*)imageKs
{
    UIImage *sourceImage = imageKs;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
      
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize);
    //UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:targetSize];
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
    
 
    UIGraphicsEndImageContext();
    return newImage;
}
@end
