//
//  UploadManager.m
//  patrol
//
//  Created by 曹云霄 on 2017/2/8.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "UploadManager.h"
#import "OSSHelper.h"

@implementation UploadResponse



@end


@implementation UploadManager



/**
 获取App配置项
 */
+ (void)getAppOption {
    NSString *string = @"{\"accessKey\":\"LTAIiRWdyPrLTinG\",\"secretKey\":\"nWBZDNaGf6CWL8FhQt0eJB8Y0xpUOd\",\"endPoint\":\"oss-cn-shanghai.aliyuncs.com\",\"bucketName\":\"total-gomore\", \"region\":\"oss-cn-shanghai\",\"imgEndpoint\":\"total-gomore.img-cn-shanghai.aliyuncs.com\", \"width\":\"200\", \"height\":\"200\"}";
    
    AccountConfigModel_uploadType *uploadType = [[AccountConfigModel_uploadType alloc] initWithString:string error:nil];
    if ([uploadType.ossType isEqualToString:@"COS"]) {
        uploadType.type = @"COS";
    }else {
        uploadType.type = @"OSS";
    }
    AccountConfigModel *configModel = [AccountConfigModel new];
    configModel.uploadType = uploadType;
    kUser.configModel = configModel;
}

/**
 上传附件

 @param array 附件列表
 @param completed 成功
 @param failed 失败
 */
+ (void)uploadObjectArray:(NSArray<PostAttachmentModel *>*)array completed:(void (^)(UploadResponse *success))completed failed:(void(^)(NSString *error))failed
{
    [[self class] getAppOption];
    //判断上传所需配置项是否为空
    if ([ToolsManager empty:kUser.configModel.uploadType.accessKey] || [ToolsManager empty:kUser.configModel.uploadType.secretKey] || [ToolsManager empty:kUser.configModel.uploadType.endPoint] || [ToolsManager empty:kUser.configModel.uploadType.bucketName]) {
        ShowAlertView(@"提示", @"上传配置项获取失败，暂时无法上传附件", @[@"我知道了"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            failed(@"上传配置项获取失败，暂时无法上传附件");
        });
    }else {
        //处理视频缩略图、图片缩略图
        NSMutableArray *attachmentArray = [NSMutableArray array];
        for (int i=0; i<array.count; i++) {
            PostAttachmentModel *attachmentModel = array[i];
            switch (attachmentModel.attachmentType) {
                case ATTACHMENT_VIDEO:
                {
                    PostAttachmentModel *model = [[PostAttachmentModel alloc] initWithDictionary:[attachmentModel toDictionary] error:nil];
                    model.fileUrl = attachmentModel.thumbnailUrl;
                    model.attachmentType = ATTACHMENT_IMAGE;
                    [attachmentArray addObject:model];
                }
                    break;
                case ATTACHMENT_IMAGE:
                {
                    UIImage *image = [UIImage imageWithContentsOfFile:attachmentModel.fileUrl];
                    UIImage *thumbnailImage = [image rescaleImageToSize:CGSizeMake(200, 200)];
                    NSData *imageData = UIImageJPEGRepresentation(thumbnailImage, 1);
                    NSString *imageName = [ToolsManager md5Data:imageData];
                    NSString *thumbnailPath = [kPathDocument stringByAppendingPathComponent:imageName];
                    [imageData writeToFile:thumbnailPath atomically:NO];
                    attachmentModel.thumbnailUrl = thumbnailPath;
                    PostAttachmentModel *model = [[PostAttachmentModel alloc] initWithDictionary:[attachmentModel toDictionary] error:nil];
                    model.fileUrl = thumbnailPath;
                    model.attachmentType = ATTACHMENT_IMAGE;
                    [attachmentArray addObject:model];
                }
                    break;

                default:
                    break;
            }
            [attachmentArray addObject:attachmentModel];
        }
        if ([kUser.configModel.uploadType.type isEqualToString:@"OSS"]) {
            [[self class] uploadPhotoOrVideoByOSS:attachmentArray completed:^(id success) {
                completed(success);
            } failed:^(id error) {
                failed(error);
            }];
        }
    }
}


+ (UPLOAD_TYPE)getUploadType {
    if ([kUser.configModel.uploadType.type isEqualToString:@"OSS"]) {
        return UPLOAD_THIRDPARTY;
    }else if ([kUser.configModel.uploadType.type isEqualToString:@"COS"]) {
        return UPLOAD_THIRDPARTY;
    }else {
        return UPLOAD_COMMON;
    }
}

