//
//  GMGeneMemoryResultViewController.m
//  Gengmei
//
//  Created by 朱璇 on 2019/12/6.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

#import "GMGeneMemoryResultViewController.h"
#import "ALShareSheet.h"

@interface GMGeneMemoryResultViewController ()<WKWebViewDelegate, GMClientH5BridgeDelegate>
@property (nonatomic, strong) NSDictionary *dataDict;
@property (nonatomic, strong) UIImage *shareImage; // 前端传递过来的图片
@property (nonatomic, strong) GMImageView *shareImageView; // 分享展示的图片
@property (nonatomic, strong) ALShareSheet *shareSheet; // 分享弹出框
@property (nonatomic, copy) NSString *imUrl;
@end

@implementation GMGeneMemoryResultViewController

- (void)initController {
    [super initController];
//    self.pageName = @"face_institute_report";
    self.navigationBar.backgroundColor = UIColor.clearColor;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self preferredStatusBarStyle];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UIApplication sharedApplication].statusBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.controlNavigationByYou = YES;
    self.navigationBar.hidden = YES;
    self.fd_interactivePopDisabled = YES;
    self.webCompent.delegate = self;
    self.webCompent.clientH5Object.delegate = self;
    [self.webCompent mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];

    if (_webPath.length > 0) {
        self.webCompent.fullUrl = [NSString stringWithFormat:@"%@%@",GMServerDomains.apiHost, _webPath];
    } else {
        self.webCompent.fullUrl = [NSString stringWithFormat:@"%@%@",GMServerDomains.apiHost, API_AI_RESEARCH_REPORT];
    }
    [self.webCompent webviewLoad:self];
}

- (void)setWebPath:(NSString *)webPath {
    _webPath = webPath;
}

#pragma mark - 前端与移动端连调方法
- (void)jsGlobalDataLoaded:(NSString *)jsonString {
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    _jsGlobalObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    if (_jsGlobalObject == nil) {
        return;
    }
    
    if (_jsGlobalObject[@"page_name"]) {
        self.pageName = _jsGlobalObject[@"page_name"];
    }
    // 调取前端方法
    NSDictionary *responseDict = [GMCache fetchObjectAtDocumentPathWithkey:kGMGeneMemoryLastData];
    NSString *dictStr = [NSString convertToPrettyPrintedJsonString: responseDict];
    NSNumber *gender = [GMCache fetchObjectAtDocumentPathWithkey:kGMGeneMemoryGender];
    NSString *javaScriptStr = [NSString stringWithFormat:@"window.gm.pack.run('jsPageRenderData',%@, %d)", dictStr, gender.intValue];
    [self.webCompent.webView evaluateJavaScript:javaScriptStr completionHandler:nil];
}

-(void)jsControlBackToMethod:(NSString *)str {
    if([str isEqualToString:@"pop"]){  // 返回到拍照测试页面
        [self backFurther];
    } else if ([str isEqualToString:@"face"]) { //  返回测脸页面
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GMTestSkinAnimationWebViewSenBack" object:nil];
        [self backFurther];
    }  else if ([str isEqualToString:@"reserch"]) { //  返回面孔起源
        [self backFurther];
    } else if ([str isEqualToString:@"skin"]) { // 测肤
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GMFaceInfoSharePopToFaceSkin" object:nil];
        [self backFurther];
    } else if ([str isEqualToString:@"back"]) { // 返回上一页
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)jsJumpToResearchPage:(NSString *)url {
    GMGeneMemoryResultViewController *geneListVC = [[GMGeneMemoryResultViewController alloc] init];
    geneListVC.webPath = url;
    [self.navigationController pushViewController:geneListVC animated:YES];
}

- (NSString *)jsGetLocalStorage:(NSString *)key {
    NSString *cacheKey = [GMCache fetchObjectAtDocumentPathWithkey:key];
    NSString *javaScriptStr = [NSString stringWithFormat:@"window.gm.pack.run('getLocalStorage','%@')",cacheKey];
    [self.webCompent.webView evaluateJavaScript:javaScriptStr completionHandler:nil];

    if (![cacheKey isNonEmpty]) {
        return  @"";
    }
    return cacheKey;
}

// 当图片生成时，前端会调用这个方法
- (void)shareResearchInfoImageMethod:(NSString *)imageDataStr{
    _shareImage = [self stringToImageWith:imageDataStr imageStr:@"imageString"];
    if (!_shareImage) {
        [self toast:@"糟糕，生成失败了，再试一次吧"];
        return;
    }
    // 展示分享框
    [self shareFaceInfo];
    // 保存图片到相册
    UIImageWriteToSavedPhotosAlbum(_shareImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    [self toast:@"图片已存至相册，快分享给朋友炫耀一下"];
}

// 解析前端传递过来的图片
- (UIImage *)stringToImageWith:(NSString *)imageData imageStr:(NSString *)imageStr {
    NSData *jsonData = [imageData dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSString *imageString = dict[imageStr] ?: @"";
    UIImage *image = [UIImage imageWithData:[[NSData alloc] initWithBase64EncodedString:imageString options:NSDataBase64DecodingIgnoreUnknownCharacters]];
    return image;
}

- (void)shareFaceInfo {
    CGFloat scale1 = _shareImage.size.height / _shareImage.size.width;
    CGFloat width1 = ShareImageHeight / scale1;
    self.shareImageView.image = self.shareImage;
    self.shareImageView.frame = CGRectMake((MAINSCREEN_WIDTH - width1)/2, OCNavigationBar.barHeight + 10, width1, ShareImageHeight);
    [self.shareSheet addSubview:self.shareImageView];
    [self.shareSheet show];
    [UIView animateWithDuration:0.5 animations:^{
        _shareImageView.alpha = 1.0;
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {}

// 返回按钮点击事件
-(void)backFurther {
    BOOL isPop = YES;
    for (UIViewController *vc in AppDelegate.navigation.childViewControllers) {
        if ([vc isKindOfClass:[NewFaceShotController class]]){
            isPop = NO;
            [AppDelegate.navigation popToViewController:vc animated:YES];
            return;
        }
    }
    if (isPop) {
        [AppDelegate.navigation popToRootViewControllerAnimated:YES];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 懒加载数据
- (ALShareSheet *)shareSheet {
    if (!_shareSheet) {
        _shareSheet = [[ALShareSheet alloc] init];
        _shareSheet.bgAlphaColor = RGBCOLOR_HEX(0xF4F3F8);
        __weak typeof(self) weakSelf = self;
        _shareSheet.hiddenBlock = ^{  // 隐藏
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.shareImageView.alpha = 0.0;
            } completion:^(BOOL finished) {
                [weakSelf.shareImageView removeFromSuperview];
            }];
        };
        _shareSheet.shareTypeBlock = ^(GMSharePlatform platform) {  // 分享
            [[GMShareSDK shareInstance] shareImage:weakSelf.shareImage platform:platform];
            [Phobos track:@"page_click_share_channel" attributes:@{@"page_name":SafeString(weakSelf.pageName),
                                                                   @"share_channel":SafeString([GMShareSDK shareChannel:platform])}];
        };
    }
    return _shareSheet;
}

-(GMImageView *)shareImageView {
    if (!_shareImageView) {
        _shareImageView = [[GMImageView alloc] init];
        _shareImageView.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT);
        _shareImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _shareImageView;
}
@end
