//
//  ALFaceInfoViewModel.m
//  GMAlpha
//
//  Created by Mikasa on 2019/5/7.
//  Copyright © 2019 Gengmei. All rights reserved.
//
//#import "ALOneImageResultViewController.h"
//#import "Gengmei-Swift.h"
#import "ALFaceInfoViewModel.h"
#import "GMAIConst.h"
#import "ALUpLoadManager.h"
//#import "ALUpLoadManager.h"
//#import "GMFaceInfoShareViewController.h"
#import "UIImage+ImageEffects.h"
//#import "GMHudModule+Alpha.h"
#import "ALTransFormFaceUtil.h"
#import "ALFacePointsModel.h"
//#import "GMFacePointViewController.h"
#import "GMFaceV3Model.h"
#import "GMAIConst.h"

@import GMRouter;
@import GMCache;
@import GMNetworking;
@import SDWebImage;
@implementation ALFaceInfoViewModel
/**
 获取面部点数据
 
 @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) {
                NSDictionary *data = [ALTransFormFaceUtil readLocalFileWithName:@"points_v2"];
                ALFacePointsModel *pointsModel = [[ALFacePointsModel alloc] initWithDictionary:data[@"data"] error:nil];
                successBlock(pointsModel);
            }
        } else {
            if (failBlock) {
                failBlock(response.message);
            }
        }
    }];
}

/**
 执行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);
            }
        }
    }];
}


/**
 面部分享页面
 */
+ (void)jumpFaceAnalysisSharePage {
    [[GMRouter sharedInstance] pushScheme:@"gengmei://face_info_share"];
}

/**
 * 上传 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];
    }];
}

+ (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;
    [ALFaceInfoViewModel excuteOneImageCreate:SafeString(path) successBlock:^(id responseObject) {
        [ALFaceInfoViewModel clearFaceId];
        [ALFaceInfoViewModel saveFaceId:responseObject[@"face_id"]];
        /** 获取面部分析数据 */
        [weakSelf getFaceAnalysis:path vc:vc successBlock:successBlock];
    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

/**
 获取面部分析数据
 
 @param path OneImage图片地址
 */
+ (void)getFaceAnalysis:(NSString *)path vc:(UIViewController *)vc successBlock:(HttpSuccessBlock)successBlock {
    __weak __typeof(self)weakSelf = self;
    [ALFaceInfoViewModel excuteFacePointsInfo:path successBlock:^(ALFacePointsModel *pointsModel) {
        [weakSelf jumpFaceAnalysisPage:pointsModel vc:vc successBlock:successBlock];
    } failBlock:^(NSString *message) {
        [weakSelf showAlertScanErrorView];
    }];
}

//处理模型中的数组转换
+ (NSArray *)returnNSNumberArray:(NSArray *)array faceModel:(ALFaceModel *)faceModel scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
    
    NSArray *pointArray = [[NSArray alloc] init];
    NSNumber *pointX = array.firstObject;
    NSNumber *pointY = array.lastObject;
    pointX = [NSNumber numberWithFloat:(pointX.floatValue * scaleX)];
    pointY = [NSNumber numberWithFloat:(pointY.floatValue * scaleY)];
    return pointArray = @[pointX, pointY];
}

