//
//  ALUpLoadManager.m
//  GMAlpha
//
//  Created by zhouLiang on 2018/11/26.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALUpLoadManager.h"
#import "GMAIConst.h"
//#import "QNUploadManager.h"
#import <Qiniu/QNUploadManager.h>
#import <CommonCrypto/CommonDigest.h>
//#import "GMPhotoTools.h"
@import GMFoundation;
@import GMNetworking;
@interface ALUpLoadManager ()

@property (nonatomic, copy) NSString *token;

@end

@implementation ALUpLoadManager

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    
    return instance;
}
/**
 * 七牛上传图片
 */
- (void)setImage:(UIImage *)image getTokenType:(GetTokenType)type fileSuffix:(NSString *)fileSuffix block:(returnImageUrlBlock)block failBlock:(returnFailBlock)failBlock {
    
    if (!image) {
        failBlock(@"数据不能为空");
        return;
    }
    NSDictionary *params = @{@"token_type" : @(type)};
    [GMNetworking requestOCWithApi:API_FACE_GET_TOKEN method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess) {
            //token get success
            NSDictionary *dict = response.data;
            NSString *token = dict[@"token"];
            [self putImage:image getTokenType:type token:token fileSuffix:fileSuffix block:block failBlock:failBlock];
        } else {
            failBlock(response.message);
        }
    }];
}

// 上传图片
- (void)putImage:(UIImage *)image getTokenType:(GetTokenType)type token:(NSString *)token fileSuffix:(NSString *)fileSuffix block:(returnImageUrlBlock)block failBlock:(returnFailBlock)failBlock {
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSData *imageData;
        if (type == GetTokenTypeSaoFace) {
            imageData = UIImageJPEGRepresentation(image,1.0);
        }
        else{
            imageData = UIImageJPEGRepresentation(image,0.7);
        }
        NSString *key = [self createImagePath];
        if ([fileSuffix isNonEmpty]) {
            key = [NSString stringWithFormat:@"%@%@",key,fileSuffix];
        }
        [upManager putData:imageData key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info) {
                // 上传成功
                if (block != nil) {
                    block(key);
                }
            } else {
                if (failBlock != nil) {
                    failBlock(@"上传失败");
                }
                //上传失败
//                [AppDelegate.visibleController toast:@"上传失败"];
            }
            dispatch_group_leave(group);
        } option:nil];
    });
}

/**
 * 七牛上传文件
 */
- (void)setFile:(NSString *)file getTokenType:(GetTokenType)type block:(returnImageUrlBlock)block failBlock:(returnFailBlock)failBlock
{
    
//    if ([[GMLoginManager shareInstance] showLoginViewIfNeeded]) {
//        return;
//    }
    
    if (![file isNonEmpty]) {
        failBlock(@"数据不能为空");
        return;
    }
    
    NSDictionary *params = @{@"token_type" : @(type)};
    [GMNetworking requestOCWithApi:API_FACE_GET_TOKEN method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess)
        {
            //token get success
            NSDictionary *dict = response.data;
            NSString *token = dict[@"token"];
            
            dispatch_group_t group = dispatch_group_create();
            
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                QNUploadManager *upManager = [[QNUploadManager alloc] init];
                //        NSData *imageData = UIImageJPEGRepresentation(image,.7);
                NSString *key = [self createImagePath];
                [upManager putFile:file key:key token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                    if (info) {
                        // 上传成功
                        if (block != nil) {
                            block(key);
                        }
                    } else {
                        if (failBlock != nil) {
                            failBlock(@"上传失败");
                        }
                        //上传失败
//                        [AppDelegate.visibleController toast:@"上传失败"];
                    }
                    dispatch_group_leave(group);
                } option:nil];
                
            });
        }
        else
        {
            //token get fail
//            [AppDelegate.visibleController toast:response.message];
        }
    }];
    
}

/**
 * 七牛上传视频
 */
