//
//  CommunityVC.m
//  Open
//
//  Created by qinxuyang on 2021/11/23.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "CommunityVC.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"
#import <WXApi.h>
#define CommunityUrl @"https://nginx.weface.com.cn/appH5/appoutlink/#/riches"
//#define CommunityUrl @"http://172.16.10.194:9900/#/"
@interface CommunityVC ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, strong) NSDictionary *shareDic;
@end

@implementation CommunityVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor whiteColor] image:nil isOpaque:YES];//颜色
 
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        // Fallback on earlier versions
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    }
    
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showSuspension"]) {
//       //悬浮按钮
//       [[clickEvent instance] SuspensionBtnRooterVC:self];
//    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.webView];

    if (@available(iOS 11.0, *)) {
           self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
       self.automaticallyAdjustsScrollViewInsets = NO;
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:CommunityUrl]];
    [self.webView loadRequest:request];
    //登陆
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginUpdateDataAction) name:KKSBLoginSuccessNotificationName object:nil];
    //页面跳转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PageJumpAction) name:@"CommunityPageJumpNotificationName" object:nil];
    
//    if (self.isFrom) {
//        [self configNav];
//    }
}
#pragma mark - 界面跳转
- (void)PageJumpAction{
    NSString *urlParm = [[NSUserDefaults standardUserDefaults] objectForKey:@"WefaceCommunityUrl"];
    if (urlParm && urlParm.length > 0) {
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"WefaceCommunityUrl"];
        [[NSUserDefaults standardUserDefaults]synchronize];

      //跳转对应界面 调用原生JS方法
     NSArray *arr = [urlParm componentsSeparatedByString:@"|"];
     if (arr.count == 2) {
        NSMutableDictionary *Parm = [NSMutableDictionary dictionary];
        [Parm setValue:arr[0] forKey:@"path"];
        [Parm setValue:arr[1] forKey:@"id"];
        NSString*jsonStr = [self dictionaryToJson:Parm];
        jsonStr = [self noWhiteSpaceString:jsonStr];
        NSString *jsString = [NSString stringWithFormat:@"toRouter(%@)", jsonStr];
        [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            NSLog(@"加载页面%@",error);
        }];
     }
    }
}
- (void)configNav
{
    UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor colorWithHex:0x086ed7];
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"看看";
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
}
- (void)backClick{
    if (self.webView.canGoBack==YES) {
        [self.webView goBack];
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)loginUpdateDataAction{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:CommunityUrl]];
    [self.webView loadRequest:request];
}
- (WKWebView *)webView{
    if (_webView == nil) {
        //创建网页配置对象
        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 * userContentController = [[WKUserContentController alloc] init];
        //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
        [userContentController addScriptMessageHandler:self  name:@"shareUrl"];
        [userContentController addScriptMessageHandler:self  name:@"finishThisPage"];
        [userContentController addScriptMessageHandler:self  name:@"InvokeToApp"];
        [userContentController addScriptMessageHandler:self  name:@"openUrl"];
        [userContentController addScriptMessageHandler:self  name:@"toSmallProgram"];
        [userContentController addScriptMessageHandler:self  name:@"isOpenInApp"];//富民银行
        [userContentController addScriptMessageHandler:self  name:@"forumLogin"];
        [userContentController addScriptMessageHandler:self name:@"getUserId"];
        [userContentController addScriptMessageHandler:self name:@"getPhoneNumber"];
        [userContentController addScriptMessageHandler:self name:@"getVersionId"];
        [userContentController addScriptMessageHandler:self name:@"getLoginInfo"];
        config.userContentController = userContentController;
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT, ScreenWidth, ScreenHeight - STATUS_BAR_HEIGHT - TAB_BAR_HEIGHT) configuration:config];
      
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.bounces = false;
        [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
            NSString *oldAgent = result;
            if ([oldAgent rangeOfString:@"kksh"].location !=NSNotFound) {
                return;
            }
            // 给User-Agent添加额外的信息
            NSString *newAgent = [NSString stringWithFormat:@"%@;%@", oldAgent, @"kksh"];

            // 设置global User-Agent
            if (@available(iOS 9.0, *)) {
                [self->_webView setCustomUserAgent:newAgent];
            }else{
                [self->_webView setValue:newAgent forKey:@"applicationNameForUserAgent"];
            }
        }];
    }
    return _webView;
}
#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 - 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 *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];
    
    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;
    [self.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            //NSLog(@"value图片: %@ error: %@", response, error);
        [wSelf PageJumpAction];
     }];
}

