//
//  CustomWKWebViewController.m
//  Lighting
//
//  Created by 曹云霄 on 16/5/17.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "CustomWKWebViewController.h"
#import <WebKit/WebKit.h>

@interface CustomWKWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler,UIScrollViewDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) WKWebViewConfiguration *config;
@property (nonatomic,strong) UIButton *dismissButton;

@end

@implementation CustomWKWebViewController

#pragma mark - lazy
- (WKWebViewConfiguration *)config
{
    if (!_config) {
        _config = [[WKWebViewConfiguration alloc]init];
        // 设置偏好设置
        _config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        _config.preferences.minimumFontSize = 10;
        // 默认认为YES
        _config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        _config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        // 通过JS与webview内容交互
        _config.userContentController = [[WKUserContentController alloc] init];
        [_config.userContentController addScriptMessageHandler:self name:@"AppModel"];
        [_config.userContentController addScriptMessageHandler:self name:@"appShare"];
    }
    return _config;
}

- (WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:self.config];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        _webView.scrollView.delegate = self;
        [self.view insertSubview:_webView atIndex:0];
    }
    return _webView;
}

#pragma mark - 停止播放
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self determineTheURLFileType];
    [self addDismissButton];
}

#pragma mark - 判断加载文件类型
- (void)determineTheURLFileType
{
    [self loadURLfileAction];
}

#pragma mark - 加载URL
- (void)loadURLfileAction
{
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        NSLog(@"清理缓存成功");
    }];
}

#pragma mark - 数据
- (void)setUrlString:(NSString *)urlString
{
    _urlString = urlString;
    if (self.type == Image) {
       [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:urlString]]];
    }else {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
    }
}

#pragma mark - 添加关闭按钮
- (void)addDismissButton
{
    self.dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.dismissButton];
    [self.dismissButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(40);
        make.top.mas_equalTo(40);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    [self.dismissButton setBackgroundImage:TCImage(@"1") forState:UIControlStateNormal];
    [self.dismissButton addTarget:self action:@selector(dismissButtonClick) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //抽奖结果
    if ([message.name isEqualToString:@"AppModel"]) {
        // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
       id json = [NSJSONSerialization JSONObjectWithData:[message.body[@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        if (json) {
            if ([json isKindOfClass:[NSDictionary class]]) {
                NSDictionary *resultDict = (NSDictionary *)json;
                if ([[resultDict allKeys] containsObject:@"click"]) {
                    self.dismissButton.enabled = NO;
                }else {
                    self.dismissButton.enabled = YES;
                    if (self.luckyDrawFinishBlock) {
                        self.luckyDrawFinishBlock(resultDict);
                    }
                }
            }
        }
    }else if ([message.name isEqualToString:@"appShare"]) {
        //体验中心3D分享
        NSString *imgUrl = message.body[@"imgUrl"];
        NSString *panoUrl = message.body[@"panoUrl"];
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        messageObject.text = @"欧立方一键分享";
        if ([[self class] isBlankString:panoUrl]) {
            UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
            [shareObject setShareImage:imgUrl];
            messageObject.shareObject = shareObject;
        }else {
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"欧立方体验中心3D分享" descr:nil thumImage:[UIImage imageNamed:@"shareIcon"]];
            shareObject.webpageUrl = panoUrl;
            messageObject.shareObject = shareObject;
        }
        [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                ShowAlertView(@"提示", @"分享失败", @[@"我知道了"], UIAlertControllerStyleAlert, nil);
            }else{
                [XBLoadingView showHUDViewWithSuccessText:@"分享微信朋友圈成功" completeBlock:nil];
            }
        }];
    }
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark -dismiss
- (void)dismissButtonClick
{
    WS(weakSelf);
    [self dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.dismissLuckyDrawController) {
            weakSelf.dismissLuckyDrawController();
        }
    }];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    [XBLoadingView showHUDViewWithDefaultWithView:self.view];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [XBLoadingView hideHUDViewWithDefaultWithView:self.view];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [XBLoadingView hideHUDViewWithDefaultWithView:self.view];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat height = scrollView.frame.size.height;
    CGFloat contentYoffset = scrollView.contentOffset.y;
    CGFloat distanceFromBottom = scrollView.contentSize.height - contentYoffset;
    WS(weakSelf);
    if (distanceFromBottom <= height && self.type == Study) {
        ShowAlertView(@"提示", @"学习完成，是否开始考核？", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            if (index == ONE) {
                return;
            }
            if (weakSelf.scrollViewEndBottomBlock) {
                weakSelf.scrollViewEndBottomBlock(weakSelf.indexPath);
            }
        });
    }
}




@end
