//
//  ViewController.m
//  XYSW
//
//  Created by Jim on 2021/9/7.
//

#import "ViewController.h"

#import "YHScanQRCodeVC.h"
#import "TZImagePickerManager.h"
#import "WeDocument.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "LCDownloadManager.h"
#import <QuickLook/QuickLook.h>

@interface ViewController ()<UIDocumentPickerDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>

@property (nonatomic , strong) UIImageView *pickerImageV;

@property (nonatomic, strong) AFHTTPRequestOperation *operation;

@property (nonatomic, strong) NSString *fileSvPath;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setTitle:@"扫一扫" forState:UIControlStateNormal];
    [scanBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(150, KNavHeight+40, 80, 25);
    [scanBtn addTarget:self action:@selector(goToScanVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    
    _pickerImageV = [[UIImageView alloc] init];
    [self.view addSubview:_pickerImageV];
    [_pickerImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-34);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(150);
        make.width.mas_equalTo(KScreenWidth);
    }];
    
    UIButton *scanBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn1 setTitle:@"拍照" forState:UIControlStateNormal];
    [scanBtn1 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn1.frame = CGRectMake(20, KNavHeight+40, 80, 25);
    [scanBtn1 addTarget:self action:@selector(goToCameraComplain) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn1];
    
    UIButton *scanBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn2 setTitle:@"相册" forState:UIControlStateNormal];
    [scanBtn2 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn2.frame = CGRectMake(260, KNavHeight+40, 80, 25);
    [scanBtn2 addTarget:self action:@selector(goToPickerImageComplain) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn2];
    
    UIButton *scanBtn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn3 setTitle:@"文件上传" forState:UIControlStateNormal];
    [scanBtn3 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn3.frame = CGRectMake(150, KNavHeight+100, 80, 25);
    [scanBtn3 addTarget:self action:@selector(goToopenFileData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn3];
    
    UIButton *scanBtn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn4 setTitle:@"退出登录" forState:UIControlStateNormal];
    [scanBtn4 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn4.frame = CGRectMake(150, KNavHeight+140, 80, 25);
    [scanBtn4 addTarget:self action:@selector(goToLoginViewControll) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn4];
    
    UIButton *scanBtn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn5 setTitle:@"文件下载" forState:UIControlStateNormal];
    [scanBtn5 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn5.frame = CGRectMake(150, KNavHeight+180, 80, 25);
    [scanBtn5 addTarget:self action:@selector(goToDownFile) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn5];
}

-(void)goToDownFile{
    
    //NSString *fileUrl=[body.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 下载路径
    NSString *fileUrl = @"";
    // 缓存路径
    long timeStamp = (long)([[NSDate date] timeIntervalSince1970]*1000);
    NSString* fileCachePath=[NSString stringWithFormat:@"%ld%@",timeStamp,@"fileName"];
    // 本地路径
    NSString *cacgeFileUrl = [NSString stringWithFormat:@"/%@/file/%@",@"kUid",fileCachePath];
    
    __weak typeof(self) weakSelf = self;
    
    [self.operation cancel];
    
    self.operation = [LCDownloadManager downloadFileWithURLString:fileUrl fileName:@"fileNamefileCachePath" cachePath: fileCachePath progress:^(CGFloat progress, CGFloat totalMBRead, CGFloat totalMBExpectedToRead) {
        // 正在下载
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        // 下载成功
        
        // 打开文件 预览
        NSString* fileUrl=[NSString stringWithFormat:@"%@%@",[[self class] XH_getDocumentDir],cacgeFileUrl];
        if (fileUrl) {
            weakSelf.fileSvPath = fileUrl;
            QLPreviewController *preViewCon = [QLPreviewController new];
             preViewCon.dataSource = weakSelf;
            [preViewCon setDelegate:weakSelf];
            [weakSelf presentViewController:preViewCon animated:YES completion:nil];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        //下载失败
        
    }];
    
    
    
}

-(void)goToScanVC{
    
    [Untis judgeIsHaveCamerCompleteBlock:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                YHScanQRCodeVC *vc = [[YHScanQRCodeVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得照相机的使用权限，请在设置中开启「照相机」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
    
    
}

-(void)goToCameraComplain{
    [Untis judgeIsHaveCamerCompleteBlock:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[TZImagePickerManager shareManager] pushCameraViewController:self complete:^(UIImage * _Nonnull cameraImage) {
                    if (cameraImage) {
                        [self setPickerViewImage:cameraImage];
                    }
                }];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得照相机的使用权限，请在设置中开启「照相机」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
}


-(void)goToPickerImageComplain{
    [Untis judgeIsHaveAlbumCompleteBlock:^(BOOL granted) {
        if (granted) {
            [[TZImagePickerManager shareManager] pushPickerViewController:PickerViewControllerTypeOfImageDefault fromViewController:self selectImageNumber:1 complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets, BOOL isSelectOriginalPhoto) {
                if (photos.count) {
                    UIImage *image = [photos firstObject];
                    [self setPickerViewImage:image];
                }
            }];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得相册的使用权限，请在设置中开启「相册」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
}

-(void)goToLoginViewControll{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"login"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [AppDelegate startLoginViewController];
}

-(void)goToopenFileData{
    NSArray *documentTypes = @[@"public.content",
                               @"public.text",
                               @"public.source-code",
                               @"public.image",
                               @"public.jpeg",
                               @"public.png",
                               @"com.adobe.pdf",
                               @"com.apple.keynote.key",
                               @"com.microsoft.word.doc",
                               @"com.microsoft.excel.xls",
                               @"com.microsoft.powerpoint.ppt"];
    UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
    for (int i=0; i<urls.count; i++) {
         [self openFileData:urls[i]];
    }
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    DLog(@"%@",url);
}

-(void)openFileData:(NSURL*)url{
    WeDocument *document = [[WeDocument alloc] initWithFileURL:url];
    __weak typeof(self) weakSelf = self;
    
    [document openWithCompletionHandler:^(BOOL success) {
        
        if (success) {
            DLog(@"文件名%@",document.docFileName);
            DLog(@"文件类型%@",document.docMIMEType);
            DLog(@"文件长度%lu",(unsigned long)document.docLength);
            DLog(@"文件资源%@",document.documentData);
            dispatch_queue_t queue = dispatch_queue_create("my_concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
               // 文件上传
            });

        }  else
        {
            DLog(@"读取失败");
        }
        [document closeWithCompletionHandler:^(BOOL success) {
            
        }];
    }];
    
}

#pragma mark --- QLPreviewControllerDelegate
- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
    return 1;
}
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return [NSURL fileURLWithPath:self.fileSvPath];
}
- (void)previewControllerDidDismiss:(QLPreviewController *)controller
{
 
}

-(void)setPickerViewImage:(UIImage *)image{
    self.pickerImageV.image = image;
}

//数据路径
+ (NSString *)XH_getDocumentDir{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

@end
