//
//  TYWebViewController.m
//  CZBWebProjectDemoForOC
//
//  Created by 边智峰 on 2018/11/14.
//  Copyright © 2018 czb365.com. All rights reserved.
//

#import "TYWebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <WebKit/WebKit.h>
#import "CZBInfoManager.h"
//applinks:kklife.weface.com.cn
static NSString *redirectScheme = @"msdev.czb365.com";

@interface TYWebViewController () <WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, copy) NSString * endPayRedirectURL;

/**
 是否设置过userAgent
 */
@property (nonatomic, assign) BOOL isSetUserAgent;
@end

@implementation TYWebViewController

- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
    }
    return _webView;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self navConfig];
    
    [self prepareUI];
    [self prepareWebview];
    
    [self.webView addObserver:self forKeyPath: @"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath: @"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    
    _endPayRedirectURL = @"";
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 50, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn 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];
    [backBtn addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    

    //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 = @"团油";
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}
- (void)prepareUI {
    self.webView.allowsBackForwardNavigationGestures = true;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
//    NSInteger statusH = [UIApplication sharedApplication].statusBarFrame.size.height;
    self.webView.frame = CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight);
    [self.view addSubview:self.webView];
}
- (void)buttonClick_1{
    if (self.webView.canGoBack==YES) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)prepareWebview {
    
    NSURL *url = [NSURL URLWithString:self.url];
    
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
    if (@available(iOS 9.0, *)) {
//        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//
//        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        
//        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
//
//        }];
    } else {
        // Fallback on earlier versions
    }
    /// 设置UA
    if (!self.isSetUserAgent) {

        [CZBInfoManager setUserAgent:@"CZBIOS" webView:self.webView completion:^{
            [self.webView loadRequest:req];
            self.isSetUserAgent = true;
        }];
        
    } else {
        [self.webView loadRequest:req];
    }

    ////////////////************************* 需执行注册事件
    [CZBInfoManager registerWebView: self.webView];
   
    /////************************************************
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"]) {
        self.navigationItem.title = self.webView.title;
    } else if ([keyPath isEqualToString: @"canGoBack"]) {
        [self goBackStateChanged];
    }
}

- (void)goBackStateChanged {
    if (self.navigationItem.leftBarButtonItem == nil) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(webViewGoBack)];
    }
}

- (void)webViewGoBack {
    if ([self.webView canGoBack] == true) {
        [self.webView goBack];
    } else {
        /// 重新LoadRequest 不要重复注册Js交互事件
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
}
///WebViewDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"最新的加载请求: === %@", navigationAction.request.URL.absoluteString);
    NSString *url = navigationAction.request.URL.absoluteString;
    
    if ([url hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![url hasSuffix:@"redirect_url=msdev.czb365.com://"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        
        if ([url containsString:@"redirect_url="]) {
            NSArray *arr = [url componentsSeparatedByString:@"redirect_url="];
            url = [arr firstObject];
            _endPayRedirectURL = [arr lastObject];
            url = [url stringByAppendingFormat:@"redirect_url=msdev.czb365.com://"];
        } else {
            url = [url stringByAppendingFormat:@"redirect_url=msdev.czb365.com://"];
        }
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
        request.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
        [webView loadRequest:request];
        
        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);
    ////////////////************************* 处理请求
}

-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:true completion:nil];
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
}
@end
