//
//  ALCreateTopicViewModel.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/7.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "ALCreateTopicViewModel.h"
#import "ALCreateDiaryObject.h"
#import "ALCreateTopicListObject.h"
#import <CommonCrypto/CommonDigest.h>
#import "GMPhotoTools.h"
#import "ALUpLoadManager.h"
@import Qiniu;

@interface ALCreateTopicViewModel ()
//视频是否走过上传流程
@property (nonatomic, assign) BOOL isVideoPush;
//图片是否走完上传流程
@property (nonatomic, assign) BOOL isImagePush;
//请求接口的参数
@property (nonatomic, assign) NSInteger fromInType;
@end

@implementation ALCreateTopicViewModel

- (instancetype)initWithType:(FromWhereComeIn)type{
    self = [super init];
    if (self) {
        _remoteUrl = API_GROUP_USERLIST;
        self.fromInType = type;
        if (self.fromInType == FromWhereComeInDetail) {
            self.fromInType = FromWhereComeInCreat;
        }
    }
    return self;
}

- (void)buildParams{
    _params = @{
                @"user_id":@([GMLoginManager shareInstance].user.userId),
                @"page":@(self.page),
                @"count":@(10),
                @"type":@(self.fromInType)
                };
}

- (void)buildModelWithRemoteDic:(NSDictionary *)dic {
    NSDictionary *data = dic[@"data"];
    if (data[@"groups"]) {
        [self.dataArray addObjectsFromArray:[ALCreateTopicListObject arrayOfModelsFromDictionaries:data[@"groups"] error:nil]];
    }
}

- (void)uploadImagesAndVideoSuccessBlock:(HttpSuccessBlock)successBlock failBlock:(HttpFailedBlock)failBlock {
    _isAllImageAndVideoUploadSuccess = YES;
    dispatch_group_t group = dispatch_group_create();

    if (self.diaryObj.images.count == 0) {
        self.isImagePush = YES;
    }
    if (!self.diaryObj.videoModel.fileURL) {
        self.isVideoPush = YES;
    }
    
    [self uploadTopicObject:self.diaryObj dispatchGroup:group successBlock:successBlock failBlock:failBlock];
    
    // 有视频且视频上传失败的时候上传
    if (self.diaryObj.videoModel.fileURL) {
        //        dispatch_group_enter(group);
        //        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self uploadVideoOfObject:self.diaryObj dispatchGroup:group successBlock:successBlock failBlock:failBlock];
        //        });
    }
    //    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    if (self.isAllImageAndVideoUploadSuccess == NO) {
        failBlock(@"上传失败");
        return;
    }
    if (self.isVideoPush == YES && self.isImagePush == YES) {
        [self publishTopicWithSuccessBlock:^(id responseObject) {
            successBlock(responseObject);
        } failBlock:^(NSString *message) {
            failBlock(@"上传失败");
        }];
    }

    
//    });
}
- (void)uploadTopicObject:(ALCreateDiaryObject *)obj dispatchGroup:(dispatch_group_t)dispatchGroup successBlock:(HttpSuccessBlock)successBlock failBlock:(HttpFailedBlock)failBlock {
    
    __block NSInteger num = 0;
    for (NSInteger i = 0; i < obj.images.count; i++){
        GMPhotoModel *imageObj = obj.images[i];
        __weak __typeof(self)weakSelf = self;
        if (!imageObj.isUploadSuccess) {
            
            if (imageObj.thumbPhoto) {
                NSData *imageData = UIImageJPEGRepresentation(imageObj.thumbPhoto, .7);
                [[ALUpLoadManager shareInstance] setData:imageData getTokenType:(GetTokenTypeImage) key:nil block:^(NSString *path) {
                    imageObj.image = path;
                    imageObj.imageName = path;
                    imageObj.isUploadSuccess = YES;
                    num++;
                    if (num == obj.images.count) {
                        //不管是否上传成功，走完上传了
                        self.isImagePush = YES;
                        [self publishTopicWithSuccessBlock:^(id responseObject) {
                            successBlock(responseObject);
                        } failBlock:^(NSString *message) {
                            failBlock(@"图片上传失败");
                        }];
                    }
                } failBlock:^(NSString *message) {
                    num++;
                    weakSelf.isAllImageAndVideoUploadSuccess = NO;
                    imageObj.isUploadSuccess = NO;
                    if (num == obj.images.count) {
                        //不管是否上传成功，走完上传了
                        self.isImagePush = YES;
                        [self publishTopicWithSuccessBlock:^(id responseObject) {
                            successBlock(responseObject);
                        } failBlock:^(NSString *message) {
                            failBlock(@"图片上传失败");
                        }];
                    }
                }];
            }
            else
            {
                imageObj.isUploadSuccess = NO;
                self.isAllImageAndVideoUploadSuccess = NO;
                
            }
        }
        
    }
}

- (void)publishTopicWithSuccessBlock:(HttpSuccessBlock)successBlock failBlock:(HttpFailedBlock)failBlock {
    //构造参数
    if (self.isVideoPush == YES && self.isImagePush == YES) {
        NSDictionary *params = [self toJsonDictWithObject:self.diaryObj];
        [GMNetworking requestOCWithApi:API_TOPIC_CTEATE method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC *responseObject) {
            if (responseObject.isSuccess) {
                successBlock(responseObject);
            } else {
                failBlock(responseObject.message);
            }
        }];
        self.isVideoPush = NO;
        self.isImagePush = NO;
    }

}

