//
//  InputGongwenFileCell.m
//  smartRhino
//
//  Created by Android on 2020/1/14.
//  Copyright © 2020 tederen. All rights reserved.
//

#import "InputGongwenFileCell.h"
#import "MyWordCell.h"
#import "DownFileViewController.h"

@interface InputGongwenFileCell() <UICollectionViewDelegate,UICollectionViewDataSource>
@property (copy, nonatomic)NSURL *fileURL;
@end

@implementation InputGongwenFileCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.gongwenContent.placeholder = @"请输入";
    self.gongwenContent.placeholderColor = RGB(153, 153, 153);
    self.gongwenContent.font = [UIFont systemFontOfSize:16];
    self.mycollectionView.delegate = self;
    self.mycollectionView.dataSource = self;
    [self.mycollectionView registerNib:[UINib nibWithNibName:@"MyWordCell" bundle:nil] forCellWithReuseIdentifier:@"MyWordCell"];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)setApprovalSection:(NSMutableArray<SelectImageModel *> *)approvalSection {
    _approvalSection = approvalSection;
    [self.mycollectionView reloadData];
}

#pragma mark - UICollectionViewDelegate UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.approvalSection.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
    MyWordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyWordCell" forIndexPath:indexPath];
    [cell looadDataHiden:(self.approvalSection.count == indexPath.item)];
    if (self.approvalSection.count == indexPath.item) {
        cell.iconImage.image = self.placeholderImg.length > 0 ? IMG(self.placeholderImg) : IMG(@"添加审批人");
    }else{
        SelectImageModel * model = self.approvalSection[indexPath.item];
        if([self.approvalSection[indexPath.item].FileType isEqualToString:@"image"]){
            cell.iconImage.image = self.approvalSection[indexPath.item].image;
        }else{
            cell.iconImage.image = IMG([ZYCTool getFileNameImage:model.FileName]);
        }
        WS(weakSelf);
        [cell.deleteButton setAction:^{
            [weakSelf deleteHanderBack:indexPath];
        }];
    }
    cell.indexPath = indexPath;
    [cell.deleteButton setAction:^{
        [weakSelf deleteHanderBack:indexPath];
    }];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(self.approvalSection.count == indexPath.item){
        if ([self.delegate respondsToSelector:@selector(addPictureWith:WithSuccess:failure:)]) {
            [self.delegate addPictureWith:self.index WithSuccess:^(id  _Nullable responseObject) {
                
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
    }else{
        [self checkUpHanderBack:indexPath];
    }
}

#pragma mark - MyWordCellDelegate
- (void)deleteHanderBack:(NSIndexPath *)indexPath{
    NSLog(@"MyWordCell 3");
    [self.approvalSection removeObjectAtIndex:indexPath.item];
    [self.mycollectionView reloadData];
    if ([self.delegate respondsToSelector:@selector(deletePictureWithCell:SuperViewCellIndexPath:WithSuccess:failure:)]) {
        [self.delegate deletePictureWithCell:indexPath SuperViewCellIndexPath:self.index WithSuccess:^(id  _Nullable responseObject) {
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
}

- (void)checkUpHanderBack:(NSIndexPath *)indexPath{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSString *urlStr = self.approvalSection[indexPath.item].AbsolutePath;
    NSString *fileName = [urlStr lastPathComponent]; //获取文件名称
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSLog(@"上传文件地址%@",URL.absoluteString);
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    WS(weakSelf);
    //判断是否存在
    //        if([self isFileExist:fileName]) {
    //            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    //            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
    //            WorkFlowFileModel *mdoel = [[WorkFlowFileModel alloc]init];
    //            mdoel.PreviewUrl = url.absoluteString;
    //            mdoel.DownloadUrl = url.absoluteString;
    //            DownFileViewController *vc = [[DownFileViewController alloc]init];
    //            vc.model = mdoel;
    //            vc.modalPresentationStyle = UIModalPresentationFullScreen;
    //            [[UIApplication sharedApplication].windows.firstObject.rootViewController presentViewController:vc animated:YES completion:nil];
    //        }else {
    SHOWLOADING
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
        
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        return url;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        REMOVESHOW
        NSLog(@"%@",response);
        if (weakSelf.ClickCellBlock) {
            weakSelf.ClickCellBlock(indexPath.item);
        }
    }];
    [downloadTask resume];
    //        }
}

//判断文件是否已经在沙盒中存在
-(BOOL) isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}


@end