// 页面加载失败时调用
- (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;
    }
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
#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:@"shareUrl"]){
        self.shareDic = message.body;
        if ([self.shareDic[@"type"] isEqualToString:@"好友"]) {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
        }else if([self.shareDic[@"type"] isEqualToString:@"朋友圈"]){
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
        }
    }else if([message.name isEqualToString:@"finishThisPage"]){
        //返回
        [self.navigationController popViewControllerAnimated:YES];
    }else if([message.name isEqualToString:@"InvokeToApp"]){
        //调用原生
        [[clickEvent instance] clickEventRooterVC:self Content:message.body menuName:@""];
    }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:@"getLoginInfo"]){//获取登录信息
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]){
          
            NSDictionary* dic = @{
                @"id":@([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:@"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:@"showSaveQRAlertVC"]){
        //保存图片
        NSString*urlString = message.body;
       
       [self showSaveQRAlertVC:urlString];
    }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:@"forumLogin"]){
        //重新登录
       
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstlog"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"secondImage"];
        [getPeopleID getpeopleLimitedAuthority:NO];
        [getPeopleID socialSate:0];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
        
        //雷俊博退出时清除登录类型和账号密码
        [getPeopleID getLoginType:nil];
        [getPeopleID getLoginAccount:nil];
        [getPeopleID getLoginPassword:nil];
        [getPeopleID saveDefaultLoginAccount:nil];
        [getPeopleID saveDefaultLoginPassword:nil];
        [getPeopleID getTotalCoins:nil];
        [getPeopleID clearTotalCoins];
        [getPeopleID clearDefaultProvince];
        
        [getPeopleID saveAccountAuthWithState:NO];
        
        
        [PayUserInfoManager sharedManager].model = nil;
        
        
        //清除分享时间
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"shareLastTime"];
        //清除最近认证记录
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"ValidationDic"];
        //清除认证成功弹框时间
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"coinsauthenticationLastTime"];
        
        //清除走路赚金币领取时间
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"onFootCoinsDate"];
        
        
        [UserDefault setInteger:0 forKey:@"appleLoginState"];
        
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        //清除登录时间
        [getPeopleID saveLoginTime:nil];
        
        //[self deleterzUserTable];
        
        [self cleanCacheAndCookie];

        self.tabBarController.selectedIndex = 0;
        [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
    }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:@"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);
         }];
    }
}

#pragma mark - 未登录跳转
- (void)unLoginTap {
    [[NSNotificationCenter defaultCenter]postNotificationName:KKSBJumpLoginVCNotificationName object:nil];
}

#pragma mark - webview清楚缓存
- (void)cleanCacheAndCookie{
    
    // 获取
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        
        [cookieJar deleteCookie:cookie];
    
    }
   
}
- (void)showSaveQRAlertVC:(NSString *)imgUrl
{
    UIAlertController*alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确实是否要保存图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction*confirmAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
        UIImage* image = [UIImage imageWithData:data];
               
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    
    if (error) {
        [Tools showMessage:@"保存失败"];
    }else{
        [Tools showMessage:@"保存成功"];
    }
    
    [self.webView evaluateJavaScript:@"finGetImg('null')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value图片: %@ error: %@", response, error);
    }];
}
#pragma mark - 分享
//中奖分享
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    
    if (![WXApi isWXAppInstalled]) {
        [Tools showMessage:@"请先安装微信!!!"];
        return;
    }

    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareDic[@"title"] descr:self.shareDic[@"describe"] thumImage:self.shareDic[@"imageUrl"]];
        //设置网页地址
    NSString *url = self.shareDic[@"url"];
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        
    }];
}
/**
 *  字典转JSON字符串
 *
 *  @param dic 字典
 *
 *  @return JSON字符串
 */
- (NSString*) dictionaryToJson:(NSDictionary *)dic{
    NSString *json = nil;

    if ([NSJSONSerialization isValidJSONObject:dic]) {
      NSError *error;
      NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
      if(!error) {
          json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      }
      else {
          NSLog(@"JSON parse error: %@", error);
      }
    }else {
      NSLog(@"Not a valid JSON object: %@", dic);
    }
    return json;
}

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