//
//  GMFaceV3Util.m
//  Gengmei
//
//  Created by Q14 on 2019/7/1.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

#import "GMFaceV3Util.h"
#import "ALTransFormFaceUtil.h"
#import "GMFaceV3Model.h"
#import "GMAIConst.h"
#import "ALUpLoadManager.h"
//#import "GMHudModule+Alpha.h"
//#import "GMFacePointViewController.h"
@import GMNetworking;
@import GMCache;
@import SDWebImage;

@implementation GMFaceV3Util
/**
 获取面部点数据
 
 @param image_url image_url
 @param successBlock successBlock
 @param failBlock failBlock
 */
+ (void)excuteFacePointsInfo:(NSString *)image_url
                successBlock:(HttpSuccessBlock)successBlock
                   failBlock:(HttpFailedBlock)failBlock {
    
    NSDictionary *param = @{@"image_url":SafeString(image_url)};
    [GMNetworking requestOCWithApi:API_ONEIMAGE_POINTS method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC *response) {
        if (response.isSuccess) {
            if (successBlock) {
                GMFaceV3PointsModel *pointsModel = [[GMFaceV3PointsModel alloc] initWithDictionary:response.data error:nil];
                if (successBlock) {
                    successBlock(pointsModel);
                }
            }
        } else {
            if (failBlock) {
                failBlock(response.message);
            }
        }
    }];
}

+ (void)requestBeaytyImage:(GMFaceV3PointsModel *)pointsModel
              successBlock:(HttpSuccessBlock)successBlock {
    __weak typeof(self) weakSelf = self;
    NSDictionary *param = @{@"image_url":SafeString(pointsModel.imgUrl)};
    [GMNetworking requestOCWithApi:API_ONEIMAGE_BEAUTY_IMAGE method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC *response) {
        if (response.isSuccess) {
            if (successBlock) {
                successBlock(response.data);
            }
        } else {
            [weakSelf showAlertScanErrorView];
        }
    }];
}

/**
 执行OneImage 创建
 
 @param successBlock successBlock
 @param failBlock failBlock
 */
+ (void)excuteOneImageCreate:(NSString *)faceUrl
                successBlock:(HttpSuccessBlock)successBlock
                   failBlock:(HttpFailedBlock)failBlock {
    
    NSDictionary *param = @{@"face_url":SafeString(faceUrl)};
    [GMNetworking requestOCWithApi:API_ONEIMAGE_CREATE method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC *response) {
        if (response.isSuccess) {
            if (successBlock) {
                successBlock(response.data);
            }
        } else {
            if (failBlock) {
                failBlock(response.message);
            }
        }
    }];
}

/**
 * 上传 OneImage 图片
 * 先将图片传到七牛，再将路径传到服务端及保存本地
 */
+ (void)uploadOneImageToQiNiu:(UIImage *)image vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock  {
    if (!image) {
        [self showAlertScanErrorView];
        return;
    };
    __weak __typeof(self)weakSelf = self;
    ALUpLoadManager *uploadImage = [ALUpLoadManager new];
    [uploadImage setImage:image getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *path) {
        [weakSelf uploadOneImageToServer:path vc:vc successBlock:successBlock];
    } failBlock:^(NSString *message) {
//        [weakSelf showAlertScanErrorView];
    }];
}

/**
* 面孔起源
* 上传 OneImage 图片
* 先将图片传到七牛，再将路径传到服务端
*/
+ (void)uploadOneImageToQiNiu:(UIImage *)image gender:(NSInteger)gender vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    if (!image) {
        [self showAlertScanErrorView];
        return;
    };
    __weak __typeof(self)weakSelf = self;
    ALUpLoadManager *uploadImage = [ALUpLoadManager new];
    [uploadImage setImage:image getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *path) {
        [weakSelf uploadOneImageToServer:path gender:gender vc:vc successBlock:successBlock];
    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

+ (void)uploadImageToQiNiu:(UIImage *)image successBlock:(HttpSuccessBlock)successBlock {
    if (!image) {
        return;
    };
    ALUpLoadManager *uploadImage = [ALUpLoadManager new];

    [uploadImage setImage:image getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *path) {
        if (successBlock) {
            successBlock(path);
        }
    } failBlock:^(NSString *message) {
    }];
}

