//
//  KKAuthHelperViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/4/13.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "KKAuthHelperViewController.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"
#import "Tools.h"

//认证查询
#import "WeiJianQueryViewController.h"
#import "AuthenticationListViewController.h"
//我的奖品
#import "MyPrizeListVC.h"

//极光小视频
#import "KKTabBarViewController.h"
#import "KKTVViewController.h"
#import "LittleVideoViewController.h"
#import "KKVideoViewController.h"
#import "KKSVideoViewController.h"

//存钱罐
#import "StatisticsViewController.h"
#import "SaveTabBarController.h"
#import "SaveProductListController.h"
#import "MyAssetsController.h"
#import "LittleGoldHouseWebVC.h"
#import "ProductDetailController.h"
#import "KKActivityRedPackageBaseView.h"
#import "KKCLFundViewController.h"

//微信
#import <WXApi.h>

//社保认证
#import "KKUserIdentifyViewController.h"
//补贴认证
#import "DistrictAuthenticationPersonalInfoController.h"

//打卡
#import "CoinsCenterViewController.h"

//邀请好友
#import "ShareViewController.h"

//听听
#import "KKLisenViewController.h"

@interface KKAuthHelperViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic, strong)WKWebView *webView;

@end

@implementation KKAuthHelperViewController
#pragma mark 移除观察者
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"title"];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
         
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *whiteView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:whiteView];
    [whiteView addSubview:self.webView];

    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
       }
    
    [self navConfig];
    
    
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    
    [self.webView loadRequest:request];
}


- (void)navConfig {
    
    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button_2.frame = CGRectMake(-30, 0, 60, 25);
    button_2.titleLabel.textAlignment =NSTextAlignmentLeft;
    [button_2 setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [button_2 setTitle:@"返回" forState:UIControlStateNormal];
    [button_2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button_2 addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];
    
    self.navigationItem.leftBarButtonItem = backButtonItem_2;
}

#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //网页title
    if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.title = self.webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
     } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
     }
}

#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:页面开始加载");
}
//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:内容开始返回");
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:页面加载完成");

    NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];  //获取本地版本号
    currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSDictionary* dic = @{
        @"telphone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"fromapp":@"kksh",
        @"frommodel":@(2),
        @"userid":@([getPeopleID PeopleID]),
        @"version":currentVersion
    };
    
    NSString*jsonStr = [self dictionaryToJson:dic];
    jsonStr = [self noWhiteSpaceString:jsonStr];
   // jsonStr = [SecurityUtil encodeBase64String:jsonStr];
    NSString *inputValue = [NSString stringWithFormat:@"getInfoFromApp(%@)",jsonStr];
   
   
   [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                 NSLog(@"value图片: %@ error: %@", response, error);
    }];
    

}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"WebVC:页面加载失败");
}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:接收到服务器跳转请求");
}

// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSLog(@"WebVC:收到服务器响应,是否跳转");
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

