//
//  NvEditMaterialViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/6/11.
 //
//

#import "NvEditMaterialViewController.h"
#import "NvEditMaterialCollectionViewCell.h"
#import "NvEditMaterialLayout.h"
#import "NvsVideoTrack.h"
#import "NvsVideoClip.h"
#import "NvEditBottomCollectionViewCell.h"
#import "NvEditTailoringViewController.h"
#import "NvAlbumViewController.h"
#import "NvBaseNavigationController.h"
#import "NvTimelineUtils.h"
#import "NvTimelineImageUtils.h"
#import "NvTipsView.h"
#import "MSSysAlertUtil.h"
#import "NvEditPictureViewController.h"

@interface NvEditMaterialViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, NvEditMaterialLayoutDelegate>

@property (nonatomic, strong) NvsStreamingContext *context;
@property (nonatomic, strong) NvsVideoTrack *track;

@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray *dataArray;        //滑动视图数组

@property (nonatomic, strong) UICollectionView *bottomView;
@property (nonatomic, strong) NSArray *dataArray1;              //视频编辑对应的功能数组
@property (nonatomic, strong) NSArray *dataArray2;              //图片编辑对应的功能数组

@property (nonatomic, strong) NSArray *currentArray;     //当前需要展示的数组

@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;

@property (nonatomic, assign) NSInteger currentInt;

@property (nonatomic, assign) NSInteger index;//添加asset时dataSource的下标位置

@property (nonatomic, strong) NvTimelineData *timelineData;

@property (nonatomic, strong) NvsTimeline *currentTimeline;

@property (nonatomic, assign) BOOL longState;   //长按标识

@property (nonatomic, assign) BOOL addMaterial;

@property (nonatomic, strong) UIView *line;

@end

@implementation NvEditMaterialViewController

- (void)dealloc{
    NSLog(@"%s",__func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    self.title = @"编辑";
    self.context = [NvsStreamingContext sharedInstance];
    self.dataArray1 = @[@{@"裁剪":@"NvTrim"},
                        @{@"分割":@"NvSplit"},
                        @{@"校色":@"NvColorCorrect"},
                        @{@"调整":@"NvFlip"},
                        @{@"速度":@"NvSpeed"},
                        @{@"音量":@"NvEditVolumn"},
                        @{@"复制":@"NvCopy"},
                        @{@"删除":@"NvEditDelete"}];
    
    self.dataArray2 = @[@{@"时长":@"NvSpeed"},@{@"运动":@"NvFlip"},@{@"校色":@"NvColorCorrect"},@{@"复制":@"NvCopy"},@{@"删除":@"NvEditDelete"}];
    [self addSubViews];
    
    self.timeline = [NvTimelineUtils createTimeline:self.editMode];
    self.timelineData = [NvTimelineData sharedInstance];
    [self addLoadingImage];
}

- (void)addLoadingImage{
    if (self.dataArray.count != 0) {
        [self.dataArray removeAllObjects];
    }
    [NvTimelineUtils resetEditData:self.timeline editDataArray:[[NvTimelineData sharedInstance] editDataArray]];
    [NvTimelineUtils resetVideoFx:self.timeline videoFxDataArray:[[NvTimelineData sharedInstance] videoFxDataArray]];
    
    self.track = [self.timeline getVideoTrackByIndex:0];
    for (int i = 0; i < self.track.clipCount; i++) {
        [self.track setBuiltinTransition:i withName:@""];
        [self.track setPackagedTransition:i withPackageId:@""];
    }
    
    [self.dataArray addObjectsFromArray:self.timelineData.editDataArray];
    NvEditDataModel *firstModel = [self.dataArray firstObject];
    if (firstModel.isImage) {
        self.currentArray = self.dataArray2;
        _bottomView.frame = CGRectMake(15 * SCREANSCALE, 430 *SCREANSCALE, SCREEN_WDITH - 15 * SCREANSCALE, 80*SCREANSCALE);
    }else{
        self.currentArray = self.dataArray1;
        _bottomView.frame = CGRectMake(0, 430 *SCREANSCALE, SCREEN_WDITH, 80*SCREANSCALE);
    }
    
    [self.collection reloadData];
    [self resetFilter];
}

- (UIView *)leftNavigationBarItemView {
    return [UIView new];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_addMaterial) {
        _addMaterial = NO;
        [self addLoadingImage];
        NvEditDataModel *dataModel = self.dataArray[self.currentInt];
        if (dataModel.isImage) {
            self.currentArray = self.dataArray2;
            _bottomView.frame = CGRectMake(15 * SCREANSCALE, 430 *SCREANSCALE, SCREEN_WDITH - 15 * SCREANSCALE, 80*SCREANSCALE);
        }else{
            self.currentArray = self.dataArray1;
            _bottomView.frame = CGRectMake(0, 430 *SCREANSCALE, SCREEN_WDITH, 80*SCREANSCALE);
        }
        [self. bottomView reloadData];
    }else{
        [NvTimelineUtils resetEditData:self.timeline editDataArray:[[NvTimelineData sharedInstance] editDataArray]];
    }
}