// 上传到后台
+ (void)uploadOneImageToServer:(NSString *)path vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    __weak __typeof(self)weakSelf = self;
    [self excuteOneImageCreate:SafeString(path) successBlock:^(id responseObject) {
        [self clearFaceId];
        [self saveFaceId:responseObject[@"face_id"]];
        /** 获取面部分析数据 */
        [weakSelf getFaceAnalysis:path isGene:NO vc:vc successBlock:successBlock];
    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

// 面孔起源
+ (void)uploadOneImageToServer:(NSString *)path gender:(NSInteger)gender vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    __weak __typeof(self)weakSelf = self;
    [self excuteOneImageCreate:SafeString(path) successBlock:^(id responseObject) {
        [weakSelf getGeneMemoryResultWithPath:path gender:gender successBlock:^(id responseObject) {
            /** 获取面部分析数据(动画) */
            [weakSelf getFaceAnalysis:path isGene:YES vc:vc successBlock:successBlock];
        }];

    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

// 面孔起源结果请求
+ (void)getGeneMemoryResultWithPath:(NSString *)path  gender:(NSInteger)gender successBlock:(HttpSuccessBlock)successBlock {
    NSDictionary *param = @{@"face_image" : SafeString(path),
                            @"gender" : @(gender)
    };
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:API_FACE_RESEARCH_REPORT method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC *response) {
        if (response.isSuccess) {
            if (successBlock) {
                [GMCache storeObjectAtDocumentPathWithkey:kGMGeneMemoryLastData object:response.data];
                [GMCache storeObjectAtDocumentPathWithkey:kGMGeneMemoryGender object:@(gender)];
                successBlock(response.data);
            }
        } else {
            [weakSelf showAlertScanErrorView];
        }
    }];
}

/**
 获取面部分析数据
 
 @param path OneImage图片地址
 */
+ (void)getFaceAnalysis:(NSString *)path isGene:(BOOL)isGene vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    __weak __typeof(self)weakSelf = self;
    [self excuteFacePointsInfo:path successBlock:^(GMFaceV3PointsModel *pointsModel) {
        [weakSelf requestBeaytyImage:pointsModel successBlock:^(id responseObject) {
            NSDictionary *dict = responseObject;
            if (dict[@"url"]) {
                pointsModel.imgUrl = SafeString(dict[@"url"]);
            }
            [weakSelf jumpFaceAnalysisPage:pointsModel isGene:isGene vc:vc successBlock:successBlock];
        }];
    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

// 弹出OneImage生成失败的弹框信息
+ (void)showAlertScanErrorView {
    [Phobos track:@"popup_view" attributes:@{@"page_name":@"create_report",
                                             @"popup_name":@"entering_fail"}];
//    [GMHudModule showWarning:@"未能识别要分析的人脸"];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [AppDelegate.navigation popViewControllerAnimated:YES];
//    });
}

// 跳转到面部分析页面
+ (void)jumpFaceAnalysisPage:(GMFaceV3PointsModel *)pointModel isGene:(BOOL)isGene vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    // 跳转到面部分析页面
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:pointModel.imgUrl] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (error) {
            [self showAlertScanErrorView];
            return;
        }
        GMFaceV3Model *faceModel = pointModel.faces.firstObject;
        faceModel.image = image;  //模型转换

        if (successBlock) {
            successBlock(faceModel);
        } else {
#warning TODO:
//            GMFacePointViewController *pointVc = [[GMFacePointViewController alloc] initWithModel:faceModel];
//            pointVc.isGene = isGene;
//            [vc.navigationController pushViewController:pointVc animated:YES];
        }
    }];
}
#pragma mark -  face_Id  数据获取 && 存储
/**
 保存面部faceID
 */
+ (void)saveFaceId:(NSString *)face_Id {
    [GMCache storeObjectAtDocumentPathWithkey:kFace_Id object:face_Id];
}
/**
 清理掉本地存储的faceID
 */
+ (void)clearFaceId {
    [GMCache removeObjectAtDocumentPathWithkey:kFace_Id];
}

/**
 查找本地存储的face_Id
 */
+ (NSString *)getLocalFaceId {
    return [GMCache fetchObjectAtDocumentPathWithkey:kFace_Id];
}
@end