static const NSString * CompanyFirstDomainByWeChatRegister = @"k.yaodouwang.com";
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"WebVC:发送请求之前,决定是否跳转");
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
//    NSString* reqUrl = navigationAction.request.URL.absoluteString;
    NSString * scheme = [navigationAction.request.URL scheme];
    
    NSURL  * url = navigationAction.request.URL;
    UIApplication *app = [UIApplication sharedApplication];
    //    appstore的外的包
        if ([url.absoluteString containsString:@"itms-appss://"]) {
            [app openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    
    
    ///打电话
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [navigationAction.request.URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@", resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
    
    

    
     if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
           decisionHandler(WKNavigationActionPolicyCancel);
           
           if ([navigationAction.request.URL.absoluteString hasPrefix:@"weixin://"]) {
               [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
           }
           return;
       }
       
    
    
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}

#pragma mark - WKUIDelegate
//创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"WebVC:创建一个新的WebView");
     WKFrameInfo *frameInfo = navigationAction.targetFrame;
       if (![frameInfo isMainFrame]) {
           [webView loadRequest:navigationAction.request];
       }
       return nil;
}

//输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
    NSLog(@"WebVC:输入框");
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    NSLog(@"WebVC:确认框");
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"WebVC:警告框");
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    
   
    
    if ([message.name isEqualToString:@"kkshHelper"]) {
        if ([message.body isKindOfClass:[NSString class]]) {
            NSString *type = message.body;
            
            if ([type isEqualToString:@"1002"]) {
                
                [self goToAuthQueryVC];//查看认证记录
                
            }else if ([type isEqualToString:@"1003"]) {
                
                [self goToMyPrizeListVC];//我的奖品
                
            }else if ([type isEqualToString:@"1004"]) {
                
                [self goToTVVC:NO];//看视频赚红包
                
            }else if ([type isEqualToString:@"1009"]){
                
                [self goToSheBaoAuthListVC];
                
            }else if ([type isEqualToString:@"1010"]){
                
                [self goToBuTieAuthListVC];
                
            }else if ([type isEqualToString:@"1011"]){
                
                [self goToYouFuListVC];
                
            }else if ([type isEqualToString:@"1022"]){
//                [self judgeSaveAmountRequest];
                [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
            }else if ([type isEqualToString:@"1023"]){
                [self goToSheBaoAuthVC];
            }else if ([type isEqualToString:@"1024"]){
                [self goToBuTieAuthVC];
            }else if ([type isEqualToString:@"1025"]){
                [self goToYiBaoKaVC];
            }else if ([type isEqualToString:@"1026"]){
                [self goToFreeGiveJobVC];
            }else if ([type isEqualToString:@"1027"]){
                [self goToGoodInsuranceVC];
            }else if ([type isEqualToString:@"1028"]){
                [self goToCoinsCenterVC];
            }else if ([type isEqualToString:@"1029"]){
                [self goToChangLiangVC];
            } else if ([type isEqualToString:@"1030"]){
                [self goToCircleDishVC];
            }else if ([type isEqualToString:@"1031"]){
                [self goToInviteVC];
            }else if ([type isEqualToString:@"1032"]){
                [self goToLisenVC];
            }
        }
    }else if ([message.name isEqualToString:@"showSaveQRAlertVC"]){
        NSString*urlString = message.body;
       
       [self showSaveQRAlertVC:urlString];
   }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 shareWebPageToPlatformType:UMSocialPlatformType_WechatSession url:url title:title message:describe];
        }else if ([type isEqualToString:@"朋友圈"]) {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine url:url title:title message:describe];
        }
        
        
   }else if ([message.name isEqualToString:@"clickBackBtn"]){
       [self backClick:nil];
   }else if ([message.name isEqualToString:@"backToHomePage"]){
       [self.navigationController popToRootViewControllerAnimated:YES];
   }else if ([message.name isEqualToString:@"getAuthActivityNoti"]){
       [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
   }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:@"InvokeToApp"]){
       NSString *str = message.body;
       [[clickEvent instance] clickEventRooterVC:self Content:str menuName:@""];
   }else if ([message.name isEqualToString:@"unionLogin"]){
       NSString *str = message.body;
       [[clickEvent instance]clickEventRooterVC:self getFederatedLoginRequestWithUrl:str menuName:@""];
   }
    

}


#pragma mark - 保存图片到相册
- (void)showSaveQRAlertVC:(NSString *)imgUrl
{
    UIAlertController*alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确实是否要保存图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction*confirmAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
        UIImage* image = [UIImage imageWithData:data];
               
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
                        
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    
    if (error) {
        [Tools showMessage:@"保存失败"];
    }else{
        [Tools showMessage:@"保存成功"];
    }
}


