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

#import "SurplusmVC.h"
#import <WebKit/WebKit.h>
#import "WeakWebViewScriptMessageDelegate.h"
@interface SurplusmVC ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong)WKWebView *webView;

@end

@implementation SurplusmVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0xFB7C23] image:nil isOpaque:YES];//颜色
    
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    
    [NetworkRequest statisticsWithEventName:@"dialog_Surplusm"];
}
- (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 getChangLiangUrlRequest];
    
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.10.163:8080/#/?uid=%ldtel=%@",(long)[getPeopleID PeopleID],[getPeopleID PeopleIphoneNmber]]]];

//    [self.webView loadRequest:request];
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor colorWithHex:0xFB7C23];
    [self.view addSubview:navView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 50, 25);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateHighlighted];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitle:@"返回" forState:UIControlStateHighlighted];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    

    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}
#pragma mark - WKNavigationDelegate
//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:页面开始加载");
}
//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"WebVC:内容开始返回");
    
   
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    NSLog(@"WebVC:页面加载完成");
}

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

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

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

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

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

#pragma mark - WKScriptMessageHandler
//被自定义的WKScriptMessageHandler在回调方法里通过代理回调回来，绕了一圈就是为了解决内存不释放的问题
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    if ([message.name isEqualToString:@"openUrl"]){
        NSArray *array = message.body;
        if ([array isKindOfClass:[NSArray class]]) {
            if (array.count == 2) {
                WebVC *webvc = [[WebVC alloc]init];
                webvc.url = array[1];
                webvc.title = array[0];
                webvc.fromName = self.title;
                webvc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webvc animated:YES];
            }
        }
    }else if ([message.name isEqualToString:@"showSaveQRAlertVC"]){
        NSString*urlString = message.body;
       
       [self showSaveQRAlertVC:urlString];
    }else if([message.name isEqualToString:@"InvokeToApp"]){
        //调用原生
        [[clickEvent instance] clickEventRooterVC:self Content:message.body menuName:@""];
    }
}
- (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 - event response
- (void)backClick:(UIButton *)sender {
    if (self.fromHome) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.tabBarController.navigationController popViewControllerAnimated:YES];
    }
}
- (void)taskBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


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

    if ([NSJSONSerialization isValidJSONObject:dic]) {


      NSError *error;

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

      if(!error) {

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

      }

      else {

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

      }
    }

    else {

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

    return json;
}
- (WKWebView *)webView
{
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        config.allowsInlineMediaPlayback = YES;
        config.allowsPictureInPictureMediaPlayback = 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:@"kkshHelper"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"openUrl"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"showSaveQRAlertVC"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"InvokeToApp"];
        config.userContentController = wkUController;
//        - (_fromHome ? 0 : cl_kTabBarHeight
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - cl_kTabBarHeight) configuration:config];
        if (_fromHome) {
            _webView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight);
        }else{
            _webView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - cl_kTabBarHeight);
        }
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.scrollView.bounces = false;
 
    }
    return _webView;
}
#pragma mark - 盈米基金
- (void)getChangLiangUrlRequest
{
//    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:@"%@dynamic/menu/get",[NetworkConfig ipYinShuConfig]];
//    NSString *url = [NSString stringWithFormat:@"%@dynamic/menu/get",@"http://172.16.10.18:8017/"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *params = @{
        @"configName":@"YingMiJiJin",
        @"appName":@"kksh",
        @"version":[app_Version stringByReplacingOccurrencesOfString:@"." withString:@""],
        @"systemType":@"iOS"
    };
    //[KKLoadingAnimationView show];
    [NetworkRequest Post15:url Params:params Success:^(id _Nonnull objc) {
        //[KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSArray *array = objc[@"result"];
                if ([array isKindOfClass:[NSArray class]] && array.count > 0) {
                    NSDictionary *dic = (NSDictionary *)array[0];
                    if ([dic isKindOfClass:[NSDictionary class]]) {
                        NSString *url = dic[@"content"];
                        [self getFederatedLoginRequestWithUrl:url];
                    }
                }
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
        //[KKLoadingAnimationView dismiss];
        
    }];
}
#pragma mark - 获取联合登录链接
- (void)getFederatedLoginRequestWithUrl:(NSString *)Url
{
    NSString *url = [NSString stringWithFormat:@"%@",Url];
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    
    NSDictionary *params = @{
        @"uid":@([getPeopleID PeopleID]),
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    [KKLoadingAnimationView show];
    [NetworkRequest Get: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"]) {
            self.url = [NSString stringWithFormat:@"%@",objc[@"result"]];
            [self loadExamplePage:self.webView];
            
        }else{
            [self alertShowMessage:describe];
        }
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShowMessage:@"网络异常"];
    }];
    
}
#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];
    }
}
- (void)loadExamplePage:(WKWebView*)webView {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];

    [self.webView loadRequest:request];
}
@end
