//
//  WMDiaryAndTopicBaseController.m
//  ZhengXing
//
//  Created by wangyang on 3/5/15.
//  Copyright (c) 2015 Wanmei Creative. All rights reserved.
//

#import "WMBaseWebViewController.h"
#import "AppDelegate+AppInit.h"
#import "UIViewController+UrlScheme.h"
#import "Alpha-Swift.h"
#import "WMBaseViewController+OCNavigationBar.h"
#import <mach/mach_time.h>
#import "GMCookieManager.h"

//#import "GMAnswerQuestionView.h"

@interface WMBaseWebViewController ()<WKWebViewDelegate>
@property (nonatomic, assign) CGFloat animationDistance;
@end

@implementation WMBaseWebViewController

- (GMWebViewComponent *)webCompent {
    if (!_webCompent) {
        _webCompent = [GMWebViewComponent new];
        _webCompent.delegate = self;
    }
    if (!_webCompent.superview) {
        [self.view addSubview:_webCompent];
    }
    return _webCompent;
}


- (void)initController{
    [super initController];
}

- (void)webViewLoadRequest {
    if (self.fullURL == nil || [self.fullURL isEqualToString:@""]) {
        return;
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    self.webCompent.fullUrl = self.fullURL;
    [self.webCompent webviewLoad:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    CGFloat top = self.navigationBar.height;
    [self.webCompent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(top);
        make.bottom.mas_equalTo(0);
    }];
    
    // 设置Agent，关键字是最后的那个Gengmei，这样服务端就知道是通过app内部加载网页。
    NSDictionary *dictionary = USER_AGENT_DIC;
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
    // 加载URL
    [self reloadURL];
}

- (void)reloadURL {
    
    [self handleURL];
    [self webViewLoadRequest];
}

#pragma mark - Handle URL
/**
 不允许重写
 */
- (void)handleURL {
    
    if (_fullURL.length == 0) {
        // 使用path拼接，并且加上query
        _fullURL = [self wrapWebUrlWithPath];
    }else{
        // 为fullURL加上默认query
        _fullURL = [self wrapWebUrlWithFullURL];
    }
    
    if (![_fullURL isNonEmpty]) return;
    
    // 额外的参数
    _fullURL = [_fullURL stringByAppendingString:[self moreQueryParameters]];
    
    self.webCompent.fullUrl = _fullURL;
}

/**
 不允许重写
 */
- (NSString *)wrapWebUrlWithPath{
    
    if (![_path isNonEmpty]) {
        return @"";
    }
    NSString *wrapedUrl = [NSString stringWithFormat:@"%@%@%@", GMServerDomains.apiHost, self.path,GMNetworking.urlCommonParameters];
    return wrapedUrl;
}

/**
 不允许重写
 */
- (NSString *)wrapWebUrlWithFullURL{
    
    // 因为有的 fullURL 带了一部分 query，而将要拼接的urlCommonParameters还带了一个问号，所以要做判断
    NSString *defaultQuery = GMNetworking.urlCommonParameters;
    if ([_fullURL rangeOfString:@"?"].length > 0) {
        defaultQuery = [defaultQuery stringByReplacingOccurrencesOfString:@"?" withString:@"&"];
    }
    
    NSString *wrapedUrl = [NSString stringWithFormat:@"%@%@", _fullURL, defaultQuery];
    
    return wrapedUrl;
}

- (NSString *)moreQueryParameters{
    return @"";
}

- (void)refreshWebView {
    
    //自己本地调用webview刷新时候,绑定关系还存在,不需要重新绑定GMClient和window上的方法.
    [self.webCompent reload];
}

#pragma mark - js
- (void)jsShowLoading{
    [GMHudModule showLoading:nil];
}

- (void)jsHideLoading{
    [GMHudModule hideLoading];
}

- (void)jsCallPhone:(NSString *)phone {
    NSString *phoneStr = [NSString stringWithFormat:@"tel:%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: phoneStr]];
}

- (void)jsSetLocalStorage:(NSString *)key withStorage:(NSString *)value {
    if (![value isNonEmpty]) {
        value = @"";
    }
    [GMCache storeObjectAtDocumentPathWithkey:key object:value];
}

- (NSString *)jsGetLocalStorage:(NSString *)key {
    NSString *cacheKey = [GMCache fetchObjectAtDocumentPathWithkey:key];
    if (![cacheKey isNonEmpty]) {
        return  @"";
    }
    return cacheKey;
}

- (void)jsSyncSSOInfo:(NSString *)jsonString {
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    if (info[@"user_id"] != nil) {
        [[GMLoginManager shareInstance] loginSuccessWithUserInfo:info shouldBroadcast:NO];
    }

    if (info[@"cookie"] != nil && info[@"domain"] != nil) {
        [GMCookieManager saveSessionId:info[@"cookie"] domain:info[@"domain"]];
    }
}

- (void)globalDataLoaded:(NSDictionary *)data {
    
    [self trackEventGlobalPage:data];
}

- (void)globalPageData:(NSDictionary *)data {
    
    [self trackEventGlobalPage:data];
}

// PageView
- (void)trackEventGlobalPage:(NSDictionary *)data {
    
    if ([self data:data containsKey:@"page_name"]) {
        self.pageName = SafeString(data[@"page_name"]);
    }
    if ([self data:data containsKey:@"business_id"]) {
        self.businessId = SafeString(data[@"business_id"]);
    }
    
    BOOL isNavigationAlpha = [data[@"hide_navigation_shadow"] boolValue];
    if (isNavigationAlpha) {
        self.navigationBar.isShowShadow = NO;
        self.animationDistance = [data[@"header_height"] floatValue] - OCNavigationBar.barHeight;
    } else {
        self.navigationBar.isShowShadow = !isNavigationAlpha;
    }
}

- (BOOL)data:(NSDictionary *)data containsKey:(NSString *)key {
    if ([data.allKeys containsObject:key] && [SafeString(data[key]) isNonEmpty] ) {
        return YES;
    }
    return NO;
}
#pragma mark - 重写
#pragma mark - 导航栏按键响应
- (void)rightButtonClicked:(OCNavigationBarButton *)button{
    [super rightButtonClicked:button];

    // 隐藏键盘，避免不必要的bug发生
    [self.view endEditing:YES];
}

#pragma mark - UIWebViewDelegate
/**
 *  @author wangyang, 16-01-07 11:01:02
 *
 *  @brief 因为有一些controller不继承baseWebView，但是的确有一些controller有webview的，并且还要能够处理更美协议，所以把这个移动到了这里。比如圈子详情页
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    // 拦截scheme为alpha时，是javascript要调用native代码
    if ([[request.URL scheme] isEqualToString:@"alpha"]) {
        // Host
        NSString *host = [[request.URL host] trimBothEnd];
        // 取得参数
        NSDictionary *parameters = [request.URL.absoluteString urlQueryToDictionary];
        [self handleLinkTapWithUrl:request.URL.absoluteString withHost:host withParams:parameters];
    } 
    return YES;
}

/**
 *  @brief  父类处理H5页面的点击链接后跳转页面的逻辑,其它非跳转性逻辑需要子类来写
 *
 *  @param url
 *  @param host
 *  @param param
 */
- (void)handleLinkTapWithUrl:(NSString *)url withHost:(NSString *)host withParams:(NSDictionary *)param{
    if(host && [[self getHostDictionary] objectForKey:host]){
        [self pushScheme:url];
    }
}

- (void)webViewDidFinishLoad:(UIWebView*)webView {
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [GMHudModule hideLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
    [GMHudModule hideLoading];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    if ([error code] != NSURLErrorCancelled){
        [GMHudModule showWarning:@"加载失败，请重试"];
    }
}

- (void)dealloc{
    
    // 在某些情况下，如果controller先dealloc了，会导致webView找不到delegate而crash。例如修复jspatch与webview冲突时就会遇到。
    // 复现步骤：先注释以下代码，再push到一个webController，加载时立即后退，等待，然后crash，提示 “webView:identifierForInitialRequest:fromDataSource”
//    self.webView.delegate = nil;
//    [self.webView stopLoading];
}

@end
