//
//  ACWebPlusJSBridge.m
//  iOSJSBridgeDemo
//
//  Created by 罗坚(EX-LUOJIAN004) on 2018/5/21.
//  Copyright © 2018年 罗坚(EX-LUOJIAN004). All rights reserved.
//

#import "ACWebPlusJSBridge.h"
#import "UIColor+AppCore.h"
#import "UIViewController+AppCorePopOn.h"
#import "YYPhotoBrowseView.h"
#import "ACBridgeUtil.h"

typedef enum : NSUInteger {
    ACBarButtonTypeText,
    ACBarButtonTypeImage,
} ACBarButtonType;

#define RightBarButtonStartTag 10000

@interface ACWebPlusJSBridge () <AppCoreBackButtonHandlerProtocol>
{
    dispatch_queue_t queue;
}

@property (nonatomic, assign) BOOL isPreviewImageOn;
@property (nonatomic, strong) NSString *backListenerStr;
@property (nonatomic, strong) NSMutableDictionary *rightBarBtnListenerDic;
@property (nonatomic, strong) NSMutableArray *adaptButtonInfoAr;

@end

@implementation ACWebPlusJSBridge

- (id)init
{
    if ([super init]) {
        self.isPreviewImageOn = YES;
    }
    return self;
}

- (void)initHandles
{
    __weak typeof(self) ws = self;
    
    [self registerHandler:@"setNav" handler:^(id webView, ACMessage *msg) {
        NSDictionary *backButtonDic = msg.dataDic[@"backButtonInfo"];
        NSDictionary *titleDic = msg.dataDic[@"titleInfo"];
        NSArray *buttonInfoAr = msg.dataDic[@"rightButtons"];
        NSString *bgColorStr = msg.dataDic[@"bgColor"];
        NSString *isHiddenStr = msg.dataDic[@"isHidden"];

        // 背景色
        if (bgColorStr) {
            UIColor *color = [UIColor ac_colorWithCSS:bgColorStr];
            if (color) {
                UINavigationBar * bar = ws.vc.navigationController.navigationBar;
                [bar setBarTintColor:color];
            }
        }
        // 隐藏
        if (isHiddenStr) {
            ws.vc.navigationController.navigationBarHidden = [isHiddenStr boolValue];
        }
        // 标题
        if (titleDic) {
            NSString *nameStr = titleDic[@"title"];
            NSString *colorStr = titleDic[@"titleColor"];
            if (nameStr) {
                ws.vc.title = nameStr;
            }
            if (colorStr) {
                UIColor *color = [UIColor ac_colorWithCSS:colorStr];
                if (color) {
                    //导航栏字体的颜色
                    ws.vc.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:color};
                }
            }
        }
        // 右边按钮
        if (buttonInfoAr) {
            [ws showRightBarButtons:buttonInfoAr];
        }
        // 返回按钮
        if (backButtonDic) {
            NSString *backButtonListenerStr = backButtonDic[@"clickListener"];
            if (backButtonListenerStr) {
                if ([backButtonListenerStr length]) {
                    self.vc.popDelegate = self;
                    self.backListenerStr = backButtonListenerStr;
                }
                else {
                    self.vc.popDelegate = nil;
                    self.backListenerStr = nil;
                }
            }
        }
        return msg;
    }];
    
    [self registerHandler:@"back" handler:^(id webView, ACMessage *msg) {
        [ws.vc.navigationController popViewControllerAnimated:YES];
        
        return msg;
    }];
    
    // 图片是否可点击
    [self registerHandler:@"setPreviewImage" handler:^(id webView, ACMessage *msg) {
        NSString *isPreviewImageOnStr = msg.dataDic[@"isEnabled"];
        if ([isPreviewImageOnStr length]) {
            self.isPreviewImageOn = [isPreviewImageOnStr boolValue];
        }
        
        return msg;
    }];
}

