//
//  GMAIUploadImagesManager.m
//  Gengmei
//
//  Created by 卢悦明 on 2020/5/14.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMAIUploadImagesManager.h"
#import "GMEditPhotoInfo.h"
#import "QiniuSDK.h"
#import<CommonCrypto/CommonDigest.h>
@import GMNetworking;
@import GMFoundation;
@import GMKit;
@interface GMAIUploadImagesManager()
@property (nonatomic, assign) BOOL isAllImageUploadSuccess;
///**
// 图片token(必传)
// */
//@property (nonatomic, copy) NSString *imageToken;

@end

@implementation GMAIUploadImagesManager
static GMAIUploadImagesManager *shareInstance = nil;

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[GMAIUploadImagesManager alloc] init];
    });
    return shareInstance;
}

- (void)getTokenWithType:(GMAITokenType)type resultBlock:(UploadFinishedBlock)resultBlock {
    NSDictionary *params = @{@"token_type" : @(type)};
    [GMNetworking requestOCWithApi:@"/api/app/upload_token" method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess) {
            //token get success
            NSDictionary *dict = response.data;
            resultBlock(response.isSuccess, dict[@"token"]);
        } else {
            resultBlock(NO, response.message);
        }
    }];
}

-(void)uploadImages:(NSArray *)images imageToken:(NSString *)imageToken resultBlock:(UploadFinishedBlock)resultBlock {
    __weak typeof(self)weakSelf = self;
    _isAllImageUploadSuccess = YES;
        _resultImages = [NSMutableArray arrayWithArray:images];
        dispatch_group_t group = dispatch_group_create();
        NSInteger index = 0;
        for (GMEditPhotoInfo *obj in images) {
            [self uploadImage:obj imageToken:imageToken objIndex:index dispatchGroup:group];
            index++;
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            if (weakSelf.isAllImageUploadSuccess == NO) {
                resultBlock(NO, @"");
            } else {
                resultBlock(YES, @"");
            }
        });
}

- (void)uploadImage:(GMEditPhotoInfo *)imageObj imageToken:(NSString *)imageToken objIndex:(NSInteger)objIndex  dispatchGroup:(dispatch_group_t)dispatchGroup {
    if (imageObj.finshedImage) {
        __weak typeof(self)weakSelf = self;
        dispatch_group_enter(dispatchGroup);
        dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            if (imageToken) {
                NSData *imageData = UIImageJPEGRepresentation(imageObj.finshedImage, 1);
                NSString *key = [self createImagePath];
                [upManager putData:imageData key:key token:imageToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                    if (info.isOK) {
                        // 上传成功
                        NSInteger index = [self.resultImages indexOfObject:imageObj];
                        [weakSelf.resultImages replaceObjectAtIndex:index withObject:[weakSelf allImageInfoWithPhoto:imageObj key:key]];
                    } else {
                        //上传失败
                        weakSelf.isAllImageUploadSuccess = NO;
                    }
                    dispatch_group_leave(dispatchGroup);
                } option:nil];
            } else {
                weakSelf.isAllImageUploadSuccess = NO;
                dispatch_group_leave(dispatchGroup);
            }
        });
    } else {
        NSInteger index = [self.resultImages indexOfObject:imageObj];
        [self.resultImages replaceObjectAtIndex:index withObject:[self allImageInfoWithPhoto:imageObj key:@""]];
    }
}

- (NSDictionary *)allImageInfoWithPhoto:(GMEditPhotoInfo *)photo key:(NSString *)key {
    NSMutableDictionary *image = [NSMutableDictionary dictionary];
    if ([key isNonEmpty]) { // 本地图片上传成功后
        [image setObject:key forKey:@"image"];
        [image setObject:@(photo.asset.pixelWidth) forKey:@"width"];
        [image setObject:@(photo.asset.pixelHeight) forKey:@"height"];
    } else { // 编辑图片的URL
        [image setObject:photo.photoPath.absoluteString forKey:@"image"];
        [image setObject:@(photo.pixelWidth) forKey:@"width"];
        [image setObject:@(photo.pixelHeight) forKey:@"height"];
    }
    return image;
}


// 生成图片路径
- (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;
}

+ (NSDictionary *)imageInfoWithPath:(NSString *)path width:(NSInteger)width height:(NSInteger)height {
    return @{@"image_url": SafeString(path),
              @"width":@(width),
              @"height":@(height),
              @"type": @"image"
    };;
}

// 取随机字符串
- (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
