//
//  GMTestSkinAnimationWebView.m
//  Gengmei
//
//  Created by 刘鹿杰 on 2019/8/21.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

#import "GMTestSkinAnimationWebView.h"
#import "GMFaceV3Util.h"
#import "Gengmei-Swift.h"
#import "UIView+Gradient.h"
#import "GMPhotoDefine.h"
#import "ALShareSheet.h"
#import "GMSkinUpLoadHeadPicPopView.h"
#import "Lottie.h"
#import "GMAIFacePopViewObject.h"
#import "GMFacePhotosPopView.h"

#define ShareImageHeight (MAINSCREEN_HEIGHT - UIView.safeAreaInsetsBottom - 206 - self.navigationBar.bottom)

@interface GMTestSkinAnimationWebView ()<WKWebViewDelegate,GMPhotoPickDismissDelegate>

@property (nonatomic, strong) GMImageView *bgImageView;       // 待展示图片的image
@property (nonatomic, strong) GMView *loadingView;            // 动画View
@property (nonatomic, strong) GMView *contentView;
@property (nonatomic, strong) UIView *bottomView; // 悬浮按钮View
@property (nonatomic, strong) GMWebViewComponent *webCompent; // WebView
@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;
@property (nonatomic, assign) BOOL webLoadSucceed;
@property (nonatomic, copy) NSString *oringImageURL; // 上传的图片链接
@property (nonatomic, strong) GMAIFacePopViewObject *popViewObject; // 弹框模型
@property (nonatomic, strong) GMFacePhotosPopView *popView; // 弹出提示框

@end

@implementation GMTestSkinAnimationWebView

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

