//
//  CODownloadManager+Paper.m
//  WXQuestion
//
//  Created by hyz on 2019/4/1.
//  Copyright © 2019 中公网校. All rights reserved.
//

#import "CODownloadManager+Paper.h"
#import "CODownloadObject.h"
#import "WXCOMacros.h"
#import "WXCOUtility.h"

@implementation CODownloadManager (Paper)

- (void)co_startPaperDownload:(NSMutableArray <CODownloadPaperModel *>*)paperArray
                       userID:(NSString *)userID
          downloadRejectBlock:(nullable void (^)(NSMutableArray <CODownloadRejectModel *> * _Nullable rejectArray))block
         withPriorityDownload:(BOOL)isPriority {
    NSMutableArray *downloadArray; // 要进入自己封装的下载器中的对象集合
    NSMutableArray *rejectArray; // 不满足下载条件数据集合
    if (paperArray.count > 0) {
        rejectArray = [NSMutableArray arrayWithCapacity:10];
        downloadArray = [NSMutableArray arrayWithCapacity:paperArray.count];
        self.newDownloadModels = nil;
        
        for (CODownloadPaperModel *model in paperArray) {
            DownloadRejectReason reason = [self co_checkPaperCanDownload:model];
            if (reason != DownloadRejectReasonCanDownload) {
                CODownloadRejectModel *rejectModel = [[CODownloadRejectModel alloc] init];
                rejectModel.lesson_id = model.paper_id;
                rejectModel.lesson_type = COLessonTypePdf;
                rejectModel.reason = reason;
                rejectModel.lesson_name = model.paper_name;
                [rejectArray addObject:rejectModel];
                continue;
            }
            
            CODownloadObject *downloadObject = [self co_createDownloadObjectByPaperModel:model];
            if (WXCOIsNilOrNull(downloadObject) == NO) {
                [downloadArray addObject:downloadObject];
            }
        }
    }
    
    [CODownloadModel batchAddDownloadModel2Database:self.newDownloadModels userID:userID];
    [self co_startDownload:downloadArray downloadRejectBlock:block subjoinRejectionArray:rejectArray
      withPriorityDownload:isPriority];
}

- (void)co_pausePaperDownload:(NSMutableArray <CODownloadPaperModel *>*)paperArray {
    [self co_pauseDownload:[self co_getDownloadObjectByPaperModelArray:paperArray]];
}

- (void)co_deletePaperDownload:(NSMutableArray <CODownloadPaperModel *>*)paperArray
            withViewController:(UIViewController *)presentVc
                        userID:(NSString *)userID
                   cancelBlock:(nullable void(^)(BOOL cancel))block {
    if (paperArray == nil || paperArray.count <= 0) { // 没发现可以删除的对象
        [WXCOUtility showAlertWithMessage:@"此次操作中没有发现可删除的文件"];
        
        if (WXCOIsNilOrNull(block) == NO) {
            block(YES);
        }
        return;
    }
    
    if (presentVc == nil) {
        presentVc = [WXCOUtility getCurrentVC];
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:
                                  [NSString stringWithFormat:@"确定要%ld删除项下载任务吗？", (long)paperArray.count]
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelActoin = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             if (WXCOIsNilOrNull(block) == NO) {
                                                                 block(YES);
                                                             }
                                                         }];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             if (WXCOIsNilOrNull(block) == NO) {
                                                                 block(NO);
                                                             }
                                                             [weakSelf co_deleteDownload:[self co_getDownloadObjectByPaperModelArray:paperArray] userID:userID];
                                                         }];
    [alertVc addAction:cancelActoin];
    [alertVc addAction:deleteAction];
    [presentVc presentViewController:alertVc animated:YES completion:nil];
}

- (CODownloadObject *)co_getDownloadObjectByPaperModel:(CODownloadPaperModel *)model {
    if (model == nil || WXCOStringIsEmpty(model.download_url) == YES) {
        return nil;
    }
    
    return [self co_getDownloadObjectByUrl:model.download_url];
}

