//
//  TWDocumentVC.m
//  sfs
//
//  Created by fishxiaou on 16/12/5.
//  Copyright © 2016年 fishxiaou. All rights reserved.
//

#import "TWDocumentVC.h"

#define DocumentNavBarTintColor [UIColor colorWithRed:77/255.0 green:208/255.0 blue:200/255.0 alpha:1]

#define DocumentNavTintColor [UIColor whiteColor]

@interface TWDocumentVC ()<UIDocumentInteractionControllerDelegate>

/** 路径 */
@property (nonatomic,strong) NSURL *sourceUrl;
/** 预览类 */
@property (strong, nonatomic) UIDocumentInteractionController *documentInteractionController;

@end

@implementation TWDocumentVC

+(void)showWihtSourceUrl:(NSURL *)url fromViewController:(UIViewController *)superViewController {
    TWDocumentVC * showView = [[TWDocumentVC alloc]initWithNibName:nil bundle:nil];
    showView.sourceUrl = url;
    UINavigationController *fileNavi = [[UINavigationController alloc]initWithRootViewController:showView];
    fileNavi.navigationBar.translucent = false;
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance * appearance = [[UINavigationBarAppearance alloc] init];
        appearance.shadowColor = DocumentNavTintColor;
        appearance.backgroundColor = DocumentNavTintColor;
        appearance.titleTextAttributes = @{NSForegroundColorAttributeName : UIColor.blackColor, NSFontAttributeName : [UIFont systemFontOfSize:18.0f]};
        fileNavi.navigationBar.standardAppearance = appearance;
        fileNavi.navigationBar.scrollEdgeAppearance = appearance;
        fileNavi.navigationBar.tintColor = UIColor.blackColor;
    } else {
        fileNavi.navigationBar.tintColor = UIColor.blackColor;
        fileNavi.navigationBar.barTintColor = DocumentNavBarTintColor;
        fileNavi.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : UIColor.blackColor, NSFontAttributeName : [UIFont systemFontOfSize:18.0f]};
    }
    UIViewController *superView = superViewController;
    superView.modalPresentationStyle = UIModalPresentationOverFullScreen;
    superView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    while (superView.presentedViewController)
    {
        superView = superView.presentedViewController;
    }
    [superView presentViewController:fileNavi animated:true completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"文件导入";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismissDecumentView)];
    
    [self initUI];
}

-(void)initUI {
    if (self.sourceUrl == nil) { return; }
    NSString *fileName = [self fileName];
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UIImageView *iconView = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth*0.5 -  45, 30 , 90, 90)];
    [iconView setImage:[UIImage imageNamed:[DocumentTools fileExtension:fileName]]];
    [self.view addSubview:iconView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 130, screenWidth, 22)];
    titleLabel.text = [fileName stringByDeletingPathExtension];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:titleLabel];
    
    UIButton *openBnt = [UIButton buttonWithType:UIButtonTypeCustom];
    [openBnt setFrame:CGRectMake( 50, 180, screenWidth - 100, 44)];
    [openBnt setTitle:@"打开文件" forState:UIControlStateNormal];
    [openBnt setBackgroundColor:[UIColor colorWithRed:84/255.0 green:190/255.0 blue:248/255.0 alpha:1]];
    openBnt.layer.cornerRadius = 6;
    openBnt.layer.masksToBounds = YES;
    [openBnt addTarget:self action:@selector(previewDocument:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:openBnt];
    
    UIButton *saveBnt = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBnt setFrame:CGRectMake(50, 260, screenWidth - 100, 44)];
    [saveBnt setTitle:@"保存文件" forState:UIControlStateNormal];
    [saveBnt setBackgroundColor:[UIColor colorWithRed:71/255.0 green:195/255.0 blue:184/255.0 alpha:1]];
    saveBnt.layer.cornerRadius = 6;
    saveBnt.layer.masksToBounds = YES;
    [saveBnt addTarget:self action:@selector(saveDocument:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBnt];
}

-(void)dismissDecumentView {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 获取文件名称
-(NSString *)fileName {
    NSString * filePath = [self.sourceUrl absoluteString];
    NSString * utf8Path = filePath.stringByRemovingPercentEncoding;
    return [utf8Path lastPathComponent];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 预览
- (void)previewDocument:(UIButton *)sender {
    if (self.sourceUrl) {
        self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:self.sourceUrl];
        [self.documentInteractionController setDelegate:self];
        [self.documentInteractionController presentPreviewAnimated:YES];
    }
}

#pragma mark Document Interaction Controller Delegate Methods
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
    return self;
}