-(void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBar.isShowShadow = NO;
    self.fd_interactivePopDisabled = YES;
    
    // 添加上次报告数据浏览
    NSString *haveLastReport = [GMCache fetchObjectAtDocumentPathWithkey:@"GMTestSkinIsShowData"];
    NSDictionary *responseDict = [GMCache fetchObjectAtDocumentPathWithkey:@"GMTestSkinLastData"];
    BOOL haveScanSkin = GMLaunchManager.shareManager.appConfigObject.haveScanSkin; // 查看远端是否有上次报告
    self.oringImageURL = [GMCache fetchObjectAtDocumentPathWithkey:@"GMLastReportOringImageURL"]; // 查看是否有图片链接

    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.loadingView];
    
    // 添加webView
    self.webCompent = [[GMWebViewComponent alloc] init];
    _webCompent.delegate = self;
    [self.view insertSubview:_webCompent belowSubview:self.bgImageView];
    [_webCompent mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
        make.top.mas_equalTo(OCNavigationBar.barHeight);
    }];
    
    if (haveLastReport.isNonEmpty && responseDict && !self.image) {  // 本地数据存储
        
        [self successDeal:responseDict];
        
    } else if (haveScanSkin && !self.image){   // 加载上次报告网络数据
        __weak typeof(self) weakSelf = self;
        [GMNetworking requestOCWithApi:API_FACE_GET_SKIN_RECORD method:GMHTTPMethodGet parameters:nil completion:^(GMResponseOC * _Nonnull response) {
            if (response.isSuccess){
                [GMCache storeObjectAtDocumentPathWithkey:@"GMTestSkinLastData" object:response.data];
                [GMCache storeObjectAtDocumentPathWithkey:@"GMTestSkinIsShowData" object:@"yes"];
                [weakSelf successDeal:response.data];
            }else{
                [weakSelf toast:response.data[@"资源阻塞， 请稍后再试！"]];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }];
    } else {   // 测肤正常进入的时候， 走这个分支
        __weak typeof(self) weakSelf = self;
        [GMFaceV3Util uploadImageToQiNiu:self.image successBlock:^(id responseObject) {
            weakSelf.oringImageURL = [NSString stringWithFormat:@"https://pic.igengmei.com/%@-aspectscale800", responseObject];
            NSDictionary *param = @{@"image_url":SafeString(weakSelf.oringImageURL)};
            [GMNetworking requestOCWithApi:API_FACE_APP_TEST_SKIN method:GMHTTPMethodGet parameters:param completion:^(GMResponseOC * _Nonnull response) {
                if (response.isSuccess){
                    [GMCache storeObjectAtDocumentPathWithkey:@"GMTestSkinLastData" object:response.data];
                    [GMCache storeObjectAtDocumentPathWithkey:@"GMTestSkinIsShowData" object: @"yes"];
                    [GMCache storeObjectAtDocumentPathWithkey:@"GMLastReportOringImageURL" object: weakSelf.oringImageURL];
                    [weakSelf successDeal:response.data];
                }else{
                    [weakSelf toast:response.data[@"资源阻塞， 请稍后再试！"]];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            }];
        }];
    }
    // 加载loading页面弹框数据
    [self loadPopViewData];
}

-(void)successDeal:(NSDictionary *)dict{
    if ([dict[@"thrid_consultation_url"] isNonEmpty]) {
        self.imUrl = dict[@"thrid_consultation_url"];
    }
    if ([dict[@"retcode"] integerValue] == 0) {
        self.dataDict = dict;
        [self.webCompent setLocalStorage:@"skinUserImg" value:SafeString(self.oringImageURL)];
        self.webCompent.fullUrl = [NSString stringWithFormat:@"%@/%@",GMServerDomains.apiHost, SafeString(dict[@"gray_url"] ?: @"phantom/skin_measuring_report_3")];
        [self.webCompent webviewLoad:self];
    }else{
        [Phobos track:@"popup_view" attributes:@{@"page_name" : self.pageName,
                                                 @"popup_name" : SafeValue(dict[@"retcode"]),@"popup_content" : SafeValue(dict[@"retmsg"])}];
        [self toast:dict[@"retmsg"]];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)loadPopViewData {
    // 加载弹框逻辑：
    [GMNetworking requestOCWithApi:@"/gm_ai/pop_window" method:GMHTTPMethodGet parameters:@{@"pop_type": @"2"} completion:^(GMResponseOC * _Nonnull response) {
        if (response.isSuccess) {  // 加载成功
            self.popViewObject = [[GMAIFacePopViewObject alloc] initWithDictionary:response.data error:nil];
            [self.navigationController.view addSubview:self.popView]; // 添加弹出框
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [Phobos track:@"popup_view" attributes:@{@"page_name" : SafeString(self.pageName), @"popup_name" :SafeString(self.popViewObject.title),@"popup_content" : SafeString(self.popViewObject.content)}];
                [UIView animateWithDuration:0.25 animations:^{
                    self.popView.mj_y = (0);
                } completion:^(BOOL finished) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [UIView animateWithDuration:0.25 animations:^{
                            self.popView.mj_y = -(100 + OCNavigationBar.statusBarHeight);
                        } completion:^(BOOL finished) {
                            [self.popView removeFromSuperview];
                        }];
                    });
                }];
            });
        }
    }];
}