- (void)showRightBarButtons:(NSArray *)buttonInfoAr
{
    __weak typeof(self) ws = self;
    queue = dispatch_queue_create("com.appcore.webplus.rightbarbuttonimages", DISPATCH_QUEUE_CONCURRENT);
    
    [ws.adaptButtonInfoAr removeAllObjects];
    for (int i = 0; i< [buttonInfoAr count]; i++) {
        NSDictionary *buttonInfoDic = buttonInfoAr[i];
        NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
        [buttonInfoDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [newDic setObject:obj forKey:key];
        }];
        
        __weak NSMutableDictionary *weakDic = newDic;
        NSString *imageNameStr = buttonInfoDic[@"imageName"];
        NSString *imageURLStr = buttonInfoDic[@"imageURL"];
        if ([imageURLStr length]) {
            dispatch_async(queue, ^{
                UIImage *image = nil;
                NSError *error;
                NSURL *url = [NSURL URLWithString:imageURLStr];
                NSData *imageData = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error];
                image = [UIImage imageWithData:imageData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (weakDic) {
                        weakDic[@"image"] = image;
                    }
                });
            });
        }
        else if ([imageNameStr length]) {
            newDic[@"image"] = [UIImage imageNamed:imageNameStr];
        }
        [ws.adaptButtonInfoAr addObject:newDic];
    }
    
    dispatch_barrier_async(queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableArray *btnAr = [NSMutableArray new];
            for (NSDictionary *btnDic in ws.adaptButtonInfoAr) {
                NSString *nameStr = btnDic[@"title"];
                NSString *colorStr = btnDic[@"titleColor"];
                NSString *imageNameStr = btnDic[@"imageName"];
                NSString *imageURLStr = btnDic[@"imageURL"];
                NSString *enabledStr = btnDic[@"isEnabled"];
                NSString *listenerStr = btnDic[@"clickListener"];
                UIImage *image = btnDic[@"image"];
                
                UIBarButtonItem *btn = nil;
                if ([imageNameStr length] || [imageURLStr length]) {
                    if (image) {
                        btn = [[UIBarButtonItem alloc] initWithImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarBtnAction:)];
                    }
                    else {
                        continue;
                    }
                }
                else {
                    btn = [[UIBarButtonItem alloc] initWithTitle:nameStr style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarBtnAction:)];
                    if (colorStr) {
                        UIColor *color = [UIColor ac_colorWithCSS:colorStr];
                        if (color) {
                            [btn setTintColor:color];
                        }
                    }
                }
                
                if ([enabledStr length]) {
                    btn.enabled = [enabledStr boolValue];
                }
                btn.tag = RightBarButtonStartTag+[self.adaptButtonInfoAr indexOfObject:btnDic];
                ws.rightBarBtnListenerDic[[NSString stringWithFormat:@"%d",(int)btn.tag]] = listenerStr;
//                UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//                negativeSpacer.width = -20.f;
//                [btnAr insertObject:negativeSpacer atIndex:0];
                [btnAr insertObject:btn atIndex:0];
            }
            if ([btnAr count] == 0) {
                ws.vc.navigationItem.rightBarButtonItem = nil;
                ws.vc.navigationItem.rightBarButtonItems = nil;
            }
            else {
                ws.vc.navigationItem.rightBarButtonItem = nil;
                ws.vc.navigationItem.rightBarButtonItems = btnAr;
            }
        });
    });
}

- (void)clickRightBarBtnAction:(UIBarButtonItem *)btn
{
    int tag = (int)btn.tag;
    NSString *listenerStr = self.rightBarBtnListenerDic[[NSString stringWithFormat:@"%d",tag]];
    if ([listenerStr length]) {
        [ACBridgeUtil webView:self.webView callJsWithString:[NSString stringWithFormat:@"%@()",listenerStr]];
    }
}

- (void)previewPictureImage:(NSString *)src
{
    BOOL isPreviewImageOn = self.isPreviewImageOn;
    if (isPreviewImageOn == NO) {
        return;
    }
    
    NSInteger currentIndex = 0;
    NSMutableArray *items = [NSMutableArray array];
    NSMutableArray *imageViews = @[].mutableCopy;
    UIView *fromView = nil;
    NSArray *imgSrcArray = self.imageAr;
    for (NSInteger i = 0; i < imgSrcArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.center = ((UIWebView *)self.webView).center;
        [imageViews addObject:imageView];

        NSString *path = imgSrcArray[i];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        NSURL *url = [NSURL URLWithString:imgSrcArray[i]];
        item.thumbView = imageView;
        item.largeImageURL = url;
        [items addObject:item];
        if ([path isEqualToString:src]) {
            currentIndex = i;
        }
        fromView = imageViews[currentIndex];
    }
    YYPhotoBrowseView *groupView = [[YYPhotoBrowseView alloc]initWithGroupItems:items];
    [groupView presentFromImageView:fromView toContainer:self.vc.navigationController.view animated:YES completion:nil];
}

- (BOOL)appCore_navigationShouldPopOnBackButton
{
    if ([self.backListenerStr length]) {
        [ACBridgeUtil webView:self.webView callJsWithString:[NSString stringWithFormat:@"%@()",self.backListenerStr]];
    }
    return NO;
}

#pragma mark - getter and setter

- (NSArray<NSString *> *)imageAr
{
    if (_imageAr == nil) {
        _imageAr = [[NSMutableArray alloc] initWithCapacity:5];
    }
    return _imageAr;
}

- (NSMutableDictionary *)rightBarBtnListenerDic
{
    if (_rightBarBtnListenerDic == nil) {
        _rightBarBtnListenerDic = [NSMutableDictionary new];
    }
    return _rightBarBtnListenerDic;
}

- (NSMutableArray *)adaptButtonInfoAr
{
    if (_adaptButtonInfoAr == nil) {
        _adaptButtonInfoAr = [NSMutableArray new];
    }
    return _adaptButtonInfoAr;
}

@end
