//
//  ALCaptureUtils.m
//  GMAlpha
//
//  Created by Q14 on 2018/12/3.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALCaptureUtils.h"
#import "ALFaceSDK.h"
#import "ALScanManager.h"
@interface ALCaptureUtils()
/** netPath对应raw_similar_data */
@property (nonatomic, copy) NSString *netPath;
/** bmpPath对应pre_uv_url */
@property (nonatomic, copy) NSString *bmpPath;
@property (nonatomic, strong) ALFaceSDK  *faceSDK;
// 轮寻
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ALCaptureUtils

- (instancetype)init {
    if (self = [super init]) {
        _createUV = YES;
    }
    return self;
}
- (void)uploadNetImage:(UIImage *)netImage BmpImage:(UIImage *)bmpImage complete:(CompleteBlock)completeBlock {
     __weak __typeof(self)weakSelf = self;
    [ALUpLoadManager.shareInstance setImage:netImage getTokenType:GetTokenTypeSaoFace fileSuffix:nil block:^(NSString *path) {
        //上传成功
        weakSelf.netPath = path;
        [weakSelf setNetPath:weakSelf.netPath bmpPath:weakSelf.bmpPath complete:completeBlock];
    } failBlock:^(NSString *message) {
        //上传失败
    }];
    
    [ALUpLoadManager.shareInstance setImage:bmpImage getTokenType:GetTokenTypeSaoFace fileSuffix:@".bmp" block:^(NSString *path) {
        //上传成功
        weakSelf.bmpPath = path;
        [weakSelf setNetPath:weakSelf.netPath bmpPath:weakSelf.bmpPath complete:completeBlock];
    } failBlock:^(NSString *message) {
        //上传失败
    }];
}

/** 客户端数据上传 */
- (void)setNetPath:(NSString *)netPath bmpPath:(NSString *)bmpPath complete:(CompleteBlock)completeBlock
{
    if (netPath && bmpPath)
    {
        _faceSDK = [[ALFaceSDK alloc]init];
        __weak __typeof(self)weakSelf = self;
        [_faceSDK faceUploadRaw_similar_data:bmpPath pre_uv_url:netPath create_uv:_createUV successBlock:^(id responseObject) {
            //如果返回成功轮巡调获取UV
            completeBlock(YES);
            if (weakSelf.createUV) {
               weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(getUVImageMethod) userInfo:nil repeats:YES];
            }
        } failBlock:^(NSString *message) {
            
        }];
        self.netPath = nil;
        self.bmpPath = nil;
    }
}

#pragma mrk--获取UV图
- (void)getUVImageMethod
{
    NSLog(@"来到我这里了");
    
    __weak __typeof(self)weakSelf = self;
    [self.faceSDK faceUploadSuccessBlock:^(GMResponseOC *responseObject) {
        [weakSelf.timer invalidate];
        weakSelf.timer = nil;
        NSDictionary *data = responseObject.data;
        
        NSString *urlStr = data[@"uv_url"];
        NSString *txtPath = [self.u2dSession.rootSessionDirectory stringByAppendingString:@"/outputnew.txt"];
        [ALFaceSDK downloadURL:urlStr storePath:txtPath progress:^(NSProgress *downloadProgress) {
            
        } destination:^(NSURL *targetPath) {
           [self generate3DModelOutPutTxt:txtPath];
        } failure:^(NSError *error) {
            
        }];
    } failBlock:^(NSString *message) {
//        [weakSelf toast:message];
        [AppDelegate.visibleController toast:message];
    }];
}

//根据 UV txt  生成3D 模型
- (void)generate3DModelOutPutTxt:(NSString *)modelMat {
//    //定义UV图片存储路径 --用于生成模型时贴图使用
    NSString * uvImgFile22 = [self.u2dSession.rootSessionDirectory stringByAppendingString:@"/formatUV.jpg"];
    //定义保存obj model的路径，该路径要存在
    NSString * objPath = self.u2dSession.rootSessionDirectory;
    //定义保存obj 文件名，只支持obj后缀
    NSString * ObjName = @"model.obj";
    //该函数会在给定 objPath 路径下生成  model.obj  model.mtl mode.png  三个文件
    BOOL isSuccess = [_u2dModel  exportNetDataToObjWithoutPath:objPath objFileName:ObjName andNetMatFile:modelMat modelTF:&_tff_net uvImgFile:uvImgFile22];
    if (isSuccess) {
        
    } else {
        [AppDelegate.visibleController toast:@"模型生成失败"];
    }
    // 虽然选择城市页是被present的，但是 visibleViewController 仍然能访问到该controller
}

- (ALFaceSDK *)faceSDK
{
    if (!_faceSDK) {
        _faceSDK = [[ALFaceSDK alloc]init];
    }
    return _faceSDK;
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}

//判断文件是否已经在沙盒中已经存在？
-(BOOL) isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    return result;
}

- (NSMutableArray *)allFilesAtPath:(NSString *)direString
{
    NSMutableArray *pathArray = [NSMutableArray array];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:direString error:nil];
    for (NSString *fileName in tempArray) {
        BOOL flag = YES;
        NSString *fullPath = [direString stringByAppendingPathComponent:fileName];
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&flag]) {
            if (!flag) {
                // ignore .DS_Store
                if (![[fileName substringToIndex:1] isEqualToString:@"."]) {
                    [pathArray addObject:fullPath];
                }
            }
            else {
                [pathArray addObject:[self allFilesAtPath:fullPath]];
            }
        }
    }
    
    return pathArray;
}
@end