// leftButton点击事件
-(void)backAction:(OCNavigationBarButton *)button{
    if (self.webLoadSucceed){
        [self.webCompent.webView evaluateJavaScript:@"window.gm.pack.run('signBack')" completionHandler:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    [self shareFriend];
}

// 再测一次
-(void)againBtnClick {
    [Phobos track:@"on_click_button" attributes:@{@"page_name" : self.pageName, @"button_name" : @"detect_again" }];
    if ([self.referer isEqualToString:@"home"]) {
        [[GMRouter sharedInstance] pushScheme:@"gengmei://scan_faceimage?face_skin_tab_index=1"];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 添加悬浮btn 及逻辑处理

- (void)addSuspendBottomView {
    CGFloat margin = (MAINSCREEN_WIDTH - 103 * 3) / 4;
    // 专家咨询
    GMButton *consultBtn = [self creatBtnWithImageName:@"face_photo_bgImage" title:@"专家咨询" titleColor:RGBCOLOR_HEX(0xFF5963) selector:@selector(imButtonClick)];
    [consultBtn setImage:[UIImage imageNamed:@"face_test_consultIcon"] forState:UIControlStateNormal];
    [self.bottomView addSubview:consultBtn];
    [consultBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(38);
        make.width.mas_equalTo(103);
        make.right.mas_equalTo(self.view.mas_right).offset(-margin);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(btnBottomMargin);
    }];
    // 颜值分析
    GMButton *skinAnalyseBtn = [self creatBtnWithImageName:@"face_analyse_bgImage" title:@"颜值分析" titleColor:UIColor.auxiliaryTextGreen selector:@selector(aiButtonClick)];
    [skinAnalyseBtn setImage:[UIImage imageNamed:@"face_test_analyse"] forState:UIControlStateNormal];
    [self.bottomView addSubview:skinAnalyseBtn];
    [skinAnalyseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(38);
        make.width.mas_equalTo(103);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(btnBottomMargin);
    }];
    
    // 再测一次
    GMButton *againBtn = [self creatBtnWithImageName:@"face_analyse_bgImage" title:@"再测一次" titleColor:UIColor.auxiliaryTextGreen selector:@selector(againBtnClick)];
    [againBtn setImage:[UIImage imageNamed:@"face_test_photoIcon"] forState:UIControlStateNormal];
    [self.bottomView addSubview:againBtn];
    [againBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(38);
        make.width.mas_equalTo(103);
        make.left.mas_equalTo(self.view.mas_left).offset(margin);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(btnBottomMargin);
    }];
}

- (GMButton *)creatBtnWithImageName:(NSString *)imageStr title:(NSString *)title titleColor:(UIColor *)titleColor selector:(SEL)sel{
    GMButton *btn = [[GMButton alloc] init];
    btn.adjustsImageWhenHighlighted = NO;
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [btn setBackgroundImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    return btn;
}

- (void)imButtonClick {
    if (self.imUrl) {
        [Phobos track:@"on_click_button" attributes:@{@"page_name" : self.pageName, @"button_name" : @"im_button" }];
        [[GMRouter sharedInstance] pushScheme:self.imUrl];

    }
}

-(void)goHomeBtnClick {
    [Phobos track:@"on_click_button" attributes:@{@"page_name" :SafeString(self.pageName), @"button_name" : @"back_home"}];
    [self.webCompent.webView evaluateJavaScript:@"window.gm.pack.run('signBack','sk_hm')" completionHandler:nil];
}

- (void)aiButtonClick {
    // 发送通知，切换摄像头
    [Phobos track:@"on_click_button" attributes:@{@"page_name" : self.pageName, @"button_name" : @"ai_function" }];
    if ([self.referer isEqualToString:@"home"]){
        [[GMRouter sharedInstance] pushScheme:@"gengmei://scan_faceimage"];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GMTestSkinAnimationWebViewSenBack" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)shareFriend {
    [Phobos track:@"page_click_share" attributes:@{@"page_name" : self.pageName}];
    [self.webCompent.webView evaluateJavaScript:@"window.gm.pack.run('share')" completionHandler:nil];
}

- (void)changeAvatar {
    GMPhotoPickController *controller = [[GMPhotoPickController alloc] initWithMaxImageCount:1 maxVideoCount:0 maxCount:1 photoDisplayType:GMPhotosDisplayImageType];
    controller.dismissDelegate = self;
    controller.root.singleSelection = YES;
    controller.root.showCropFirst = YES;
    [self presentViewController:controller animated:YES completion:NULL];
}

// 获取到截取的图片
- (void)dismissPhotoPick:(NSArray<GMEditPhotoInfo *> *)infos {
    if (infos.count == 0) { return;}
    GMEditPhotoInfo *model = infos.firstObject;
    UIImage *image = model.finshedImage;
    [GMFaceV3Util uploadImageToQiNiu:image successBlock:^(id responseObject) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *urlStr = [NSString stringWithFormat:@"https://pic.igengmei.com/%@-aspectscale800", responseObject];
            NSString *javaScriptStr = [NSString stringWithFormat:@"window.gm.pack.run('qnIconKey','%@')",urlStr];
            [self.webCompent.webView evaluateJavaScript:javaScriptStr completionHandler:nil];
        });
    }];
}

#pragma mark - 前端与移动端连调方法