#pragma mark - 微信分享

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType url:(NSString *)url title:(NSString *)title message:(NSString *)message
{
    
    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{
        
        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)goToSheBaoAuthListVC
{
    
    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    socialRecord*vc=[sb instantiateViewControllerWithIdentifier:@"socialRecord"];
    vc.hidesBottomBarWhenPushed =YES;
    vc.isHomeVC = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - 补贴认证查询
- (void)goToBuTieAuthListVC
{
    AuthenticationListViewController *vc = [[AuthenticationListViewController alloc]init];
    vc.title = @"认证记录";
    vc.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 优抚认证查询
- (void)goToYouFuListVC
{
    
    AuthenticationListViewController *vc = [[AuthenticationListViewController alloc]init];
    vc.title = @"认证记录";
    vc.hidesBottomBarWhenPushed = YES;
    vc.type = @"butie";

    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - 认证查询
- (void)goToAuthQueryVC {
    WeiJianQueryViewController* vc = [WeiJianQueryViewController new];
    vc.title = @"认证查询";
    [self.navigationController pushViewController:vc animated:YES];
    return;
}

#pragma mark - 我的奖品
- (void)goToMyPrizeListVC {
    MyPrizeListVC *vc = [[MyPrizeListVC alloc]init];
    vc.title = @"我的奖品";
    [self.navigationController pushViewController:vc animated:YES];
    return;
}


#pragma mark - 跳转到小视频
- (void)goToTVVC:(BOOL)fromHome {
    
    KKSVideoViewController *oneVC = [[KKSVideoViewController alloc]initWithType:fromHome];
    oneVC.title = fromHome ?@"看视频" :@"红包视频";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:oneVC animated:YES];
    
    /*
    KKTabBarViewController *tabBarVC = [[KKTabBarViewController alloc]initWithType:fromHome];
    
    
    LittleVideoViewController *twoVC = [[LittleVideoViewController alloc] init];
    twoVC.title = fromHome ?@"看视频" :@"红包视频";
    twoVC.view.backgroundColor = [UIColor whiteColor];
    twoVC.tabBarItem = [self getCustomItemWithTitle:@"更多" image:@"" selectedImage:@""];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:twoVC];
    [tabBarVC addChildViewController:nav1];
    
    KKVideoViewController *oneVC = [[KKVideoViewController alloc] init];
    oneVC.title = fromHome ?@"看视频" :@"红包视频";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.tabBarItem = [self getCustomItemWithTitle:@"小视频" image:@"" selectedImage:@""];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:oneVC];
    [tabBarVC addChildViewController:nav2];
    
    
    
    //tabBarVC.fromHome = fromHome;
    
    
    //修改主题的颜色
    tabBarVC.tabBar.tintColor = [UIColor colorWithHex:0x137ef6];
    
    
    
    [tabBarVC.navigationController setNavigationBarHidden:YES];
    tabBarVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tabBarVC animated:YES];
     
     */
    
}

#pragma mark - 社保认证
- (void)goToSheBaoAuthVC
{
    KKUserIdentifyViewController*vc = [[KKUserIdentifyViewController alloc]init];
    vc.title = @"社保认证";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 补贴认证
- (void)goToBuTieAuthVC
{
    DistrictAuthenticationPersonalInfoController* vc = [DistrictAuthenticationPersonalInfoController new];
    vc.title = @"补贴认证";
    vc.type = @"butie";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 医保卡
- (void)goToYiBaoKaVC
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipays://"]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"alipays://platformapi/startapp?appId=2021001123625885&page=pages%2findex%2findex%3fprovideId%3d2088331168368991%26chInfo%3dXSbduanfanyong"] options:nil completionHandler:nil];
        return;
        }
    
    if (![WXApi isWXAppInstalled]){
        [Tools showMessage:@"请安装支付宝APP后重试"];
        return;
    }
    
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_45334679e384";  //拉起的小程序的username
    launchMiniProgramReq.path = @"pages/nhsa-code/index/index?channel=AAEKTLpkFoE88Zic8BqWR87_&cityCode=440300";    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        
    }];
}

#pragma mark - 免费招工
- (void)goToFreeGiveJobVC
{
    [self jumpToHTML5:@"https://nginx.weface.com.cn/appH5/workApp/#/home" andJAnalytics:@"找工作"];
}

#pragma mark - 实惠保险
- (void)goToGoodInsuranceVC
{
    [self jumpToHTML5:@"http://nginx.weface.com.cn/lesson/dadiApp/index.html" andJAnalytics:@"实惠保险"];
}

#pragma mark - 打卡
- (void)goToCoinsCenterVC
{
    CoinsCenterViewController *vc = [[CoinsCenterViewController alloc]init];
    vc.title = @"打卡赚金币";
    [self.navigationController pushViewController:vc animated:YES];
}



//#pragma mark - 存钱罐
//- (void)judgeSaveAmountRequest
//{
//    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGetSaveAmountRequest];
//    NSLog(@"获取乌当和比财账户存款金额总数量url:%@",url);
//
////    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"];
//
//    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
//    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
//
//
////    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"tel"];
////    [params setObject:@([getPeopleID PeopleID]) forKey:@"uid"];
////    [params setObject:province forKey:@"province"];
////    [params setObject:city forKey:@"city"];
////    [params setObject:county forKey:@"county"];
//
//
//
//    NSLog(@"params:%@",params);
//    [KKLoadingAnimationView show];
//    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
//        [KKLoadingAnimationView dismiss];
//        NSLog(@"objc:%@",objc);
//        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
//        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
//        if ([state isEqualToString:@"200"]) {
//            NSDictionary *result = objc[@"result"];
//            if ([result isKindOfClass:[NSDictionary class]]) {
//                NSString *sumAmount = [NSString stringWithFormat:@"%@",result[@"sumAmount"]];
//
//
//                if (sumAmount.doubleValue > 0) {
//                    SaveTabBarController*tabVC = (SaveTabBarController*)[self getTabVC:YES];
//
//                    [tabVC.navigationController setNavigationBarHidden:YES];
//                    tabVC.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:tabVC animated:YES];
//                }else{
//
////                    LittleGoldHouseWebVC *oneVC = [[LittleGoldHouseWebVC alloc] init];
////                    oneVC.title = @"小金库";
////                    oneVC.view.backgroundColor = [UIColor whiteColor];
////                    oneVC.fromHome = YES;
////                    oneVC.hidesBottomBarWhenPushed = YES;
////                    [self.navigationController pushViewController:oneVC animated:YES];
//
//                    SaveTabBarController*tabVC = (SaveTabBarController*)[self getTabVC2];
//
//                    [tabVC.navigationController setNavigationBarHidden:YES];
//                    tabVC.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:tabVC animated:YES];
//
//
//                }
//
//
//
//
//            }
//
//        }else{
//            [Tools showMessage:describe];
//        }
//
//    } Failure:^(NSError* error) {
//        [KKLoadingAnimationView dismiss];
//        NSLog(@"error:%@",error);
//
//        [Tools showMessage:@"网络出小差了,请稍后重试"];
//
//    }];
//}

#pragma mark - 转盘
- (void)goToCircleDishVC
{
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                             };
    NSString *url =[NSString stringWithFormat:@"%@score/getpersonintegrals",CoinsBaseUrl];
    
    WeakSelf;
    [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
        if (responseObj) {
            NSString *code = [responseObj[@"code"] stringValue];
            if ([code isEqualToString:@"0"]) {
                [getPeopleID getTotalCoins:responseObj[@"result"]];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[KKAuthHelperViewController class]]) {
                    
                    WebVC *webVC = [[WebVC alloc]init];
                     webVC.type = @"home";
                     webVC.title = @"金币抽奖";
                     //外网http://nginx.weface.com.cn/lesson/award/src/award.html
                     //内网@"http://172.16.10.121/projects/html-nginx/html-nginx/lesson/award/src/award.html"
                    //webVC.url = @"http://nginx.weface.com.cn/lesson/award/src/award.html";
                      webVC.url = CoinsRewardedUrl;
                     [weakSelf.navigationController pushViewController:webVC animated:YES];
                    
                }
                
                
            }
        }
    }];
}