- (void)resetFilter {
    NSMutableArray *filters = [[NvTimelineData sharedInstance] videoFxDataArray];
    for (NvTimeFilterInfoModel *filter in filters) {
        filter.inPoint = 0;
        filter.outPoint = _timeline.duration;
    }
}

- (void)addSubViews{
    NvEditMaterialLayout *layout = [[NvEditMaterialLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(180*SCREANSCALE, 320*SCREANSCALE);
    layout.minimumLineSpacing = 24*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.delegate = self;
    _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0 * SCREANSCALE, 0 *SCREANSCALE, SCREEN_WDITH, 320*SCREANSCALE) collectionViewLayout:layout];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_collection];
    [_collection registerClass:[NvEditMaterialCollectionViewCell class] forCellWithReuseIdentifier:@"NvEditMaterialCollectionViewCell"];
    _collection.backgroundColor = [UIColor nv_colorWithHexRGB:@"#242728"];
    self.longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handlelongGesture:)];
    
    [_collection addGestureRecognizer:self.longPress];
    
    UICollectionViewFlowLayout *layout1 = [[UICollectionViewFlowLayout alloc]init];
    layout1.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout1.itemSize = CGSizeMake(65*SCREANSCALE, 80*SCREANSCALE);
    layout1.minimumLineSpacing = 5*SCREANSCALE;
    layout1.minimumInteritemSpacing = 0;
    _bottomView = [[UICollectionView alloc] initWithFrame:CGRectMake(0 * SCREANSCALE, 430 *SCREANSCALE, SCREEN_WDITH, 80*SCREANSCALE) collectionViewLayout:layout1];
    _bottomView.delegate = self;
    _bottomView.dataSource = self;
    _bottomView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_bottomView];
    [_bottomView registerClass:[NvEditBottomCollectionViewCell class] forCellWithReuseIdentifier:@"NvEditBottomCollectionViewCell"];
    _bottomView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#242728"];
    
    UIButton *finsh = [UIButton buttonWithType:UIButtonTypeCustom];
    [finsh setImage:[NvUtils imageWithName:@"Nvcheck - material"] forState:UIControlStateNormal];
    [finsh addTarget:self action:@selector(finshClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:finsh];
    [finsh mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        if (KIsiPhoneX) {
            make.bottom.equalTo(self.view.mas_bottom).offset(- 39 * SCREANSCALE);
        }else{
            make.bottom.equalTo(self.view.mas_bottom).offset(- 15 * SCREANSCALE);
        }
        
        make.width.offset(25 * SCREANSCALE);
        make.height.offset(20 * SCREANSCALE);
    }];
    
    self.line = [UIView new];
    self.line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@1);
        make.bottom.equalTo(finsh.mas_top).offset(-12*SCREANSCALE);
    }];
    
}

- (void)segmentation:(NSNotification *)notification{
    NSDictionary *dic= [notification userInfo];
    NSInteger integer = [dic[@"index"] integerValue];
    _collection.contentOffset = CGPointMake(integer * SCREANWIDTH/2, 0);
}

- (void)toustTipView:(NSString *)title{
    NvTipsView *tipView = [[NvTipsView alloc]initWithFrame:CGRectMake(0, 0, SCREANWIDTH, SCREANHEIGHT) withPrompt:@"提示" describeTitle:[NSString stringWithFormat:@"Demo%@界面正在开发中，敬请期待。SDK内部已支持。",title] describeContent:nil buttonText:@"知道了" withCenter:YES];
    [tipView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tipView];
}

#pragma mark tipView按钮点击事件
- (void)knowClick:(UIButton *)sender{
    [sender.superview.superview removeFromSuperview];
}

#pragma mark - 结束编辑点击事件
- (void)finshClick:(UIButton *)btn{
    [_context removeTimeline:_timeline];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == _bottomView) {
        return self.currentArray.count;
    }
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _bottomView) {
        NvEditBottomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvEditBottomCollectionViewCell" forIndexPath:indexPath];
        cell.dict = self.currentArray[indexPath.item];
        return cell;
    }
    NvEditMaterialCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvEditMaterialCollectionViewCell" forIndexPath:indexPath];