-(void)jsControlBackToMethod:(NSString *)str{
    if([str isEqualToString:@"pop"]){  // 返回测肤页面
        [self.navigationController popViewControllerAnimated:YES];
    }else if([str isEqualToString:@"face"]){ //  返回测脸页面
        if ([self.referer isEqualToString:@"home"]){
//            [[GMRouter sharedInstance] pushScheme:@"gengmei://scan_faceimage"];
            [[GMRouter sharedInstance] pushScheme:@"gengmei://scan_faceimage"];
        }else{        
            [[NSNotificationCenter defaultCenter] postNotificationName:@"GMTestSkinAnimationWebViewSenBack" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

// 判断按钮滑动的位置
-(void)jsPageReachBottom:(BOOL)isScrollbottom{}

- (NSString *)getConvertWithKey:(NSString *)key {
    return [NSString convertToPrettyPrintedJsonString:self.dataDict[key] ?: @{}];
}

-(void)globalDataLoaded:(NSDictionary *)data{
    // 调取前端方法
    NSString *dictStr = [NSString stringWithFormat:@"%@,%@,%@,%@", [self getConvertWithKey:@"skin_check_results"],  [self getConvertWithKey:@"own_diagnose"], [self getConvertWithKey:@"current_user"], [self getConvertWithKey:@"popup"]];
    NSString *newDictStr = [[dictStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *javaScriptStr = [NSString stringWithFormat:@"window.gm.pack.run('jsPageRenderData',%@)",newDictStr];
    [self.webCompent.webView evaluateJavaScript:javaScriptStr completionHandler:nil];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.bgImageView.alpha = 0.0;
        self.loadingView.alpha = 0.0;
        self.navigationBar.backgroundColor = UIColor.whiteColor;
        self.navigationBar.title = @"肤质报告";
        self.navigationBar.rightIcon = @"face_right_share_image";
        [self addSuspendBottomView]; // 添加悬浮按钮
        self.webLoadSucceed = YES;
    } completion:^(BOOL finished) {
        self.bgImageView.hidden = YES;
        [self.loadingView removeFromSuperview];
    }];
}

// 当图片生成时，前端会调用这个方法
- (void)shareSkinInfoImageMethod:(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:@"已保存至相册"];
}

- (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 {}

// 解析前端传递过来的图片
- (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;
}

#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 *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[GMImageView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT)];
        if (self.image) {
            _bgImageView.image = self.image;
        }else if (_oringImageURL.isNonEmpty){
            [_bgImageView sd_setImageWithURL:[NSURL URLWithString:self.oringImageURL]];
        }else {
            _bgImageView.image = [UIImage imageNamed:@"facev5_share_bgImage"];
        }
        _bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _bgImageView;
}

- (GMView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[GMView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, MAINSCREEN_HEIGHT)];
        _loadingView.backgroundColor =  [UIColor colorWithHex:0 alpha:0.8];
        GMImageView *loadingImageView = [[GMImageView alloc] initWithFrame:CGRectMake((MAINSCREEN_WIDTH - 300) / 2, (MAINSCREEN_HEIGHT - 300) / 2, 300, 300)];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"skinloadinganimation.webp" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:path];
        loadingImageView.image = [UIImage sd_imageWithData:data];
        [_loadingView addSubview:loadingImageView];
    }
    return _loadingView;
}

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

- (GMFacePhotosPopView *)popView {
    if (!_popView) {
        _popView = [[GMFacePhotosPopView alloc] init];
        CGFloat popViewH = 100 + OCNavigationBar.statusBarHeight;
        _popView.frame = CGRectMake(0, -popViewH, MAINSCREEN_WIDTH, popViewH);
        _popView.popModel = self.popViewObject;
        // 剪切圆角
        [self changeLabelStyle:_popView];
    }
    return _popView;
}

- (void)changeLabelStyle:(GMView *)view {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor clearColor];
        [self.view insertSubview:_bottomView belowSubview:self.bgImageView];
        [_bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(84 + UIView.safeAreaInsetsBottom);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }];
        // 添加背景颜色
        GMImageView *bgImgView = [[GMImageView alloc] initWithImage:[UIImage imageNamed:@"face_bottomView_bgImage"]];
        [_bottomView addSubview:bgImgView];
        [bgImgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_equalTo(0);
            make.height.mas_equalTo(84);
        }];
        // 安全区域防止透明
        UIView *safeAreaView = [[UIView alloc] init];
        safeAreaView.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:safeAreaView];
        [safeAreaView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(UIView.safeAreaInsetsBottom);
        }];
    }
    return _bottomView;
}

@end