#pragma mark - 保存
- (void)saveDocument:(UIButton *)sender {
    DocumentTools *tool = [[DocumentTools alloc]init];
    BOOL ok = [tool saveFileToApp:self.sourceUrl];
    if (ok) {
        UIAlertController* alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存到本地成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertC addAction:okAction];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

@end

typedef void(^DocumentCall)(float,bool);

@interface DocumentTools()<NSURLSessionDownloadDelegate>
/** 本地文件夹 */
@property (nonatomic,copy) NSString * localPath;
/** 文件名称 */
@property (nonatomic,copy) NSString * curFileName;
/** 进度回调 */
@property (nonatomic,strong) DocumentCall documentCall;
@end

@implementation DocumentTools

-(NSMutableArray *)fileArr {
    if (_fileArr == nil) {
        NSFileManager *fileManage = [NSFileManager defaultManager];
        NSArray *names = [fileManage contentsOfDirectoryAtPath:self.localPath error:nil];
        _fileArr = [NSMutableArray arrayWithCapacity:6];
        for (NSString *theName in names) {
            NSMutableDictionary * theDoc = [NSMutableDictionary dictionaryWithCapacity:4];
            NSString *fullPath = [self.localPath stringByAppendingPathComponent:theName];
            [theDoc setValue:fullPath forKey:@"fullpath"];
            [theDoc setValue:theName forKey:@"name"];
            [theDoc setValue:[DocumentTools getCreatDate:fullPath] forKey:@"time"];
            [theDoc setValue:[DocumentTools getDataCount:fullPath] forKey:@"count"];
            [_fileArr addObject:theDoc];
        }
    }
    return _fileArr;
}

-(NSString *)localPath{
    if (_localPath == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex:0];
        _localPath = [docDir stringByAppendingPathComponent:@"TWFile"];
        [self checkPath:_localPath];
    }
    return _localPath;
}

-(NSString *)theTWDocumentPatch{
    return self.localPath;
}

