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

#import "GMFaceReplayResultVC.h"
#import "GMScreenRecorderManager.h"
#import "GMFaceInfoShareViewController.h"
#import "GMShareView.h"
#import "GMFaceReplayModel.h"
#import "WMShareObject.h"
#import "GMFaceReplayViewController.h"


@interface GMFaceReplayResultVC ()<GMScreenRecorderDelegate, CAAnimationDelegate, GMShareViewDelegate>

@property (nonatomic, strong) GMFaceReplayModel *repalyModel;  // 数据模型
@property (nonatomic, strong) GMFaceV3Model *faceModel;        // 脸型点位数据模型
@property (nonatomic, strong) WMShareObject *shareObject;      // 分享数据获取

@property (nonatomic, strong) UIImageView *resultImageView;     // 结果页面展示图片
@property (nonatomic, strong) GMButton *backBtn;               // 返回按钮
@property (nonatomic, strong) GMShareView *shareView;          //  分享view

@end

@implementation GMFaceReplayResultVC

- (instancetype)initWithModel:(GMFaceV3Model *)faceModel replayModel:(GMFaceReplayModel *)replayModel{
    if (self = [super init]) {
        self.pageName = @"scan_report_video";
        self.repalyModel = replayModel;
        self.faceModel = faceModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBar.hidden = YES;
    self.fd_interactivePopDisabled = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    // 加载分享资源
    __weak typeof (self) weakSelf = self;
    [GMNetworking requestOCWithApi:API_FACE_SHARE_DATA method:GMHTTPMethodGet parameters:nil completion:^(GMResponseOC * _Nonnull responseObject) {
        weakSelf.shareObject = [[WMShareObject alloc] initWithDictionary:responseObject.data error:nil];
        weakSelf.shareView.shareObject = weakSelf.shareObject;
    }];
    // 添加结果页面图片
    if (self.repalyModel.resultImage) {
        self.resultImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, [self getResultImageHeight])];
        _resultImageView.image = self.repalyModel.resultImage;
        [self.view addSubview:self.resultImageView];
    }
    // 设置录屏代理方法
    if (self.repalyModel.tapType != GMReplayViewTapPreview) {
        [GMScreenRecorderManager sharedManager].delegate = self;
    }
    [self addbackBtn]; // 添加返回按钮
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    CGFloat imageOffset = [self getResultImageHeight] - MAINSCREEN_HEIGHT;
    CGFloat offsetY = (imageOffset > 0) ? (-imageOffset) : 0;
    if (offsetY < 0) {
        [UIView animateWithDuration:1.5 animations:^{
            self.resultImageView.transform = CGAffineTransformMakeTranslation(0, offsetY);
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self animationStop];
    });
}

- (CGFloat)getResultImageHeight {
    return (self.repalyModel.resultImage.size.height * MAINSCREEN_WIDTH) / self.repalyModel.resultImage.size.width;
}

- (void)addbackBtn{
    [self.view addSubview:self.backBtn];
    [self.backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.equalTo(self.view.mas_top).offset([OCNavigationBar navigationItemCenterY]);
    }];
}

#pragma mark - 代理方法
-(void)animationStop{
    self.backBtn.hidden = NO;
    if (self.repalyModel.tapType == GMReplayViewTapPreview) {
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shareBbtClick)];
        [self.view addGestureRecognizer:recognizer];
        [self.shareView showWithShareUrl:@"GMFaceReplayResultVC"];
    }else if(self.repalyModel.tapType == GMReplayViewTapWechat){ // 微信录制结束
        [self showLoading:nil];
        [GMScreenRecorderManager stopRecordWithSave];
    }else{
        [self showLoading:nil];
        [GMScreenRecorderManager stopRecordWithSave];
    }
}

// 屏幕结束录制时发现未知错误 -- 文字提醒
-(void)didStopRecordWithErrorString:(NSString *)errorString {
    [self showWarning:errorString];
    // 返回到上一页
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self backMethod];
    });
}

// 保存视频成功，并拿到保存到相册的视频URL
- (void)saveVideoSuscessWithAssetURl:(AVURLAsset *)assetURL {
    [self toast:@"视频保存成功!"];
    self.backBtn.hidden = NO;
    // 发送通知，通知结果页面视频保存成功
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GMFaceReplayResultVC" object:assetURL];
    self.shareView.shareObject.videoUrl = [NSString stringWithFormat:@"%@",assetURL.URL];
    self.shareView.shareUrl = @"GMFaceReplayResultVC";
    // 获取分享数据
    if (self.repalyModel.tapType == GMReplayViewTapDouyin){ // 抖音
        [Phobos track:@"event_status" attributes:@{@"page_name" : SafeValue(self.pageName), @"event_name" : @"douyin_video_record", @"event_status": @"success"}];
        [self.shareView shareWithType:GMSharePlatformDouyin];
    }else{ // 微信
        [Phobos track:@"event_status" attributes:@{@"page_name" : SafeValue(self.pageName), @"event_name" : @"wechartline_video_record", @"event_status": @"success"}];
        [self.shareView shareWithType:GMSharePlatformWechatTimeline];
    }
    // 返回到扫脸页面
    for (UIViewController *vc in AppDelegate.navigation.childViewControllers) {
        if ([vc isKindOfClass:[GMFaceInfoShareViewController class]]){
            [AppDelegate.navigation popToViewController:vc animated:NO];
            return;
        }
    }
}

