//
//  XXX_BaseWebC.m
//  westkissMob
//
//  Created by 王猛 on 2022/10/13.
//

#import "XXX_BaseWebC.h"
#import "DsJsInteractAPI.h"
#import "TT_ProgressV.h"
#import "UIDevice+StateHeight.h"
#import "NSString+URL.h"

@interface XXX_BaseWebC () 
@property (nonatomic, strong) TT_ProgressV *wkweb_pv;

@end

@implementation XXX_BaseWebC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if(isValid(self.webTitle)){
        self.title = self.webTitle;

    }
    if(self.isPayType == YES){
        [self present_confignavBarBar];
    }
    
    [self tt_addSubviews];
}

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


- (void)present_confignavBarBar{
    self.navigationController.navigationBar.hidden = YES;
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[UIImage imageNamed:@"base_close_black"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(xxx_closeVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
    NSInteger top = IPHONEX ? 44 : 20;
    closeBtn.frame = CGRectMake((KScreenWidth -44)/2, top, 44, 44);
}
-(void)xxx_closeVC{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)tt_addSubviews{    
    [self.view addSubview:self.dwebview];
    [self.view addSubview:self.wkweb_pv];
    //wm_todo 如果web加载失败的， self.dwebview.estimatedProgress 不存在
//    [self.dwebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    [self web_pvframeis_Hide:YES];
}
-(void)xxx_dsWebLoadUrl:(NSString *)url{
    [self.dwebview loadUrl:url];
}

-(DWKWebView *)dwebview{
    IPhoneXHeigh
    if(!_dwebview){
        _dwebview = [[DWKWebView alloc]initWithFrame:CGRectMake(0, securitytop_Y, KScreenWidth, securityNew_H)];
        _dwebview.navigationDelegate =self;

    }
    return _dwebview;
}
#pragma mark - ****************公开方法  ****************

-(void)tool_dsWebViewAddJS{
    DsJsInteractAPI *apiObject = [[DsJsInteractAPI alloc]init];
    [self.dwebview addJavascriptObject:apiObject namespace:nil];
    apiObject.dsWebC = self;
}


//添加web加载的进度条
- (TT_ProgressV *)wkweb_pv {
    if (!_wkweb_pv) {
        _wkweb_pv = [[TT_ProgressV alloc]initWithFrame:CGRectMake(0, [UIDevice vg_navigationFullHeight], KScreenWidth, 5)];
        _wkweb_pv.ColosArray = [NSArray arrayWithObjects:(id)[UIColor qmui_colorWithHexString:@"#FFDEE2"].CGColor,(id)[UIColor qmui_colorWithHexString:@"#e60013"].CGColor,nil];
    }
    return _wkweb_pv;
}
- (void)dealloc {//销毁KVO监听
//    [self.dwebview removeObserver:self forKeyPath:@"estimatedProgress" context:nil];
}

#pragma mark - **************** WKNavigationDelegate ****************

/// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self web_pvframeis_Hide:NO];
    
    if (self.isPayType) {
        [self loadEndWithUrl:webView.URL];
    }
}
///页面加载完成时调用
-(void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{
    [self web_pvframeis_Hide:NO];

    if (self.isPayType) {
        [self loadEndWithUrl:webView.URL];
    }
}

- (void)loadEndWithUrl:(NSURL *)webUrl {
    
    NSString *urlStr = [webUrl absoluteString];
    
    NSLog(@"urlStrurlStr======%@", urlStr);
    NSLog(@"webUrl.query======%@", webUrl.query);
    
    if ([urlStr containsString:@"rest/V1/rewrite/paypal/cancel"]) {
        // 取消paypal支付
        
        NSDictionary *cancelDic = @{@"title":@"Cancel Pay"};
        
        if (self.WebViewBlock) {
            self.WebViewBlock(0, cancelDic);
        }
        
        [self tool_PopViewController];
        
    } else if ([urlStr containsString:@"rest/V1/rewrite/paypal/return"]){
        
        NSDictionary *successDic = [webUrl.query getURLParameters];
        
        if (self.WebViewBlock) {
            self.WebViewBlock(1, successDic);
        }
        
        [self tool_PopViewController];
        
    }
    
//
    
    
    
    
    
    
}

#pragma mark - **************** wkweb_pv ****************
///KVO estimatedProgress 网络状态栏加载进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
   if ([keyPath isEqualToString:@"estimatedProgress"]){
        if (self.dwebview.estimatedProgress == 1) {
            [self web_pvframeis_Hide:NO];
        }else {
          [self.wkweb_pv animationWith:self.dwebview.estimatedProgress];
        }
   }else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}
- (void)web_pvframeis_Hide:(BOOL)YorN {
    CGFloat Y;
    
    if (YorN) {
        Y = [UIDevice vg_navigationFullHeight];
//        self.dwebview.alpha = 0;
    }else{
//        self.dwebview.alpha = 1;
        Y = -200;
    }
    self.wkweb_pv.frame =  CGRectMake(0, Y, KScreenWidth, 5);
    
}


-(void)webJs_onClose{
    @weakify(self)
    [self.dwebview callHandler:@"onClose" completionHandler:^(id  _Nullable value) {
        NSLog(@"onClose ---- value：%@",value);///exits
     @strongify(self)
//        if(isValid(value)){
//            [self tool_closeSaveValue:value];
//        }
        [self tool_PopViewController];
    } ];
}

- (void)tool_PopViewController{
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count == 1) {
            if (self.presentingViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if(self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}



@end
