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

#import "ALUpLoadManager.h"
#import "QNUploadManager.h"
#import "QNResponseInfo.h"
#import "QNConfiguration.h"
#import <CommonCrypto/CommonDigest.h>
#import "QNConfiguration.h"


@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:(NSString *)filePath token:(NSString*)token 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), ^{
            QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
                builder.timeoutInterval = 60;
            }];
            QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config];
            NSString *key = [self createImagePath];
            [upManager putFile:filePath key:key token:token complete:^(QNResponseInfo *info, NSString *key,NSDictionary *resp) {
                if (info.ok) {
                    // 上传成功
                    if (block != nil) {
                        block(key);
                    }
                } else {
                    if (failBlock != nil) {
                        failBlock(@"上传失败");
                    }
                }
                dispatch_group_leave(group);
            } option:nil];
        });
    };



// 生成图片或者文件的路径
- (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:@"%lld", 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