#pragma mark - GMShareViewDelegate
- (NSMutableDictionary *)fetchSharePublishContent:(GMSharePlatform)shareType {
    id shareImage = nil;
    GMShareContentType contentType = GMShareContentTypeAuto;
    WMShareBasicObject * object = [WMShareBasicObject new];
    NSString *image = _shareObject.image;
    if (image.length != 0) {
        shareImage = [GMShareSDK compressWithUrl:image];
    }else{
        // 使用app logo做图标
        shareImage = [UIImage imageNamed:@"icon"];
    }
    // 微信会话分享且微信小程序内容不为空的时候，认为是微信小程序分享
    if (shareType == GMSharePlatformWechatSession && [_shareObject.wechatmini.path isNonEmpty]) {
        shareType = GMSharePlatformWechatMiniProgram;
    }
    switch (shareType) {
        case GMSharePlatformSinaWeibo:
            object = _shareObject.weibo;
            break;
        case GMSharePlatformWechatSession:
            object = _shareObject.wechat;
            break;
        case GMSharePlatformWechatTimeline:
            object = _shareObject.wechatline;
            break;
        case GMSharePlatformQQFriend:
            object = _shareObject.qq;
            break;
        case GMSharePlatformDouyin:
            object = _shareObject.douyin;
            break;
        default:
            break;
    }
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    if (shareType == GMSharePlatformWechatMiniProgram){
        [shareParams shareSetupMiniProgramShareParamsByUrl:_shareObject.url
                                                  userName:_shareObject.wechatmini.userName
                                                      path:_shareObject.wechatmini.path
                                                     title:_shareObject.wechatmini.title
                                               description:_shareObject.wechatmini.desc
                                                thumbImage:_shareObject.wechatmini.thumbImageUrl
                                               hdImageData:_shareObject.wechatmini.hdImageUrl];
    } else {
        if (_shareObject.videoUrl.isNonEmpty) {
            // 分享视频
            [shareParams shareSetupShareParamsByText:object.content images:shareImage url:[NSURL URLWithString:_shareObject.url] title:object.title videoUrl:[NSURL URLWithString:_shareObject.videoUrl] type:contentType];
        } else {
            [shareParams shareSetupShareParamsByText:object.content
                                              images:shareImage
                                                 url:[NSURL URLWithString:_shareObject.url]
                                               title:object.title
                                                type:contentType];
        }
    }
    return  shareParams;
}

#pragma mark - 添加按钮

- (GMButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [GMButton buttonWithType:(UIButtonTypeCustom)];
        _backBtn.enableAdaptive = YES;
        _backBtn.alpha = 1.0;
        _backBtn.hidden = YES;
        [_backBtn setImage:[UIImage imageNamed:@"NewFaceBackBlack"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backMethod) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _backBtn;
}


- (void)backMethod {
    // 返回到具体页面
    BOOL isPop = YES;
    for (UIViewController *vc in AppDelegate.navigation.childViewControllers) {
        if ([vc isKindOfClass:[GMFaceInfoShareViewController class]]){
            isPop = NO;
            [AppDelegate.navigation popToViewController:vc animated:YES];
            return;
        }
    }
    if (isPop) {
        [AppDelegate.navigation popToRootViewControllerAnimated:YES];
    }
}

#pragma mark - 添加GMShareView
- (GMShareView *)shareView{
    if (!_shareView) {
        _shareView = [[GMShareView alloc] init];
        _shareView.delegate = self;
    }
    return _shareView;
}

- (void)willShowShareView:(GMShareView *)shareView {
    shareView.showCopyLink = NO;
    shareView.showRefresh = NO;
}

- (void)shareVideo:(GMSharePlatform)shareType {
    GMFaceReplayModel *rmodel = self.repalyModel;
    if (shareType == GMSharePlatformDouyin) {
        rmodel.type = @"douyin";
    }else {
        rmodel.type = @"wechat";
    }
    NSString *timeStrKey = [NSString stringWithFormat:@"%@TimeKey",rmodel.type];
    NSString *timeStr = [GMCache fetchObjectAtDiskWithkey:timeStrKey];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *dateTime = [formatter stringFromDate:date];
    if ([timeStr isEqualToString:dateTime]) { // 是同一天
        [self pushToGMFaceReplayViewController:shareType addRModel:rmodel];
    }else{ // 不是同一天
        [GMCache storeObjectAtDiskWithkey:timeStrKey object:dateTime];
        [self toast:@"分享视频需要录制您的屏幕，录制期间请勿退出界面"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self pushToGMFaceReplayViewController:shareType addRModel:rmodel];
        });
    }
}

-(void)pushToGMFaceReplayViewController:(GMSharePlatform)shareType addRModel:(GMFaceReplayModel *)rModel{
    GMFaceReplayViewController * vc = [[GMFaceReplayViewController alloc] initWithModel:self.faceModel replayModel:rModel];
    [AppDelegate.navigation pushViewController:vc animated:YES];
}

-(void)cancleShareView{
    [self backMethod];
}

-(void)shareBbtClick{
    // 添加分析弹框
    [self.shareView showWithShareUrl:@"GMFaceReplayResultVC"];
}

-(void)dealloc{
    NSLog(@"%s",__func__);
}

@end