#pragma mark - 生成图片、视频缩略图--->通过OSS上传
+ (void)uploadPhotoOrVideoByOSS:(NSMutableArray<PostAttachmentModel *> *)array completed:(void (^)(id success))completed failed:(void(^)(id error))failed {

    NSMutableArray *attachmentArray = [NSMutableArray array];
    for (int i=0; i<array.count; i++) {
        PostAttachmentModel *attachmentModel = array[i];
        kUser.configModel.uploadType.imagePath = [NSString stringWithFormat:@"%@/image/%@",kUser.f_authenticode,attachmentModel.entityType];
        kUser.configModel.uploadType.videoPath = [NSString stringWithFormat:@"%@/video/%@",kUser.f_authenticode,attachmentModel.entityType];
        switch (attachmentModel.attachmentType) {
            case ATTACHMENT_VIDEO:
            {
                attachmentModel.entityUuid = [OSSHelper getOSSObjectKeyWithtype:@"mp4" index:i];
                attachmentModel.entityUrl = [OSSHelper getCompleteVideoURLWithOSSkey:attachmentModel.entityUuid];
            }
                break;
            case ATTACHMENT_IMAGE:
            {
                attachmentModel.entityUuid = [OSSHelper getOSSObjectKeyWithtype:@"jpg" index:i];
                attachmentModel.entityUrl = [OSSHelper getCompleteImageURLWithOSSkey:attachmentModel.entityUuid];
            }
                break;
            default:
                break;
        }
        attachmentModel.fileName = [[attachmentModel.entityUrl componentsSeparatedByString:@"/"] lastObject];
        [attachmentArray addObject:attachmentModel];
    }
    NSArray *newArray = [[self class] combinationFileUrlAndThumbnailUrl:attachmentArray];
    if (attachmentArray.count) {
        [self uploadToOSSAttachments:newArray completed:^(id success) {
            completed(success);
        } failed:^(id error) {
            failed(error);
        }];
    }
}

#pragma mark - OSS上传附件
+ (void)uploadToOSSAttachments:(NSArray<PostAttachmentModel *> *)array completed:(void (^)(id success))completed failed:(void(^)(id error))failed {
   __block NSInteger index = 1; //记录当前上传的个数
    MBProgressHUD *hud = ShowDefaultProgressView([NSString stringWithFormat:@"%@%ld/%ld",@"上传中",index,(unsigned long) array.count/2], MBProgressHUDModeDeterminateHorizontalBar);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [array enumerateObjectsUsingBlock:^(PostAttachmentModel *model, NSUInteger idx,BOOL *_Nonnull stop) {
            NSString *objectKey = nil;
            NSString *imagePath = model.fileUrl ? model.fileUrl : model.thumbnailUrl;
            NSData *data = [NSData dataWithContentsOfFile:imagePath];
            switch (model.attachmentType) {
                case ATTACHMENT_IMAGE:
                {
                    objectKey = [NSString stringWithFormat:@"%@/%@/%@",kUser.configModel.uploadType.imagePath,[[NSDate date] yearMonthDayString],model.entityUuid];
                }
                    break;
                case ATTACHMENT_VIDEO:
                {
                    objectKey = [NSString stringWithFormat:@"%@/%@/%@",kUser.configModel.uploadType.videoPath,[[NSDate date] yearMonthDayString],model.entityUuid];
                }
                    break;
                default:
                    break;
            }
            [OSSHelper uploadFileObjectWithKey:objectKey data:data type:OSSHelperOperationTypeSynchronous progress:^(double progress) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    hud.progress = progress;
                });
            } success:^(OSSTask *task) {
                if (index%2 == 0) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        hud.labelText = [NSString stringWithFormat:@"%@%ld/%ld",@"上传中",(long) index/2, array.count/2];
                    });
                }
                index++;
                if (index == array.count + 1) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        hud.labelText = @"上传成功";
                        UploadResponse *result = [[UploadResponse alloc] init];
                        result.type = UPLOAD_THIRDPARTY;
                        result.response = array;
                        completed(result);
                        [hud hide:YES afterDelay:0.5];
                    });
                }

            } error:^(NSError *error) {
                *stop = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    hud.labelText = @"上传失败";
                    failed(error.localizedDescription);
                    [hud hide:YES afterDelay:0.5];
                });
            }];
        }];
    });
}



#pragma mark -组合附件和缩略图
+ (NSArray *)combinationFileUrlAndThumbnailUrl:(NSArray<PostAttachmentModel *>*)array
{
    NSArray *thumbnailArray = [array copy];
    for (int i=0; i<array.count; i++) {
        PostAttachmentModel *model = array[i];
        for (int j=0 ; j<thumbnailArray.count; j++) {
            PostAttachmentModel *thumbnailModle = thumbnailArray[j];
            if ([model.thumbnailUrl isEqualToString:thumbnailModle.fileUrl]) {
                model.thumbnailUrl = thumbnailModle.entityUrl;
                model.thumbnailName = [[thumbnailModle.entityUrl componentsSeparatedByString:@"/"] lastObject];
            }
        }
    }
    return array;
}



@end