- (NSDictionary *)toJsonDictWithObject:(ALCreateDiaryObject *)obj {
    // 处理图片数组
    NSMutableArray *images = [NSMutableArray array];
    for (GMPhotoModel *imageObj in obj.images) {
        // TODO : GMPhotoModel 初始化给它这几个属性赋默认值
        NSMutableDictionary *item = [NSMutableDictionary dictionary];
        [item setValue:imageObj.image forKey:@"url"];
        [item setValue:[NSString stringWithFormat:@"%.0lf",imageObj.imageSize.width?:300] forKey:@"width"];
        [item setValue:[NSString stringWithFormat:@"%.0lf",imageObj.imageSize.height?:400] forKey:@"height"];
        [images addObject:item];
    }
    NSString *jsonImage = [self toJSONString:images];
    // 处理整个object
    NSMutableDictionary *objDic = [NSMutableDictionary dictionary];
    if ([obj.videoModel.video isNonEmpty]) {
      NSDictionary *videoDic  = @{@"url": SafeString(obj.videoModel.video),
                                  @"width": [NSString stringWithFormat:@"%.0lf",obj.videoModel.imageSize.width?:300],
                                  @"height": [NSString stringWithFormat:@"%.0lf",obj.videoModel.imageSize.height?:400]
            };
        NSString *videoStr = [self convertToJsonData:videoDic];
        [objDic setObject:videoStr  forKey:@"video_url"];

    }
//    NSString *jsonVideo = [self toJSONString:objDic];
    if (images.count>0) {
        [objDic setObject:jsonImage forKey:@"images"];
    }
    [objDic setObject:SafeString(obj.content) forKey:@"content"];
    [objDic setObject:SafeString(obj.groupId) forKey:@"group_id"];
    return objDic;
}
/** 数组转json */
- (NSString *)toJSONString:(NSMutableArray *)array {
    NSData *data = [NSJSONSerialization dataWithJSONObject:array
                                                   options:NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
                                                     error:nil];
    if (data == nil) {
        return nil;
    }
    NSString *string = [[NSString alloc] initWithData:data
                                             encoding:NSUTF8StringEncoding];
    return string;
}
/** 字典转json */
-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

// 上传视频
- (void)uploadVideoOfObject:(ALCreateDiaryObject *)obj dispatchGroup:(dispatch_group_t)dispatchGroup successBlock:(HttpSuccessBlock)successBlock failBlock:(HttpFailedBlock)failBlock {
    __weak typeof (self)weakSelf = self;
    [GMPhotoTools compressedVideoAndWriteVideoToTemp:obj.videoModel.fileURL success:^(NSURL *url) {
        NSError *error = nil;
        NSData *videoData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
        if (error) {
            NSLog(@"%@", [error localizedDescription]);
        } else {
            NSLog(@"Data has loaded successfully.");
        }
        NSArray *array = [url.path componentsSeparatedByString:@"."];
        NSString *key = [NSString stringWithFormat:@"%d_%.0f", 1, [[NSDate date] timeIntervalSince1970]];
        NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
        NSString *base64Key = [NSString stringWithFormat:@"%@.%@", [keyData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength], array.lastObject];
        NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        //upprogress文件夹用来存储上传进度, 七牛自动实现记录, 无需别的操作
        NSString *fileUrl = [document stringByAppendingPathComponent:@"upprogress"];
        //传入断点记录的代理
        QNFileRecorder *file = [QNFileRecorder fileRecorderWithFolder:fileUrl error:nil];
        //创建带有断点记录代理的上传管理着
        QNUploadManager *upManager = [[QNUploadManager alloc] initWithRecorder:file];
        
        // TODO: 上传视频的时候是否可以直接通过路径来传？
        [[ALUpLoadManager shareInstance] getToken:(GetTokenTypeVideo) block:^(NSString *path) {
            if (path) {
                [upManager putData:videoData key:base64Key token:path complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                    if (info.isOK) {
                        obj.videoModel.video = key;
                        obj.isVideoUploadSuccess = YES;
                        self.isVideoPush = YES;
                        [self publishTopicWithSuccessBlock:^(id responseObject) {
                            successBlock(responseObject);
                        } failBlock:^(NSString *message) {
                            failBlock(@"视频上传失败");
                        }];
                    } else {
                        self.isVideoPush = YES;
                        obj.isVideoUploadSuccess = NO;
                        weakSelf.isAllImageAndVideoUploadSuccess = NO;
                        [self publishTopicWithSuccessBlock:^(id responseObject) {
                            successBlock(responseObject);
                        } failBlock:^(NSString *message) {
                            failBlock(@"视频上传失败");
                        }];
                    }
                } option:nil];
            }
        } failBlock:^(NSString *message) {
            obj.isVideoUploadSuccess = NO;
            weakSelf.isAllImageAndVideoUploadSuccess = NO;
            dispatch_group_leave(dispatchGroup);
        }];
        
    } failure:^{
        obj.isVideoUploadSuccess = NO;
        weakSelf.isAllImageAndVideoUploadSuccess = NO;
        
    }];
}

// 生成图片路径
- (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;
}
- (ALCreateDiaryObject *)diaryObj {
    if (!_diaryObj) {
        _diaryObj = [[ALCreateDiaryObject alloc] init];
    }
    return _diaryObj;
}
@end