#pragma mark - Private Methods

/// 通过试卷模型数据生成下载对象，如果已经存在则直接返回，否则新创建；PS:创建时特别注意如果该课件类型不满足下载条件，则会返回nil
/// @param model 试卷数据模型
/// @return 下载数据对象
- (CODownloadObject *)co_createDownloadObjectByPaperModel:(CODownloadPaperModel *)model {
    CODownloadObject *object = [self co_getDownloadObjectByPaperModel:model];
    if (object == nil) { // 如果还未执行过下载
        if ([self co_checkPaperCanDownload:model] == DownloadRejectReasonCanDownload) { // 满足下载条件
            object = [[CODownloadObject alloc] initWithDownloadObject:[self co_createDownloadModelForPaperModel:model]];
            [self.allDownloads addObject:object];
            [self.downloadingQueue addObject:object];
        }
    }
    return object;
}

/// 通过试卷信息创建下载模型数据
/// @param paperModel 课件信息
/// @return 下载模型数据
- (CODownloadModel *)co_createDownloadModelForPaperModel:(CODownloadPaperModel *)paperModel {
    CODownloadModel *model = [[CODownloadModel alloc] init];
    model.course_id = paperModel.paper_id;
    model.course_name = paperModel.paper_name;
    model.current_size = 0;
    model.down_date = [WXCOUtility getTimeNow];
    model.down_name = paperModel.paper_name;
    model.down_state = stateNoDownload;
    model.down_url = paperModel.download_url;
    model.lesson_id = [NSString stringWithFormat:@"%@", paperModel.paper_id];
    model.offline_code = @"";
    model.lesson_type = COLessonTypePdf;
    model.live_type = 0;
    model.file_name = @"";
    model.total_size = paperModel.pdf_size.integerValue;
    model.video_length = @"";
    model.pdf_type = COPdfTypePaper;
    model.difficulty = paperModel.difficulty;
    model.paper_content = paperModel.content;
    model.paper_type = paperModel.examType;
    model.paper_pattern = paperModel.paper_pattern;
    model.mock_paper_id = paperModel.mock_paper_id;
    model.mock_id = paperModel.mock_id;
    model.need_sync = needSyncValueYES;
    model.is_show = isShowValueYES;
    model.check_expired = checkExpiredValueNO;
    
    [self.newDownloadModels addObject:model]; // 新生成的下载模型数据
    return model;
}

/// 通过试卷模型数据获取下载对象
/// @param paperArray 试卷数据集合
/// @return 下载对象集合
- (NSMutableArray <CODownloadObject *> *)co_getDownloadObjectByPaperModelArray:(NSMutableArray <CODownloadPaperModel *>*)paperArray {
    if (paperArray == nil || paperArray.count <= 0) {
        return nil;
    }
    
    NSMutableArray *downloadArray = [NSMutableArray arrayWithCapacity:paperArray.count];
    for (CODownloadPaperModel *model in paperArray) {
        if ([self co_checkPaperCanDownload:model] != DownloadRejectReasonCanDownload) {
            continue;
        }
        
        // 从下载对象集合获取下载对象
        CODownloadObject *downloadObject = [self co_getDownloadObjectByPaperModel:model];
        if (WXCOIsNilOrNull(downloadObject) == NO) { // 课件存在下载对象
            [downloadArray addObject:downloadObject];
        }
    }
    
    return downloadArray;
}

/// 检测试卷文件是否支持下载
/// @param paperModel 试卷文件模型数据
/// @return 是否可以被下载
- (DownloadRejectReason)co_checkPaperCanDownload:(CODownloadPaperModel *)paperModel {
    if (WXCOIsNilOrNull(paperModel)) {
        return DownloadRejectReasonEmptyData;
    }
    
    if (WXCOIsNilOrNull(paperModel.download_url) == YES || paperModel.download_url.length <= 0) { // 下载地址为空
        return DownloadRejectReasonEmptyURL;
    }
    return DownloadRejectReasonCanDownload;
}

@end