//    cell.coverImage = self.dataArray[indexPath.item];
    cell.model = self.dataArray[indexPath.item];
    cell.index = indexPath.row;
    cell.currentIndex = self.currentInt;
    cell.delegate = self;
    cell.leftView.transform = CGAffineTransformMakeScale(1, 1);
    cell.rightView.transform = cell.leftView.transform;
    cell.leftBtn.transform = CGAffineTransformMakeScale(1, 1);
    cell.rightBtn.transform = cell.leftBtn.transform;
    
    [cell setAddButtonHidden:cell.index != cell.currentIndex];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _bottomView) {
        NvEditDataModel *model = self.timelineData.editDataArray[self.currentInt];
        NSDictionary *dict = self.currentArray[indexPath.item];
        NSString *titleString = dict.allKeys[0];
        if ([titleString isEqualToString:@"复制"]) {
            NvEditDataModel *clipModel = [model copy];
            clipModel.isLoading = YES;
            clipModel.thumImage = model.thumImage;
            [self.dataArray insertObject:clipModel atIndex:self.currentInt+1];
            [self.timelineData.editDataArray insertObject:clipModel atIndex:self.currentInt];
            NvTransitionInfoModel *transitionInfo = NvTransitionInfoModel.new;
            [[[NvTimelineData sharedInstance] transitionDataArray] insertObject:transitionInfo atIndex:self.currentInt+1];
            [NvTimelineUtils resetEditData:self.timeline editDataArray:self.timelineData.editDataArray];
            self.currentInt++;
            [self.collection setContentOffset:CGPointMake(self.currentInt * 204 * SCREANSCALE, 0) animated:YES];
            [self.collection reloadData];
            return;
        }else if ( [titleString isEqualToString:@"删除"]){
            if (self.dataArray.count == 1){
                NvTipsView *tipsView = [[NvTipsView alloc]initWithFrame:CGRectMake(0, 0, SCREANWIDTH, SCREANHEIGHT) withPrompt:@"提示" describeTitle:@"至少保留下一个素材" describeContent:nil buttonText:@"知道了" withCenter:NO];
                [tipsView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:tipsView];
                return;
            }
            [self.dataArray removeObjectAtIndex:self.currentInt];
            [self.timelineData.editDataArray removeObjectAtIndex:self.currentInt];
            [[[NvTimelineData sharedInstance] transitionDataArray] removeObjectAtIndex:self.currentInt];
            [NvTimelineUtils resetEditData:self.timeline editDataArray:self.timelineData.editDataArray];
            if (self.currentInt >= self.dataArray.count){
                self.currentInt = self.dataArray.count -1;
            }
            NvEditDataModel *model2 = self.timelineData.editDataArray[self.currentInt];
            self.currentArray = model2.isImage?self.dataArray2:self.dataArray1;
            [self.collection reloadData];
            [self.bottomView reloadData];
            if (self.currentInt == 0) {
                _collection.contentOffset =  CGPointMake(0, _collection.contentOffset.y);
            }else{
                _collection.contentOffset = CGPointMake(self.currentInt * 204 * SCREANSCALE, 0);
            }
            return;
        }
        if (model.isImage) {
            if ([titleString isEqualToString:@"校色"]) {
                NvEditTailoringViewController *vc = [[NvEditTailoringViewController alloc]init];
                vc.model = model;
                vc.currentIndex = self.currentInt;
                vc.editMode = _editMode;
                vc.title = titleString;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                NvEditPictureViewController *vc = [[NvEditPictureViewController alloc]init];
                vc.editMode = _editMode;
                vc.model = model;
                vc.title = titleString;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else{
            __weak typeof(self) weakSelf = self;
            NvEditTailoringViewController *vc = [[NvEditTailoringViewController alloc]init];
            vc.model = model;
            vc.currentIndex = self.currentInt;
            vc.editMode = _editMode;
            vc.title = titleString;
            vc.editBlock = ^(NvEditDataModel *newModel) {
                //分割才会走这个回调
                NvTransitionInfoModel *transitionInfo = NvTransitionInfoModel.new;
                [[[NvTimelineData sharedInstance] transitionDataArray] insertObject:transitionInfo atIndex:self.currentInt+1];
                [self.dataArray insertObject:newModel atIndex:self.currentInt +1];
                [weakSelf.collection reloadData];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    //判断手势状态
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
            _longState = YES;
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collection indexPathForItemAtPoint:[longGesture locationInView:self.collection]];
            if (indexPath == nil) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            if (@available(iOS 9.0, *)) {
                [self.collection beginInteractiveMovementForItemAtIndexPath:indexPath];
                NvEditMaterialCollectionViewCell *cell = (NvEditMaterialCollectionViewCell *)[self.collection cellForItemAtIndexPath:indexPath];
                [cell setAddButtonHidden:YES];
            } else {
                // Fallback on earlier versions
            }
        }
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程当中随时更新cell位置
            if (@available(iOS 9.0, *)) {
                [self.collection updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collection]];
            } else {
                // Fallback on earlier versions
            }
            break;
        case UIGestureRecognizerStateEnded:
            //移动结束后关闭cell移动
            if (@available(iOS 9.0, *)) {
                [self.collection endInteractiveMovement];
                NSIndexPath *indexPath = [self.collection indexPathForItemAtPoint:[longGesture locationInView:self.collection]];
                NvEditMaterialCollectionViewCell *cell = (NvEditMaterialCollectionViewCell *)[self.collection cellForItemAtIndexPath:indexPath];
                [cell setAddButtonHidden:NO];
                _longState = NO;
            } else {
                // Fallback on earlier versions
            }
            break;
        default:
            if (@available(iOS 9.0, *)) {
                [self.collection cancelInteractiveMovement];
                _longState = NO;
            } else {
                // Fallback on earlier versions
            }
            break;
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    //返回YES允许其item移动
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    //取出源item数据
    id objc = [_dataArray objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
    [_dataArray removeObject:objc];
    //将数据插入到资源数组中的目标位置上
    [_dataArray insertObject:objc atIndex:destinationIndexPath.item];
    
    NvEditDataModel *model = self.timelineData.editDataArray[sourceIndexPath.item];
    [self.timelineData.editDataArray removeObject:model];
    [self.timelineData.editDataArray insertObject:model atIndex:destinationIndexPath.item];
    self.currentInt = destinationIndexPath.item;
    NvEditMaterialCollectionViewCell *cell = (NvEditMaterialCollectionViewCell *)[self.collection cellForItemAtIndexPath:sourceIndexPath];
    cell.index = sourceIndexPath.item;
    [self.collection reloadData];
    if (destinationIndexPath.item == 0) {
            self.collection.contentOffset = CGPointMake(0, 0);
    }else{
            self.collection.contentOffset = CGPointMake(destinationIndexPath.item * 204 * SCREANSCALE, 0);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewEndScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ( !decelerate ) {
        [self scrollViewEndScroll:scrollView];
    }
}

- (void)scrollViewEndScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:_collection]) {
        if ([self.currentArray isEqualToArray:self.dataArray2]) {
            _bottomView.frame = CGRectMake(15 * SCREANSCALE, 430 *SCREANSCALE, SCREEN_WDITH - 15 * SCREANSCALE, 80*SCREANSCALE);
        }else{
            _bottomView.frame = CGRectMake(0, 430 *SCREANSCALE, SCREEN_WDITH, 80*SCREANSCALE);
        }
        
        [_bottomView reloadData];
    }
}