- (void)setData:(NSData *)data getTokenType:(GetTokenType)type key:(NSString *)key block:(returnImageUrlBlock)block failBlock:(returnFailBlock)failBlock
{
    
//    if ([[GMLoginManager shareInstance] showLoginViewIfNeeded]) {
//        return;
//    }
    
    if (!data || data.length <= 0) {
        failBlock(@"数据不能为空");
        return;
    }
    
    NSDictionary *params = @{@"token_type" : @(type)};
    __block NSString *oldKey = key;
    [GMNetworking requestOCWithApi:API_FACE_GET_TOKEN method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess)
        {
            //token get success
            NSDictionary *dict = response.data;
            NSString *token = dict[@"token"];
            
            dispatch_group_t group = dispatch_group_create();
            
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                QNUploadManager *upManager = [[QNUploadManager alloc] init];
                //        NSData *imageData = UIImageJPEGRepresentation(image,.7);
                __block NSString *newKey = [self createImagePath];
                if (oldKey == nil) {
                    oldKey = newKey;
                }
                
                [upManager putData:data key:oldKey token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                    if (info) {
                        // 上传成功
                        if (block != nil) {
                            block(key);
                        }
                    } else {
                        if (failBlock != nil) {
                            failBlock(@"上传失败");
                        }
                        //上传失败
//                        [AppDelegate.visibleController toast:@"上传失败"];
                    }
                    dispatch_group_leave(group);
                } option:nil];
            });
        }
        else
        {
            //token get fail
//            [AppDelegate.visibleController toast:response.message];
        }
    }];
}
- (void)getToken:(GetTokenType)type block:(returnImageUrlBlock)block failBlock:(returnFailBlock)failBlock
{
    NSDictionary *params = @{@"token_type" : @(type)};
    [GMNetworking requestOCWithApi:API_FACE_GET_TOKEN method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess)
        {
            //token get success
            NSDictionary *dict = response.data;
            NSString *token = dict[@"token"];
            block(token);
        }
        else
        {
            failBlock(@"token请求失败");
            //token get fail
//            [AppDelegate.visibleController toast:response.message];
        }
    }];
}
// 生成图片或者文件的路径
- (NSString *)createImagePath {
    NSString *imagePath = @"";
    // 1、先取 当前时间 按照 "年/月/日/时分" 转换 作为图片路径的上半部分--> 2018/10/25/1821
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval timeNow = [date timeIntervalSince1970];
    NSString *frontPart = [self getDateStringWithTimeStr:timeNow];
    
    imagePath = [imagePath stringByAppendingString:frontPart];
    
    // 2、取当前的时间戳 + 随机字符串(长度 32) 组成字符串，将该字符串 MD5哈希，取该哈希值的前 12位 作为图片路径的下半部分 --> caf8f8d86886
    NSString *timeNowStr = [NSString stringWithFormat:@"%.0f", timeNow];
    NSString *radomStr = [self getRadomString];
    NSString *secondPart = [timeNowStr stringByAppendingString:radomStr];
    
    NSString *secondPartMD5 = [[self MD5ForLower32Bate:secondPart] substringToIndex:12];
    
    return [NSString stringWithFormat:@"%@/%@", imagePath, secondPartMD5];
    
}

// 时间戳转字符串
- (NSString *)getDateStringWithTimeStr:(float )time{
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy/MM/dd/HHmm"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    
    return currentDateStr;
}

// 取随机字符串
- (NSString *)getRadomString {
    NSArray *array = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",nil];
    NSMutableArray *randomArray = [[NSMutableArray alloc] init];
    while (randomArray.count < 32) {
        int r = arc4random() % [array count];
        [randomArray addObject:[array objectAtIndex:r]];
    }
    return [randomArray componentsJoinedByString:@""];
}

// MD5加密
-(NSString *)MD5ForLower32Bate:(NSString *)str{
    
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    return digest;
}

@end