//模型处理
+ (ALFaceModel *)dealModelMethod:(ALFaceModel *)faceModel image:(UIImage *)image {
    //原图片的高度
    CGFloat imageW = image.size.width;
    CGFloat imageH = image.size.height;
    //宽高比
    CGFloat scale = imageW / imageH;
    //显示在当前屏幕的高度 imageH
    CGFloat currentImageH = MAINSCREEN_WIDTH / scale;
    //x转换需要乘的比例
    CGFloat scaleX = MAINSCREEN_WIDTH / imageW;
    //y转换需要乘的比例
    CGFloat scaleY = currentImageH / imageH;
    
    faceModel.imageX = 0.f;
    faceModel.imageY = 0.f;
    faceModel.imageW = MAINSCREEN_WIDTH;
    faceModel.imageH = currentImageH;
    //框的坐标转换完成
    faceModel.rect.left = faceModel.rect.left * scaleX;
    faceModel.rect.top = faceModel.rect.top * scaleY;
    faceModel.rect.right = faceModel.rect.right * scaleX;
    faceModel.rect.bottom = faceModel.rect.bottom * scaleY;
    //68个坐标点
    NSMutableArray *tempArray = [NSMutableArray new];
    [faceModel.landmark enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.landmark = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //横着的三根线
    [faceModel.analysis.faceAnalysis.santing.keypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.faceAnalysis.santing.keypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //三庭的文案拐点
    [faceModel.analysis.faceAnalysis.santing.linepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.faceAnalysis.santing.linepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //五眼的五根线
    [faceModel.analysis.faceAnalysis.wuyan.keypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.faceAnalysis.wuyan.keypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //五眼的文案拐点
    [faceModel.analysis.faceAnalysis.wuyan.linepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.faceAnalysis.wuyan.linepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //下巴的连线
    [faceModel.analysis.faceAnalysis.contour.keypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.faceAnalysis.contour.keypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //鼻子的框
    [faceModel.analysis.noseMouthAnalysis.noseKeypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.noseKeypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //鼻子部位需要放大的坐标
    [faceModel.analysis.noseMouthAnalysis.coreRect enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 1 || idx == 3) {//y值
            obj = [NSNumber numberWithFloat:(obj.floatValue * scaleY)];
        }else {
            obj = [NSNumber numberWithFloat:(obj.floatValue * scaleX)];
        }
        [tempArray addObject:obj];
    }];
    faceModel.analysis.noseMouthAnalysis.coreRect = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //鼻子的文案连线
    [faceModel.analysis.noseMouthAnalysis.noseLinepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.noseLinepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //上嘴唇的框
    [faceModel.analysis.noseMouthAnalysis.mouthUpperKeypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.mouthUpperKeypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //上嘴唇的文案连线
    [faceModel.analysis.noseMouthAnalysis.mouthUpperLinepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.mouthUpperLinepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //下嘴唇的框
    [faceModel.analysis.noseMouthAnalysis.mouthLowerKeypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.mouthLowerKeypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //下嘴唇的文案连线
    [faceModel.analysis.noseMouthAnalysis.mouthLowerLinepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.noseMouthAnalysis.mouthLowerLinepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //左眼需要放大的框
    [faceModel.analysis.eyebrowEyeAnalysis.coreRect enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 1 || idx == 3) {//y值
            obj = [NSNumber numberWithFloat:(obj.floatValue * scaleY)];
        }else {
            obj = [NSNumber numberWithFloat:(obj.floatValue * scaleX)];
        }
        [tempArray addObject:obj];
    }];
    faceModel.analysis.eyebrowEyeAnalysis.coreRect = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //左眼的框
    [faceModel.analysis.eyebrowEyeAnalysis.leftEyeKeypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.eyebrowEyeAnalysis.leftEyeKeypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //左眼眉的框
    [faceModel.analysis.eyebrowEyeAnalysis.leftEyebrowKeypoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.eyebrowEyeAnalysis.leftEyebrowKeypoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //左眼眉的文案连线
    [faceModel.analysis.eyebrowEyeAnalysis.leftEyebrowLinepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.eyebrowEyeAnalysis.leftEyebrowLinepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    //左眼的文案连线
    [faceModel.analysis.eyebrowEyeAnalysis.leftEyeLinepoints enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *pointArray = [ALFaceInfoViewModel returnNSNumberArray:obj faceModel:faceModel scaleX:scaleX scaleY:scaleY];
        [tempArray addObject:pointArray];
    }];
    faceModel.analysis.eyebrowEyeAnalysis.leftEyeLinepoints = tempArray.mutableCopy;
    [tempArray removeAllObjects];
    
    return faceModel;
}

// 跳转到面部分析页面
+ (void)jumpFaceAnalysisPage:(ALFacePointsModel *)pointModel 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 (image) {
            if (error) {
                [self showAlertScanErrorView];
                return ;
            }
            GMFaceV3Model *faceModel = pointModel.faces.firstObject;
            faceModel.image = image;

            if (successBlock) {
                successBlock(faceModel);
            } else {
                [[GMRouter sharedInstance] pushScheme:@"gengmei://face_point"];
            }
        }
    }];
}

// 弹出OneImage生成失败的弹框信息
+ (void)showAlertScanErrorView {
    
    // 如果当前处于启动流程不进行弹框,直接切换首页
    if ([self faceNextRootView]) return;
    
    [Phobos track:@"popup_view" attributes:@{@"page_name":@"create_report",
                                             @"popup_name":@"entering_fail"}];
//    [GMHudModule showWarning:@"未能识别要分析的人脸"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#warning TODO: 待完成
//        for (UIViewController *vc  in AppDelegate.navigation.childViewControllers) {
//            if ([vc isKindOfClass:[NewFaceShotController class]]){
//                [AppDelegate.navigation popToViewController:vc animated:YES];
//            }
//        }
        
    });
}

// 如果当前处于启动流程不进行弹框,直接切换首页
+ (BOOL)faceNextRootView {

    return NO;
}

#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