#pragma mark - NvEditMaterialLayoutDelegate
- (void)nvEditMaterialLayout:(NvEditMaterialLayout *)nvEditMaterialLayout uiCollectionViewLayoutAttributes:(UICollectionViewLayoutAttributes *)layout{
    if (self.longState) {
        return;
    }
    NvEditMaterialCollectionViewCell *cell = (NvEditMaterialCollectionViewCell *)[_collection cellForItemAtIndexPath: layout.indexPath];
    if (layout.indexPath.item == 0 && self.dataArray.count == 1) {
        cell.leftView.transform = CGAffineTransformMakeScale(1, 1);
        cell.rightView.transform = cell.leftView.transform;
        cell.leftBtn.transform = CGAffineTransformMakeScale(1, 1);
        cell.rightBtn.transform = cell.leftBtn.transform;
        [cell setAddButtonHidden:NO];
        cell.currentIndex = 0;
        self.currentInt = 0;
        return;
    }
    
    if (cell.currentIndex == self.currentInt) {
        cell.leftView.transform = CGAffineTransformMakeScale(layout.alpha, 1);
        cell.rightView.transform = cell.leftView.transform;
        cell.leftBtn.transform = CGAffineTransformMakeScale(layout.alpha, layout.alpha);
        cell.rightBtn.transform = cell.leftBtn.transform;
    }

    if (abs((int)(_collection.contentOffset.x + _collection.frame.size.width/2) - (int)layout.center.x) < 3) {
        self.currentInt = layout.indexPath.item;
        NvEditDataModel *model = self.timelineData.editDataArray[self.currentInt];
        [self isImageHidden:model.isImage];

        for (int i = 0; i < _dataArray.count; i++) {
            NvEditMaterialCollectionViewCell *cell = (NvEditMaterialCollectionViewCell *)[_collection cellForItemAtIndexPath: [NSIndexPath indexPathForRow:i inSection:0]];
            cell.currentIndex = self.currentInt;
            [cell setAddButtonHidden:cell.currentIndex != cell.index];
        }
    }
    

}

