//
//  ScrollMultipleWebView.m
//  vanke
//
//  Created by Z on 16/5/25.
//  Copyright © 2016年 gomore. All rights reserved.
//

#import "ScrollMultipleWebView.h"
#import <WebKit/WebKit.h>
#import "MBProgressHUD.h"
@interface ScrollMultipleWebView ()<WKNavigationDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) NSArray *arrUrls;
@property (nonatomic, strong) NSMutableArray *arrWebViews;
@property (nonatomic, strong) NSMutableArray *arrReqs;
@property (nonatomic, strong) NSMutableDictionary *dicFlag;
@property (nonatomic, strong) NSURLRequest *currentReq;
@property (nonatomic, strong) UIPageControl *pageCtrl;
@property (nonatomic, strong) NSMutableDictionary *dicRecords;
@property (nonatomic, assign) NSInteger currentIndex;







@end
@implementation ScrollMultipleWebView

- (instancetype)initWithFrame:(CGRect)frame webViewUrls:(NSArray *)arrUrls
{
    self = [super initWithFrame:frame];
    if (self) {
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        self.arrUrls = arrUrls;
        self.delegate = self;
        self.contentSize = CGSizeMake(arrUrls.count * width, 0);
        self.pagingEnabled = YES;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        for (int i = 0; i < arrUrls.count; i++) {
            
            NSString *jScript;
            if (SCREEN_WIDTH != 320) {
               jScript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, maximum-scale=2.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);";
            }else{
                jScript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=410, maximum-scale=2.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);";
            }
            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            WKUserContentController *wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];
            
            WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
            wkWebConfig.userContentController = wkUController;
            
            WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(i * width, 0, width, height)
                                                    configuration:wkWebConfig];
            webView.navigationDelegate = self;
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:arrUrls[i]]];
            [self.arrReqs addObject:request];
            [self.arrWebViews addObject:webView];
            if (i == 0){
                [self.dicRecords setObject:@1 forKey:request];
                [webView loadRequest:request];
                self.currentIndex = i;
                self.currentReq = request;
            };
            [self addSubview:webView];

        }
        
    }
    return self;
}

- (void)setPageControlBackgroundColor:(UIColor *)bgColor
{
    self.pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 20, self.superview.width, 20)];
    NSLog(@"superview.width = %f, screen.width = %f", self.superview.width,SCREEN_WIDTH);
    
    self.pageCtrl.numberOfPages = self.arrUrls.count;
    self.pageCtrl.currentPage = 0;
    self.pageCtrl.currentPageIndicatorTintColor = [UIColor colorWithWhite:0.500 alpha:0.407];
    self.pageCtrl.pageIndicatorTintColor = [UIColor grayColor];
    if (bgColor) {
        self.pageCtrl.backgroundColor = bgColor;
    }
    
    [self.superview addSubview:self.pageCtrl];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSInteger index = scrollView.contentOffset.x / SCREEN_WIDTH;
    self.pageCtrl.currentPage = index;
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.arrUrls[index]]];
    self.currentReq = req;
    self.currentIndex = index;
    if (![[self.dicRecords objectForKey:req] isEqualToNumber:@1]) {
        WKWebView *webView = self.arrWebViews[index];
        
        [self changeWebView:webView request:req];
    }
    
}

- (void)updateUrls:(NSArray *)arrUrls{
    self.arrUrls = arrUrls;
    [self.dicRecords removeAllObjects];
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:arrUrls[self.currentIndex]]];
    WKWebView *webView = self.arrWebViews[self.currentIndex];
    
    [self changeWebView:webView request:req];
}

- (void)changeWebView:(WKWebView *)webView request:(NSURLRequest *)req
{
    [UIView animateWithDuration:0.2 animations:^{
        webView.alpha = 0;
    } completion:^(BOOL finished) {
        webView.hidden = YES;
        [webView loadRequest:req];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            webView.hidden = NO;
            [UIView animateWithDuration:0.2 animations:^{
                webView.alpha = 1;
            }];
        });
        [self.dicRecords setObject:@1 forKey:req];
    }];
}

#pragma mark - wkwebview delegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [MBProgressHUD showHUDAddedTo:webView animated:YES];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [MBProgressHUD hideHUDForView:webView animated:YES];
}

#pragma mark - lazyloading

- (NSMutableArray *)arrWebViews {
    if (!_arrWebViews) {
        _arrWebViews = [NSMutableArray array];
    }
    return _arrWebViews;
}

- (NSMutableArray *)arrReqs {
    if (!_arrReqs) {
        _arrReqs = [NSMutableArray array];
    }
    return _arrReqs;
}
- (NSMutableDictionary *)dicFlag {
    if (!_dicFlag) {
        _dicFlag = [NSMutableDictionary dictionary];
    }
    return _dicFlag;
}

- (NSMutableDictionary *)dicRecords {
    if (!_dicRecords) {
        _dicRecords = [NSMutableDictionary dictionary];
    }
    return _dicRecords;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