// 检查目录
-(void)checkPath:(NSString *)path {
    NSFileManager *fileManage = [NSFileManager defaultManager];
    BOOL fileExist = [fileManage fileExistsAtPath:path];
    if (!fileExist) {
        [fileManage createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

// 获取文件的创建时间
+(NSString *)getCreatDate:(NSString* )path{
    
    NSError *error = nil;
    NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
    
    if (fileDictionary) {
        NSDate * creationDate = [fileDictionary objectForKey:NSFileCreationDate];
        
        NSDateFormatter *dfm = [[NSDateFormatter alloc]init];
        [dfm setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString * resultStr = [dfm stringFromDate:creationDate];
        return resultStr;
    }else{
        return  @"----";
    }
}

// 获取文件的大小
+(NSString *)getDataCount:(NSString* )path{
    
    NSError *error = nil;
    NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
    
    if (fileDictionary) {
        double dataCount = [[fileDictionary objectForKey:NSFileSize] doubleValue];
        return [NSString stringWithFormat:@"%f",dataCount];
    }else{
        return  @"0";
    }
}

// 获取图标
+(NSString *)fileExtension:(NSString *)fileName {
    NSString * curExtension = [fileName pathExtension];
    NSString * extensionImgName = @"icon_other";
    if ([curExtension  isEqual: @"txt"]) {
        extensionImgName = @"file_icon_txt";
    }else if ([curExtension  isEqual: @"doc"] || [curExtension  isEqual: @"docx"]) {
        extensionImgName = @"file_icon_doc";
    }else if ([curExtension  isEqual: @"pdf"]) {
        extensionImgName = @"file_icon_pdf";
    }else if ([curExtension  isEqual: @"zip"]) {
        extensionImgName = @"file_icon_zip";
    }else if ([curExtension  isEqual: @"xls"] || [curExtension  isEqual: @"xlsx"]) {
        extensionImgName = @"file_icon_xls";
    }else if ([curExtension  isEqual: @"wav"] || [curExtension  isEqual: @"mp3"]) {
        extensionImgName = @"file_icon_au";
    }else if ([curExtension  isEqual: @"mp4"] || [curExtension  isEqual: @"avi"]) {
        extensionImgName = @"file_icon_avi";
    }else if ([curExtension  isEqual: @"bmp"] || [curExtension  isEqual: @"jpg"] || [curExtension  isEqual: @"png"]) {
        extensionImgName = @"file_icon_img";
    }else if ([curExtension  isEqual: @"ppt"]){
        extensionImgName = @"file_icon_ppt";
    }else if ([curExtension isEqual: @"html"]){
        extensionImgName = @"file_icon_html";
    }
    return extensionImgName;
}

// 保存网络文件到本地沙盒
-(void)saveFileToApp:(NSURL *)url withFileName:(NSString *)fileName andResultBack:
(void(^)(float,bool))downloadCall {
    self.curFileName = fileName;
    self.documentCall = downloadCall;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
    [downloadTask resume];
}

// 保存路径文件到本地沙盒
-(BOOL)saveFileToApp:(NSURL *)filePath {
    NSData *fileData = [NSData dataWithContentsOfURL:filePath];
    
    NSString * curFilePath = [filePath absoluteString];
    NSString * utf8Path = curFilePath.stringByRemovingPercentEncoding;
    NSString * curName =[utf8Path lastPathComponent];
    
    NSString * trueName = [curName stringByDeletingPathExtension];
    NSString * trueExten = [curName pathExtension];
    NSString * theName = [trueName stringByAppendingPathExtension:trueExten];
    NSString * savePath = [self.localPath stringByAppendingPathComponent:theName];
    
    NSFileManager *fileManage = [NSFileManager defaultManager];
    int suffix = 0;
    while ([fileManage fileExistsAtPath:savePath]) {
        suffix += 1;
        NSString * nowName = [trueName stringByAppendingString:[NSString stringWithFormat:@"%d",suffix]];
        theName = [nowName stringByAppendingPathExtension:trueExten];
        savePath = [self.localPath stringByAppendingPathComponent:theName];
    }
    
    if ([fileData writeToFile:savePath atomically:YES]) {
        NSLog(@"保存成功");
        return YES;
    }else{
        NSLog(@"保存失败");
        return NO;
    }
}

// 删除指定路径的文件
-(BOOL)removeFileFromPath:(NSString *)filePath {
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:filePath];
    if (bRet) {
        NSError *err;
        return [fileMgr removeItemAtPath:filePath error:&err];
    }else{
        return YES;
    }
}

// 本地文件检索
-(NSMutableArray *)filterFileActionWithNameStr:(NSString *)filterStr {
    NSMutableArray* resuleArr = [NSMutableArray arrayWithCapacity:6];
    if (filterStr == nil || filterStr.length == 0) {
        return resuleArr;
    }
    
    for (NSMutableDictionary* theDoc in self.fileArr) {
        NSString *fileName = theDoc[@"name"];
        if ([fileName containsString:filterStr]) {
            [resuleArr addObject:theDoc];
        }
    }
    return resuleArr;
}

#pragma mark - 网络文件下载进度回调  NSURLSessionDownloadDelegate

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    
    if (self.curFileName.length == 0) {
        self.curFileName = downloadTask.response.suggestedFilename;
    }
    
    NSString * savePath = [self.localPath stringByAppendingPathComponent:self.curFileName];
    NSString * trueName = [self.curFileName stringByDeletingPathExtension];
    NSString * trueExten = [self.curFileName pathExtension];
    
    NSFileManager *fileManage = [NSFileManager defaultManager];
    int suffix = 0;
    while ([fileManage fileExistsAtPath:savePath]) {
        suffix += 1;
        NSString * nowName = [trueName stringByAppendingString:[NSString stringWithFormat:@"%d",suffix]];
        NSString * theName = [nowName stringByAppendingPathExtension:trueExten];
        savePath = [self.localPath stringByAppendingPathComponent:theName];
    }
    
    NSData *fileData = [NSData dataWithContentsOfURL:location];
    
    
    if ([fileData writeToFile:savePath atomically:YES]) {
        [fileManage removeItemAtURL:location error:NULL];
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.documentCall != nil) {
                // 1.1  > 1 表示保存完成
                weakSelf.documentCall(1.1,NO);
            }
        });
    }else{
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.documentCall != nil) {
                weakSelf.documentCall(0,YES);
            }
        });
    }
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error != nil) {
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.documentCall != nil) {
                weakSelf.documentCall(0,YES);
            }
        });
    }
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    float progress = totalBytesWritten/(float)totalBytesExpectedToWrite;
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (weakSelf.documentCall != nil) {
            weakSelf.documentCall(progress,NO);
        }
    });
}

@end