#pragma mark - NvEditMaterialCollectionViewCellDelegate
- (void)addClipForIndex:(NSInteger)index {
    self.index = index;
    NvAlbumViewController *album = [NvAlbumViewController new];
    album.delegate = self;
    NvBaseNavigationController *nav = [[NvBaseNavigationController alloc] initWithRootViewController:album];
    [self presentViewController:nav animated:YES completion:NULL];
    
}

#pragma mark - NvAlbumViewControllerDelegate
- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    [albumViewController dismissViewControllerAnimated:YES completion:NULL];
    _addMaterial = YES;
    __block NSInteger index = self.index;
    __block BOOL isshowToast = false;
    for (int i = 0;i < assets.count; i++) {
        NvAlbumAsset *asset = assets[i];
        __weak typeof(self)weakSelf = self;
        if (asset.asset.mediaType == PHAssetMediaTypeVideo) {
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.version = PHVideoRequestOptionsVersionOriginal;
            options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [[PHImageManager defaultManager] requestAVAssetForVideo:asset.asset
                                                            options:options
                                                      resultHandler:^(AVAsset * avAsset, AVAudioMix * audioMix, NSDictionary * info) {
                                                          if (avAsset && [avAsset isKindOfClass:[AVURLAsset class]]) {
                                                              NvEditDataModel *model = [NvEditDataModel new];
                                                              model.isImage = NO;
//                                                              model.videoPath = ((AVURLAsset*)avAsset).URL.absoluteString;
                                                              model.videoPath = asset.asset.localIdentifier;
                                                              model.trimIn = 0;
                                                              model.trimOut = asset.asset.duration*NV_TIME_BASE;
                                                              model.duration = asset.asset.duration*NV_TIME_BASE;
                                                              [weakSelf.timelineData.editDataArray insertObject:model atIndex:(NSUInteger)index];
                                                              
                                                              NvTransitionInfoModel *info = NvTransitionInfoModel.new;
                                                              [[[NvTimelineData sharedInstance] transitionDataArray] addObject:info];
                                                              
                                                              index++;
                                                          } else {
                                                              isshowToast = YES;
                                                          }
                                                          
                                                          dispatch_semaphore_signal(semaphore);
                                                      }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        } else if (asset.asset.mediaType == PHAssetMediaTypeImage) {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
            requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
            requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
            requestOptions.synchronous = YES;
            [[PHImageManager defaultManager] requestImageForAsset:asset.asset
                                                       targetSize:CGSizeMake(80, 80)
                                                      contentMode:PHImageContentModeAspectFit
                                                          options:requestOptions
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        BOOL isIcloud =  [[info valueForKeyPath:@"PHImageResultIsInCloudKey"] boolValue];
                                                        if (isIcloud) {
                                                            isshowToast = YES;
                                                        } else {
                                                            NvEditDataModel *model = [NvEditDataModel new];
                                                            model.isImage = YES;
                                                            model.isPhotoAlbum = YES;
                                                            model.localIdentifier = asset.asset.localIdentifier;
                                                            model.trimIn = 0;
                                                            model.trimOut = 4*NV_TIME_BASE;
                                                            [weakSelf.timelineData.editDataArray insertObject:model atIndex:(NSUInteger)index];
                                                            
                                                            NvTransitionInfoModel *info = NvTransitionInfoModel.new;
                                                            [[[NvTimelineData sharedInstance] transitionDataArray] addObject:info];
                                                            
                                                            index++;
                                                        }
                                                        dispatch_semaphore_signal(semaphore);
                                                    }
             ];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (isshowToast) {
            [MSSysAlertUtil presentAlertViewWithTitle:@"提示" message:@"所选资源在iCloud中" confirmTitle:@"确定" handler:NULL];
        }
    });
}

- (void)nvAlbumViewControllerCancelClick:(NvAlbumViewController *)albumViewController {
    [albumViewController dismissViewControllerAnimated:YES completion:NULL];
}

- (void)isImageHidden:(BOOL)hidden{
    if (hidden) {
        self.currentArray = self.dataArray2;
    }else{
        self.currentArray = self.dataArray1;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