#pragma mark - 邀请好友
- (void)goToInviteVC
{
    ShareViewController *shareVC = [[ShareViewController alloc]init];
    shareVC.title = @"邀请好友";
    shareVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:shareVC animated:YES];
}

#pragma mark - 听听
- (void)goToLisenVC
{
    KKLisenViewController*vc = [KKLisenViewController new];
    vc.fromHome = YES;
    [self.navigationController pushViewController:vc 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;
//
//}
//
//#pragma mark - 自定义UITabBarItem

//- (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)goToChangLiangVC
{
    KKCLFundViewController *oneVC = [[KKCLFundViewController alloc]init];
    oneVC.title = @"存钱罐";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.from = @"home";
    [self.navigationController pushViewController:oneVC animated:YES];
}

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




#pragma mark - 字典转json
/**
 *  字典转JSON字符串
 *
 *  @param dic 字典
 *
 *  @return JSON字符串
 */
- (NSString*) dictionaryToJson:(NSDictionary *)dic{
    NSString *json = nil;

    if ([NSJSONSerialization isValidJSONObject:dic]) {


      NSError *error;

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

      if(!error) {

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

      }

      else {

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

      }
    }

    else {

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

    return json;
}

#pragma mark - 去除空白换行

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


#pragma mark - 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 - getters and setters
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc]initWithDelegate:self];
        
        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];
        
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"kkshHelper"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"clickBackBtn"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"backToHomePage"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"showSaveQRAlertVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"shareBcWelfareUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"getAuthActivityNoti"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"openUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"unionLogin"];//lianhedenglu
       config.userContentController = wkUController;
      
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.scrollView.bounces = false;
    }
    return _webView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
