//
//  NvParCaptureViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/9/19.
 //
//

#import "NvParCaptureViewController.h"
#import "NvTipsView.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>
#import "NvFilterCell.h"
#import "NvFilterItem.h"
#import "NvLabelCell.h"
#import "NvLabelModel.h"
#import "NvAssetManager.h"
#import "NvsAssetPackageManager.h"
#import "NvsAssetPackageParticleDescParser.h"
#import "NvsCaptureVideoFx.h"
#import "stMobileDetected.h"
#import "NvsAssetPackageParticleDescParser.h"
#import "NvAlbumViewController.h"
#import "NvPreViewLiveWindow.h"
#import "NvCompileViewController.h"
#import "NvParEditViewController.h"
#import "NvSDKUtils.h"
#import "NvGraphicBtn.h"

@interface NvParCaptureViewController ()<NvsStreamingContextDelegate, UICollectionViewDelegate, UICollectionViewDataSource,NvAlbumViewControllerDelegate,NvPreViewLiveWindowDelegate,NvCompileViewControllerDelegate>

//界面按钮
@property (nonatomic, strong) UIButton *backBtn;         //关闭
@property (nonatomic, strong) NvGraphicBtn *deviceBtn;       //切换摄像头
@property (nonatomic, strong) NvGraphicBtn *flashBtn;        //闪光灯
@property (nonatomic, strong) NvGraphicBtn *particleBtn;     //粒子特效
@property (nonatomic, strong) NvGraphicBtn *graffitiBtn;     //涂鸦特效
@property (nonatomic, strong) UIButton *shootingBtn;     //拍摄
@property (nonatomic, strong) UIButton *shootingBtn_1;     //自己特有的拍摄按钮
@property (nonatomic, strong) UIButton *finishBtn;       //完成
@property (nonatomic, strong) UILabel  *timeLabel;       //录制时长
@property (nonatomic, strong) UIButton *deleteBtn;       //删除视频
@property (nonatomic, strong) UILabel  *videoCount;      //视频个数

//粒子视图
@property (nonatomic, strong) UIView *particlePanelView;//最外层
@property (nonatomic, strong) UIView *particleHeaderView;  // 速率，强度的面板视图
@property (nonatomic, strong) UISlider *filterStrengthSlider;//滤镜强度
@property (nonatomic, strong) UILabel *filterStrengthLabel;//强度
@property (nonatomic, strong) UISlider *filterSpeeadSlider;//滤镜速度
@property (nonatomic, strong) UILabel *filterSpeeadLabel;//速度
@property (nonatomic, strong) UICollectionView *segmentedView; //标签视图
@property (nonatomic, strong) NSMutableArray *labelArray;            //标签数组
@property (nonatomic, strong) UICollectionView *particleCollectionView;//粒子特效滑动视图
@property (nonatomic, strong) NSMutableArray *particleDataSource;//粒子特效数组，视图使用
@property (nonatomic, strong) NSMutableArray *filterFxArray;         //滤镜特效数组
@property (nonatomic, strong) NSMutableArray *faceFxArray;           //人脸特效数组
@property (nonatomic, strong) NSMutableArray *gesturesFxArray;       //手势特效数组
@property (nonatomic, strong) NSMutableArray *controlFxArray;        //控制特效数组
@property (nonatomic, strong) NSMutableArray *currentAngleArray;     //当前粒子的方向数组
@property (nonatomic, strong) NSMutableArray *AngleArray_0;          //当前粒子的0方向数组
@property (nonatomic, strong) NSMutableArray *AngleArray_90;         //当前粒子的90方向数组
@property (nonatomic, strong) NSMutableArray *AngleArray_180;        //当前粒子的180方向数组
@property (nonatomic, strong) NSMutableArray *AngleArray_270;        //当前粒子的270方向数组

@property (nonatomic, strong) NSString *angleString;                 //旋转角度

//权限视图
@property (nonatomic, strong) NvTipsView *permissions;
//相册权限视图
@property (nonatomic, strong) NvTipsView *photoView;
//手动对焦视图
@property (nonatomic, strong) UIImageView *focusView;
//提示
@property (nonatomic, strong) NvTipsView *tipAIView;
//预览视图
@property (nonatomic, strong) NvPreViewLiveWindow *preView;
//粒子特效提示视图
@property (nonatomic, strong) UIView *tipBoxView;
//计时器
@property (nonatomic, strong) NSTimer *timer;

//-----------------逻辑相关----------------//
@property (nonatomic, assign) int currentDeviceIndex;          //当前设备摄像头索引
@property (nonatomic, strong) NSMutableArray *videoPathArray;  //视频路径数组
@property (nonatomic, strong) NSMutableArray *durationArray;   //断点拍摄每段视频的时长数组
@property (nonatomic, assign) int64_t duration;                //总拍摄时长
@property (nonatomic, assign) int64_t lastDuration;            //断点拍摄每次停止录制的时长，duration和durationArray需要用到
@property (nonatomic, assign) BOOL clickState;     //底部弹窗视图出现和消失
@property (nonatomic, strong) NvFilterItem *currentItem; //当前操作的特效对象
@property (nonatomic, strong) NSString *compileFilePath;//生成路径

//-----------------sdk相关----------------//
@property (nonatomic, strong) NvsStreamingContext *streamingContext;
@property (nonatomic, strong) NvsLiveWindow *liveWindow;
@property (nonatomic, strong) NvsLiveWindow *liveWindowBack;
@property (nonatomic, strong) NvsLiveWindow *curLiveWindow;//当前窗口
@property (nonatomic, strong) NvAssetManager *assetManager;//素材管理
@property (nonatomic, strong) NvsCaptureVideoFx *videoFx;  //粒子特效
@property (nonatomic, strong) NvsParticleSystemContext *particleContext;//粒子上下文
@property (nonatomic, strong) stMobileDetected *stMobileDtected;//粒子相关
@property (nonatomic, strong) NvsAssetPackageParticleDescParser *currentParser;//当前粒子对象

@end

@implementation NvParCaptureViewController

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

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.streamingContext.getStreamingEngineState != NvsStreamingEngineState_CapturePreview) {
        [self startCapturePreview];
        self.streamingContext.delegate = self;
    }
    self.navigationController.navigationBar.hidden = YES;
    [self addObservers];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.labelArray = [NSMutableArray array];
    self.videoPathArray = [NSMutableArray array];
    self.durationArray = [NSMutableArray array];
    self.particleDataSource = [NSMutableArray array];
    self.filterFxArray = [NSMutableArray array];
    self.faceFxArray = [NSMutableArray array];
    self.gesturesFxArray = [NSMutableArray array];
    self.controlFxArray = [NSMutableArray array];
    self.currentAngleArray = [NSMutableArray array];
    self.AngleArray_0 = [NSMutableArray array];
    self.AngleArray_90 = [NSMutableArray array];
    self.AngleArray_180 = [NSMutableArray array];
    self.AngleArray_270 = [NSMutableArray array];
    
    [self addParticleArray];
    [self addtitleArray];
    // 检查摄像头权限
    __weak typeof(self)weakSelf = self;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                AVAuthorizationStatus audioAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
                if (audioAuthStatus == AVAuthorizationStatusNotDetermined) {
                    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                        if (granted) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf startupCapture];
                            });
                        } else {
                            // 提示麦克风权限未获得
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf startupCapture];
                                [weakSelf.view addSubview:weakSelf.permissions];
                            });
                        }
                    }];
                }
            } else {
                // 提示摄像头权限未获得
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.view addSubview:weakSelf.permissions];
                });
            }
        }];
    } else if (authStatus == AVAuthorizationStatusDenied) {
        // 提示摄像头权限未获得
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.view addSubview:weakSelf.permissions];
        });
    } else {
        // 检查麦克风权限
        authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (authStatus == AVAuthorizationStatusDenied) {
            // 提示麦克风权限未获得
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.view addSubview:weakSelf.permissions];
            });
        }
        [weakSelf startupCapture];
    }
}

#pragma mark 给粒子视图的数组添加数据
- (void)addParticleArray{
    self.assetManager = [NvAssetManager sharedInstance];
    NSArray *temporaryArray = [self.assetManager getUsableAssets:ASSET_PARTICLE aspectRatio:AspectRatio_All categoryId:0];
    NSString *packagePath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"ParticlePackage"];
    NSString *jsonPath = [packagePath stringByAppendingPathComponent:@"fx1.json"];
    NSString *jsontext = [NSString stringWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
    NSData *data =[jsontext dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSArray *array =[NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    for (int i = 0 ; i < array.count; i++) {
        NSDictionary *dict = array[i];
        for (NvAsset *asset in temporaryArray) {
            if ([dict[@"fxid"] isEqualToString:asset.uuid]) {
                NSString *effectDesc = [[NvSDKUtils getSDKContext].assetPackageManager GetVideoFxAssetPackageDescription:asset.uuid];
                if (effectDesc == nil || [effectDesc isEqualToString:@""]) {
                    NSLog(@"%@",asset.uuid);
                    NSLog(@"获取特效包出错！");
                    break;
                }
                NvsAssetPackageParticleDescParser* parser = [[NvsAssetPackageParticleDescParser alloc] initWithEffectDesc:effectDesc];
                if(parser.getParticleType == NvsParticleType_Normal){
                    asset.categoryId = 1;
                }else if(parser.getParticleType == NvsParticleType_Eye || parser.getParticleType == NvsParticleType_Mouth){
                    asset.categoryId = 2;
                }else if(parser.getParticleType == NvsParticleType_Gesture){
                    asset.categoryId = 3;
                }else if(parser.getParticleType == NvsParticleType_Touch){
                    asset.categoryId = 4;
                }
                
                asset.color = [NSString stringWithFormat:@"%@",dict[@"color"]];
                asset.parser = parser;
                asset.name = [NSString stringWithFormat:@"%@",dict[@"name"]];
                asset.coverUrl = [NSURL URLWithString:[packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",dict[@"imageName"]]]];
                break;
            }
        }
    }
    
    NvFilterItem *item = [NvFilterItem new];
    item.displayName = @"无";
    item.cover = @"NvsFilterNone";
    item.selected = NO;
    item.isParticle = NO;
    
    NvFilterItem *item_1 = [NvFilterItem new];
    item_1.displayName = @"无";
    item_1.cover = @"NvsFilterNone";
    item_1.selected = NO;
    item_1.isParticle = NO;
    
    NvFilterItem *item_2 = [NvFilterItem new];
    item_2.displayName = @"无";
    item_2.cover = @"NvsFilterNone";
    item_2.selected = NO;
    item_2.isParticle = NO;
    
    [self.filterFxArray addObject:item];
    [self.faceFxArray addObject:item_1];
    [self.gesturesFxArray addObject:item_2];
    
    NSArray *temporaryArray1 = [self.assetManager getUsableAssets:ASSET_PARTICLE aspectRatio:AspectRatio_All categoryId:1];
    for (NvAsset *asset in temporaryArray1) {
        if (asset.downloadStatus == DownloadStatusDecompressingFailed) {
            continue;
        }
        NvFilterItem *item = [NvFilterItem new];
        item.packID = asset.uuid;
        item.displayName = asset.name;
        item.cover = [asset.coverUrl absoluteString];
        item.categoryId = asset.categoryId;
        item.parser = asset.parser;
        item.isParticle = NO;
        
        [self.filterFxArray addObject:item];
    }
    
    NSArray *temporaryArray2 = [self.assetManager getUsableAssets:ASSET_PARTICLE aspectRatio:AspectRatio_All categoryId:2];
    for (NvAsset *asset in temporaryArray2) {
        NvFilterItem *item = [NvFilterItem new];
        item.packID = asset.uuid;
        item.displayName = asset.name;
        item.cover = [asset.coverUrl absoluteString];
        item.categoryId = asset.categoryId;
        item.parser = asset.parser;
        
        [self.faceFxArray addObject:item];
    }
    
    NSArray *temporaryArray3 = [self.assetManager getUsableAssets:ASSET_PARTICLE aspectRatio:AspectRatio_All categoryId:3];
    for (NvAsset *asset in temporaryArray3) {
        NvFilterItem *item = [NvFilterItem new];
        item.packID = asset.uuid;
        item.displayName = asset.name;
        item.cover = [asset.coverUrl absoluteString];
        item.categoryId = asset.categoryId;
        item.parser = asset.parser;
        
        [self.gesturesFxArray addObject:item];
    }
    
    self.particleDataSource = self.filterFxArray;
}

#pragma mark 给标签视图的数组添加数据
- (void)addtitleArray{
    NSArray *titleArray = @[@"滤镜", @"人脸", @"手势"];
    NSArray *titleImage_noArray = @[@"NvParticleFilter_no", @"NvParticleFace_no", @"NvParticleHand_no"];
    NSArray *titleImageArray = @[@"NvParticleFilter", @"NvParticleFace", @"NvParticleHand"];
    for (int i = 0; i < titleArray.count; i++) {
        NvLabelModel *model = [NvLabelModel new];
        model.labelName = titleArray[i];
        model.labelImage_no = titleImage_noArray[i];
        model.labelImage = titleImageArray[i];
        if (i == 0) {
            model.first = YES;
            model.selected = YES;
        }
        [self.labelArray addObject:model];
    }
}

#pragma mark 初始化sdk
- (void)startupCapture{
    // 初始化SDK
    self.streamingContext = [NvSDKUtils getSDKContext];
    if (!_streamingContext) {
        NSLog(@"初始化失败！");
        return;
    }

    self.stMobileDtected = [[stMobileDetected alloc] init];
    if(![self.stMobileDtected initSTMobileDetected]){
        self.stMobileDtected = nil;
        NSLog(@"初始化商汤检测失败");
    }
    // 设置回调接口
    _streamingContext.delegate = self;

    // 检查可用采集设备的数量
    if ([_streamingContext captureDeviceCount] == 0) {
        NSLog(@"没有可用于采集的设备！");
    }

    // 创建采集预览窗口并连接到摄像头采集次输出
    _liveWindowBack = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_liveWindowBack];
    _liveWindow = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_liveWindow];
    _curLiveWindow = _liveWindowBack;
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }
    _curLiveWindow = _liveWindow;
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }

    self.currentDeviceIndex = [self frontCameraDeviceIndex];
    if (![self startCapturePreview]) {
        NSLog(@"启动摄像头采集预览失败！");
    }

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    tap.numberOfTapsRequired = 1;
    [_liveWindow addGestureRecognizer:tap];

    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    tap.numberOfTapsRequired = 1;
    [_liveWindowBack addGestureRecognizer:tap1];
    
    [self addSubViews];
    [self addParticleFxView];
    [self initFocusView];
    [self configParameter];
}

#pragma mark 添加子视图
- (void)addSubViews{
    // 初始化UI
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[NvUtils imageWithName:@"Nvback"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.deviceBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"切换" withImageNormal:@"Nvdevice" withImageSelected:nil];
    [self.deviceBtn addTarget:self action:@selector(deviceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.flashBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"补光" withImageNormal:@"Nvflash_off" withImageSelected:@"Nvflash_on"];
    [self.flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.particleBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"粒子" withImageNormal:@"Nvfilter" withImageSelected:nil];
    [self.particleBtn addTarget:self action:@selector(particleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.graffitiBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"涂鸦" withImageNormal:@"NvGraffiti" withImageSelected:nil];
    [self.graffitiBtn addTarget:self action:@selector(graffitiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.shootingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shootingBtn setImage:[NvUtils imageWithName:@"Nvshooting"] forState:UIControlStateNormal];
    [self.shootingBtn setImage:[NvUtils imageWithName:@"Nvsuspended"] forState:UIControlStateSelected];
    [self.shootingBtn addTarget:self action:@selector(shootingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.shootingBtn_1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shootingBtn_1 setImage:[NvUtils imageWithName:@"NvParticleShooting"] forState:UIControlStateNormal];
    [self.shootingBtn_1 addTarget:self action:@selector(shootingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteBtn setImage:[NvUtils imageWithName:@"Nvdelete"] forState:UIControlStateNormal];
    [self.deleteBtn addTarget:self action:@selector(deleteBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishBtn setImage:[NvUtils imageWithName:@"Nvfinish"] forState:UIControlStateNormal];
    [self.finishBtn addTarget:self action:@selector(finishBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.timeLabel = [UILabel new];
    self.timeLabel.text = @"00:00";
    self.timeLabel.textColor = [UIColor nv_colorWithHexRGB:@"#D0021B"];
    self.timeLabel.font = [NvUtils fontWithSize:12];
    
    self.videoCount = [UILabel new];
    self.videoCount.userInteractionEnabled = NO;
    self.videoCount.font = [NvUtils fontWithSize:12];
    self.videoCount.textColor = UIColor.whiteColor;
    
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.deviceBtn];
    [self.view addSubview:self.flashBtn];
    [self.view addSubview:self.particleBtn];
    [self.view addSubview:self.graffitiBtn];
    [self.view addSubview:self.shootingBtn];
    [self.view addSubview:self.deleteBtn];
    [self.view addSubview:self.finishBtn];
    [self.view addSubview:self.timeLabel];
    [self.shootingBtn addSubview:self.shootingBtn_1];
    [self.shootingBtn addSubview:self.videoCount];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NV_STATUSBARHEIGHT);
        make.left.equalTo(self.view).offset(13 * SCREANSCALE);
        make.width.offset(33 * SCREANSCALE);
        make.height.offset(33 * SCREANSCALE);
    }];
    
    [self.deviceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NV_STATUSBARHEIGHT);
        make.right.equalTo(self.view).offset(- 13 * SCREANSCALE);
        make.width.offset(33 * SCREANSCALE);
    }];
    
    [self.flashBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.deviceBtn.mas_bottom).offset(12 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.particleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.flashBtn.mas_bottom).offset(12 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.graffitiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.particleBtn.mas_bottom).offset(12 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.shootingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(- 20 * SCREANSCALE);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.offset(64 * SCREANSCALE);
        make.height.offset(64 * SCREANSCALE);
    }];
    
    [self.shootingBtn_1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shootingBtn);
        make.bottom.equalTo(self.shootingBtn);
        make.left.equalTo(self.shootingBtn);
        make.right.equalTo(self.shootingBtn);
    }];
    
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.shootingBtn.mas_left).offset(- 56 * SCREANSCALE);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
        make.width.offset(48 * SCREANSCALE);
        make.height.offset(33 * SCREANSCALE);
    }];
    
    [self.finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.shootingBtn.mas_right).offset(56 * SCREANSCALE);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
        make.width.offset(40 * SCREANSCALE);
        make.height.offset(40 * SCREANSCALE);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.backBtn.mas_centerY);
    }];
    
    [self.videoCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.shootingBtn.mas_centerX);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
    }];
}

#pragma mark 添加特效标签滚动视图
- (void)addParticleFxView{
    
    _particlePanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 213*SCREANSCALE + INDICATOR)];
    _particlePanelView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_particlePanelView];
    
    _particleHeaderView = [[UIView alloc] init];
    _particleHeaderView.hidden = YES;
    _particleHeaderView.backgroundColor = [UIColor clearColor];
    [_particlePanelView addSubview:_particleHeaderView];
    [_particleHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.particlePanelView);
        make.width.offset(SCREANWIDTH);
        make.height.offset(67 * SCREANSCALE);
    }];
    
    UIView *particleBottomView = [[UIView alloc]init];
    particleBottomView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#99000000"];
    [self.view addSubview:particleBottomView];
    [particleBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.particleHeaderView.mas_bottom);
        make.bottom.equalTo(self.particlePanelView.mas_bottom);
        make.left.equalTo(self.particlePanelView.mas_left);
        make.right.equalTo(self.particlePanelView.mas_right);
    }];
    
    self.filterSpeeadLabel = [[UILabel alloc]initWithFrame:CGRectMake(13 * SCREANSCALE, 17 * SCREANSCALE, 28 * SCREANSCALE, 20 * SCREANSCALE)];;
    _filterSpeeadLabel.text = @"速率";
    _filterSpeeadLabel.font = [NvUtils fontWithSize:12];
    _filterSpeeadLabel.textColor = UIColor.whiteColor;
    [_filterSpeeadLabel sizeToFit];
    [_particleHeaderView addSubview:_filterSpeeadLabel];
    
    self.filterSpeeadSlider = [[UISlider alloc]initWithFrame:CGRectMake(55 * SCREANSCALE, 24 * SCREANSCALE, 308 * SCREANSCALE, 10 * SCREANSCALE)];
    [self.filterSpeeadSlider setMinimumValue:0.1];
    [self.filterSpeeadSlider setMaximumValue:6.0];
    self.filterSpeeadSlider.value = 1;
    self.filterSpeeadSlider.minimumTrackTintColor = [UIColor whiteColor];
    self.filterSpeeadSlider.maximumTrackTintColor = [UIColor whiteColor];
    [self.filterSpeeadSlider setThumbImage:[NvUtils imageWithName:@"Nvslider"] forState:UIControlStateNormal];
    [self.filterSpeeadSlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_particleHeaderView addSubview:_filterSpeeadSlider];
    
    self.filterStrengthLabel = [[UILabel alloc]initWithFrame:CGRectMake(13 * SCREANSCALE, 43 * SCREANSCALE, 28 * SCREANSCALE, 20 * SCREANSCALE)];;
    _filterStrengthLabel.text = @"强度";
    _filterStrengthLabel.font = [NvUtils fontWithSize:12];
    _filterStrengthLabel.textColor = UIColor.whiteColor;
    [_filterStrengthLabel sizeToFit];
    [_particleHeaderView addSubview:_filterStrengthLabel];
    
    self.filterStrengthSlider = [[UISlider alloc]initWithFrame:CGRectMake(55 * SCREANSCALE, 50 * SCREANSCALE, 308 * SCREANSCALE, 10 * SCREANSCALE)];
    [self.filterStrengthSlider setMinimumValue:0.1];
    [self.filterStrengthSlider setMaximumValue:6.0];
    self.filterStrengthSlider.value = 1;
    self.filterStrengthSlider.minimumTrackTintColor = [UIColor whiteColor];
    self.filterStrengthSlider.maximumTrackTintColor = [UIColor whiteColor];
    [self.filterStrengthSlider setThumbImage:[NvUtils imageWithName:@"Nvslider"] forState:UIControlStateNormal];
    [self.filterStrengthSlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_particleHeaderView addSubview:_filterStrengthSlider];
    
    UICollectionViewFlowLayout *layout1 = [[UICollectionViewFlowLayout alloc] init];
    layout1.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout1.itemSize = CGSizeMake(SCREEN_WDITH/self.labelArray.count, 32*SCREANSCALE);
    layout1.minimumLineSpacing = 0;
    layout1.minimumInteritemSpacing = 0;
    layout1.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _segmentedView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout1];
    _segmentedView.backgroundColor = [UIColor clearColor];
    _segmentedView.delegate = self;
    _segmentedView.dataSource = self;
    _segmentedView.showsHorizontalScrollIndicator = NO;
    [particleBottomView addSubview:_segmentedView];
    [_segmentedView registerClass:[NvLabelCell class] forCellWithReuseIdentifier:@"NvLabelCell"];
    [_segmentedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(particleBottomView.mas_top);
        make.left.equalTo(particleBottomView);
        make.right.equalTo(particleBottomView);
        make.height.offset(32 * SCREANSCALE);
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#26FFFFFF"];
    [particleBottomView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(particleBottomView);
        make.right.equalTo(particleBottomView);
        make.top.equalTo(self.segmentedView.mas_bottom);
        make.height.offset(1);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(58*SCREANSCALE, 70*SCREANSCALE);
    layout.minimumLineSpacing = 10*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    _particleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _particleCollectionView.delegate = self;
    _particleCollectionView.dataSource = self;
    _particleCollectionView.backgroundColor = [UIColor clearColor];
    _particleCollectionView.showsHorizontalScrollIndicator = NO;
    [particleBottomView addSubview:_particleCollectionView];
    [_particleCollectionView registerClass:[NvFilterCell class] forCellWithReuseIdentifier:@"NvFilterCell"];
    [_particleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line.mas_bottom);
        make.left.equalTo(self.particlePanelView);
        make.right.equalTo(self.particlePanelView);
        make.height.offset(97 * SCREANSCALE);
    }];
}

#pragma mark 添加手动对焦视图
- (void)initFocusView{
    self.focusView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.focusView.alpha = 0;
    [_focusView setImage:[NvUtils imageWithName:@"NvsCaptureFocus"]];
    [self.view addSubview:self.focusView];
}

#pragma mark 启动采集之后，初始化效果采集参数
- (void)configParameter{
    self.timeLabel.hidden = YES;
    self.deleteBtn.hidden = YES;
    self.finishBtn.hidden = YES;
    
    [self.streamingContext removeAllCaptureVideoFx];
    if (_currentDeviceIndex == [self frontCameraDeviceIndex]) {
        self.flashBtn.userInteractionEnabled = NO;
        self.flashBtn.alpha = 0.7;
    } else {
        self.flashBtn.userInteractionEnabled = YES;
        self.flashBtn.alpha = 1;
    }
}

#pragma mark 相册权限提示
- (void)tipView{
    self.photoView = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"保存失败" describeTitle:@"您还没有允许相册访问权限" describeContent:nil buttonText:@"知道了" withCenter:YES];
    [_photoView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_photoView];
}

#pragma mark tipView按钮点击事件
- (void)knowClick:(UIButton *)sender{
    _photoView.hidden = YES;
}

#pragma mark 将拍摄的视频保存到本地相册
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打包成功" message:@"已保存至相册" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark 滤镜强度、速度强度调节
- (void)sliderValueChanged:(UISlider *)slider{
    [_stMobileDtected setCurrentParticleEffect:nil effectDesc:nil];
    NSArray* emitter = [self.currentItem.parser getParticlePartitionEmitter:0];
    if(!emitter){
        return;
    }
    if ([slider isEqual:self.filterSpeeadSlider]) {
        for (int i = 0; i < emitter.count; i++){
            [self.particleContext setEmitterRateGain:emitter[i] emitterGain:slider.value];
        }
    }else{
        for (int i = 0; i < emitter.count; i++){
            [self.particleContext SetEmitterParticleSizeGain:emitter[i] emitterGain:slider.value];
        }
    }
}

#pragma mark NvsStreamingContextDelegate
- (void)didCaptureRecordingDurationUpdated:(int)captureDeviceIndex duration:(int64_t)duration{
    self.lastDuration = duration;
    self.timeLabel.text = [NvUtils convertTimecode:self.duration + duration];
    if (duration >= NV_TIME_BASE) {
        self.shootingBtn.enabled = YES;
    }
}

- (void)didCaptureDeviceCapsReady:(unsigned int)captureDeviceIndex{
    // 获取采集设备的能力描述
    NvsCaptureDeviceCapability *capability = [_streamingContext getCaptureDeviceCapability:captureDeviceIndex];
    if (!capability){
        return;
    }
}

//获取采集预览图像
- (void)captureVideoFrameGrabbedArrived:(NvsVideoFrameInfo*)sampleBufferInfo{
    if(!sampleBufferInfo)
        return;
    if (!self.stMobileDtected) {
        return;
    }
    [self.stMobileDtected grabberVideoFrameArrived:sampleBufferInfo];
}

#pragma mark 删除按钮点击
- (void)deleteBtnBtnClick:(UIButton *)sender{
    NSString *filePath = (NSString *)[_videoPathArray lastObject];
    [_videoPathArray removeLastObject];
    NSError *error;
    if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]){
        NSLog(@"删除文件失败, 错误: %@", error);
    }
    if (_videoPathArray.count == 0) {
        self.videoCount.text = @"";
        self.timeLabel.text = @"00:00";
        self.timeLabel.hidden = YES;
        self.deleteBtn.hidden = YES;
        self.finishBtn.hidden = YES;
        self.duration = 0;
        self.shootingBtn_1.hidden = NO;
        self.graffitiBtn.enabled = YES;
    }else{
        self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
        self.duration = self.duration - [[_durationArray lastObject] longLongValue];
        self.timeLabel.text = [NvUtils convertTimecode:self.duration];
    }
}

#pragma mark 切换摄像头
- (void)deviceBtnClick:(UIButton *)sender{
    UIView *fromView;
    UIView *toView;
    if ([_curLiveWindow isEqual:_liveWindow]) {
        fromView = _liveWindow;
        toView = _liveWindowBack;
    } else {
        fromView = _liveWindowBack;
        toView = _liveWindow;
    }
    _curLiveWindow = (NvsLiveWindow *)toView;
    
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }
    
    if (_currentDeviceIndex == 0) {
        _currentDeviceIndex = 1;
    } else {
        _currentDeviceIndex = 0;
    }
    
    if (_currentDeviceIndex == [self frontCameraDeviceIndex]) {
        _flashBtn.alpha = 0.7;
        _flashBtn.userInteractionEnabled = NO;
        _flashBtn.selected = NO;
    } else {
        _flashBtn.alpha = 1;
        _flashBtn.userInteractionEnabled = YES;
    }
    
    [UIView transitionFromView:fromView toView:toView duration:0.3 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
        [self.view sendSubviewToBack:self.curLiveWindow];
    }];
    [self startCapturePreview];
}

#pragma mark 闪光灯开关
- (void)flashBtnClick:(UIButton *)sender{
    if ([_streamingContext getCaptureDeviceCapability:_currentDeviceIndex].supportFlash) {
        [_streamingContext toggleFlash:![_streamingContext isFlashOn]];
        _flashBtn.selected = sender.selected ? NO : YES;
    }
}

#pragma mark 拍摄按钮点击
- (void)shootingBtnClick:(UIButton *)sender{
    if ([sender isEqual:self.shootingBtn_1]) {
        self.shootingBtn_1.hidden = YES;
        self.shootingBtn.selected = YES;
        self.timeLabel.textColor = UIColor.redColor;
        self.videoCount.hidden = YES;
        [self faceHiddenBtn:YES];
        self.shootingBtn.hidden = NO;
        self.timeLabel.hidden = NO;
        self.shootingBtn.enabled = NO;
        [self startRecording];
    }else{
        if (sender.selected) {
            sender.selected = NO;
            [self faceHiddenBtn:NO];
            [self stopRecording];
            self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
            self.timeLabel.textColor = UIColor.whiteColor;
            self.videoCount.hidden = NO;
            self.duration = self.duration + self.lastDuration;
            [self.durationArray addObject:[NSNumber numberWithLongLong:self.lastDuration]];
            self.graffitiBtn.enabled = NO;
        }else{
            self.timeLabel.textColor = UIColor.redColor;
            self.videoCount.hidden = YES;
            sender.selected = YES;
            [self faceHiddenBtn:YES];
            self.shootingBtn.hidden = NO;
            self.timeLabel.hidden = NO;
            self.shootingBtn.enabled = NO;
            [self startRecording];
        }
    }
}

#pragma mark 涂鸦按钮点击事件
- (void)graffitiBtnClick:(UIButton *)sender{
    NvAlbumViewController *vc = [[NvAlbumViewController alloc]init];
    vc.delegate = self;
    vc.isOnlyVideo = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 关闭退出
- (void)backBtnClick:(UIButton *)sender{
    [_streamingContext removeAllCaptureVideoFx];
    [_streamingContext stop];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 粒子按钮点击事件
- (void)particleBtnClick:(UIButton *)sender{
    self.clickState = YES;
    [self faceHiddenBtn:YES];
    [UIView animateWithDuration:0.1 animations:^{
        self.particlePanelView.frame = CGRectMake(0, SCREEN_HEIGTH - self.particlePanelView.frame.size.height, SCREEN_WDITH, self.particlePanelView.frame.size.height);
    }];
}

#pragma mark 完成按钮点击
- (void)finishBtnBtnClick:(UIButton *)sender{
    //路径数组 self.videoPathArray
    AVURLAsset*audioAsset=[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.videoPathArray.firstObject] options:nil];
    AVAssetTrack *track = [[audioAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    CGSize dimensions = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);
    if (dimensions.width > dimensions.height) {
       // NvEditMode16v9;
        [self addPreviewView:NvEditMode16v9 withPathArray:self.videoPathArray];
    }else{
       // NvEditMode9v16;
        [self addPreviewView:NvEditMode9v16 withPathArray:self.videoPathArray];
    }
}

#pragma mark 预览视图
- (void)addPreviewView:(NvEditMode)editMode withPathArray:(NSMutableArray *)path{
    self.preView = [[NvPreViewLiveWindow alloc]initWithFrame:self.view.frame];
    self.preView.delegate = self;
    self.preView.pathArray = path;
    self.preView.model = editMode;
    [self.view addSubview:self.preView];
}

#pragma mark NvPreViewLiveWindowDelegate
//退出关闭预览视图
- (void)backClick{
    [self.preView removeFromSuperview];
    self.preView = nil;
    [self.streamingContext connectCapturePreviewWithLiveWindow:self.curLiveWindow];
    self.streamingContext.delegate = self;
    [self startCapturePreview];
}

//生成按钮点击事件
- (void)compileClick:(NvsTimeline *)timeline{
    self.compileFilePath = [VIDEO_PATH(@"Compile") stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [NvUtils currentDateAndTime]]];
    NvCompileViewController *compileViewController = [NvCompileViewController new];
    compileViewController.delegate = self;
    compileViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [compileViewController compileTimeline:timeline outputPath:self.compileFilePath];
    [self presentViewController:compileViewController animated:NO completion:nil];
}

#pragma mark - NvCompileViewControllerDelegate
- (void)compileFinished:(BOOL)needDelete {
    [self.preView againConnection];
    if (needDelete) {
        [[NSFileManager defaultManager] removeItemAtPath:self.compileFilePath error:nil];
    } else {
        UISaveVideoAtPathToSavedPhotosAlbum(self.compileFilePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    }
}

#pragma mark 获取前置摄像头设备索引
- (unsigned int)frontCameraDeviceIndex {
    for (unsigned int i = 0; i < _streamingContext.captureDeviceCount; i++) {
        if (![_streamingContext isCaptureDeviceBackFacing:i])
            return i;
    }
    return _streamingContext.captureDeviceCount - 1;
}

#pragma mark 启动摄像头采集预览
- (BOOL)startCapturePreview {
    NSNumber *num = NV_UserInfo(@"NvRecordResolution");
    NvsVideoCaptureResolutionGrade captureResGrade = [num intValue] == 1080? NvsVideoCaptureResolutionGradeHigh:NvsVideoCaptureResolutionGradeMedium;
    if ([_streamingContext isCaptureDeviceBackFacing:_currentDeviceIndex]){
        captureResGrade = NvsVideoCaptureResolutionGradeMedium;
    }
    return [_streamingContext startCapturePreview:_currentDeviceIndex videoResGrade:captureResGrade flags: NvsStreamingEngineCaptureFlag_CaptureBuddyHostVideoFrame |NvsStreamingEngineCaptureFlag_GrabCapturedVideoFrame | NvsStreamingEngineCaptureFlag_StrictPreviewVideoSize aspectRatio:nil];
}

#pragma mark 开始录制
- (void)startRecording{
    NSString *path = [VIDEO_PATH(@"Particle") stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [NvUtils currentDateAndTime]]];
    NSMutableDictionary *config = [[NSMutableDictionary alloc] init];
    [_streamingContext startRecordingWithFx:path withFlags:0 withRecordConfigurations:config];
    [self.videoPathArray addObject:path];
}

#pragma mark 关闭录制
- (void)stopRecording{
    [_streamingContext stopRecording];
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
    {
        if (!self.photoView) {
            [self tipView];
        }
        return;
    }
    if (self.photoView) {
        [self.photoView removeFromSuperview];
    }
    UISaveVideoAtPathToSavedPhotosAlbum(self.videoPathArray.lastObject, self, nil, nil);
    
    //    UISaveVideoAtPathToSavedPhotosAlbum(
    //                                        self.videoPathArray.lastObject, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark 点击隐藏界面按钮
- (void)faceHiddenBtn:(BOOL)hidden{
    self.deviceBtn.hidden = hidden;
    self.flashBtn.hidden = hidden;
    self.backBtn.hidden = hidden;
    self.shootingBtn.hidden = hidden;
//    self.shootingBtn_1.hidden = hidden;
    self.timeLabel.hidden = hidden;
    self.deleteBtn.hidden = hidden;
    self.finishBtn.hidden = hidden;
    self.particleBtn.hidden = hidden;
    self.graffitiBtn.hidden = hidden;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == _particleCollectionView) {
        return _particleDataSource.count;
    }
    return _labelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _particleCollectionView) {
        NvFilterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvFilterCell" forIndexPath:indexPath];
        [cell renderCellWithItem:_particleDataSource[indexPath.item]];
        return cell;
    }
    NvLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvLabelCell" forIndexPath:indexPath];
    [cell renderCellWithModel:_labelArray[indexPath.item]];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == _particleCollectionView) {
        for (NvFilterItem *model in self.particleDataSource) {
            model.selected = NO;
        }
        NvFilterItem *model = self.particleDataSource[indexPath.item];
        model.selected = YES;
        if (indexPath.item == 0) {
            _particleHeaderView.hidden = YES;
             [self applyCurrentFxSelected:nil withPackageID:@""];
        }else{
            if ([self.particleDataSource isEqual:self.filterFxArray]) {
                _particleHeaderView.hidden = NO;
            }
            self.currentItem = model;
            [self applyCurrentFxSelected:model.parser withPackageID:model.packID];
        }
    }else{
        [self applyCurrentFxSelected:nil withPackageID:@""];
        self.particleHeaderView.hidden = YES;
        for (NvLabelModel *model in self.labelArray) {
            model.selected = NO;
        }
        NvLabelModel *model = self.labelArray[indexPath.item];
        model.selected = YES;
        
        if (indexPath.item == 0) {
            self.particleDataSource = self.filterFxArray;
            self.particlePanelView.frame = CGRectMake(0,self.particlePanelView.frame.origin.y, SCREANWIDTH, self.particlePanelView.frame.size.height);
        }else{
            if (indexPath.item == 1) {
                self.particleDataSource = self.faceFxArray;
            }else if(indexPath.item == 2){
                self.particleDataSource = self.gesturesFxArray;
            }
            self.particlePanelView.frame = CGRectMake(0,self.particlePanelView.frame.origin.y, SCREANWIDTH, self.particlePanelView.frame.size.height);
        }
        for (NvFilterItem *item in self.particleDataSource) {
            if (item.selected) {
                if ([self.particleDataSource isEqual:self.filterFxArray]) {
                    if ([item.displayName isEqualToString:@"无"]) {
                        self.particleHeaderView.hidden = YES;
                    }else{
                        self.particleHeaderView.hidden = NO;
                    }
                }
                [self applyCurrentFxSelected:item.parser withPackageID:item.packID];
            }
        }
        
        [_particleCollectionView reloadData];
    }
    [collectionView reloadData];
}

#pragma mark 添加粒子特效
- (void)applyCurrentFxSelected:(NvsAssetPackageParticleDescParser *)parser withPackageID:(NSString *)packageID{
    if (parser) {
        if (self.videoFx) {
            [_streamingContext removeCaptureVideoFx:self.videoFx.index];
        }
        self.videoFx = [_streamingContext appendPackagedCaptureVideoFx:packageID];
        _stMobileDtected.currentFx = self.videoFx;
        self.particleContext = [self.videoFx getParticleSystemContext];
        self.currentParser = parser;
        if (self.tipBoxView) {
            [self.timer invalidate];
            [self.tipBoxView removeFromSuperview];
            self.tipBoxView = nil;
        }
        [self useAngleParticle];
        UIDevice *device = [UIDevice currentDevice] ;
        switch (device.orientation) {
            case UIDeviceOrientationFaceUp:
                NSLog(@"屏幕朝上平躺");
                break;
                
            case UIDeviceOrientationFaceDown:
                NSLog(@"屏幕朝下平躺");
                break;
                
                //系統無法判斷目前Device的方向，有可能是斜置
            case UIDeviceOrientationUnknown:
                NSLog(@"未知方向");
                break;
                
            case UIDeviceOrientationLandscapeLeft:
                NSLog(@"屏幕向左横置");
                self.angleString = @"270";
                _stMobileDtected.rotate_type = 3;
                self.currentAngleArray = self.AngleArray_270;
                break;
                
            case UIDeviceOrientationLandscapeRight:
                NSLog(@"屏幕向右橫置");
                self.angleString = @"90";
                _stMobileDtected.rotate_type = 1;
                self.currentAngleArray = self.AngleArray_90;
                break;
                
            case UIDeviceOrientationPortrait:
                NSLog(@"屏幕直立");
                self.angleString = @"正常";
                _stMobileDtected.rotate_type = 0;
                self.currentAngleArray = self.AngleArray_0;
                break;
                
            case UIDeviceOrientationPortraitUpsideDown:
                NSLog(@"屏幕直立，上下顛倒");
                self.angleString = @"180";
                _stMobileDtected.rotate_type = 2;
                self.currentAngleArray = self.AngleArray_180;
                break;
                
            default:
                NSLog(@"无法辨识");
                break;
        }
        NSLog(@"%@",self.currentAngleArray);
        
        if (parser.getParticleType == NvsParticleType_Mouth) {
            [self noUsrArray:self.AngleArray_0];
            [self noUsrArray:self.AngleArray_90];
            [self noUsrArray:self.AngleArray_180];
            [self noUsrArray:self.AngleArray_270];
            _stMobileDtected.curentTirection = self.currentAngleArray;
            [self AddtipBoxView:@"请张嘴，体验粒子效果" WithImage:[NvUtils imageWithName:@"NvParticleFaceTip"]];
            [_stMobileDtected setCurrentParticleEffect:self.particleContext effectDesc:parser];
        }else if (parser.getParticleType == NvsParticleType_Eye){
            [self noUsrArray:self.AngleArray_0];
            [self noUsrArray:self.AngleArray_90];
            [self noUsrArray:self.AngleArray_180];
            [self noUsrArray:self.AngleArray_270];
             _stMobileDtected.curentTirection = self.currentAngleArray;
            [self AddtipBoxView:@"请眨眨眼，体验粒子效果" WithImage:[NvUtils imageWithName:@"NvParticleHandTip"]];
            [_stMobileDtected setCurrentParticleEffect:self.particleContext effectDesc:parser];
        }else if (parser.getParticleType == NvsParticleType_Gesture){
            [self AddtipBoxView:@"请手指举1，体验粒子效果" WithImage:[NvUtils imageWithName:@"NvParticleControlTip"]];
            [_stMobileDtected setCurrentParticleEffect:self.particleContext effectDesc:parser];
        }else if(parser.getParticleType == NvsParticleType_Normal){
            [_stMobileDtected setCurrentParticleEffect:nil effectDesc:nil];
            if(!self.AngleArray_0){
                return;
            }
            for (int i = 0; i < self.currentAngleArray.count; i++){
                [self.particleContext setEmitterRateGain:self.AngleArray_0[i] emitterGain:1.0];
                [self.particleContext SetEmitterParticleSizeGain:self.AngleArray_0[i] emitterGain:1.0];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self useAngleParticle_Use];
            });
        }
    }else{
        [_streamingContext removeAllCaptureVideoFx];
        [_stMobileDtected setCurrentParticleEffect:nil effectDesc:nil];
    }
}

#pragma mark 把粒子特效中当前方向和其他方向区分开
- (void)useAngleParticle{
    if (self.currentAngleArray.count != 0) {
        [self.AngleArray_0 removeAllObjects];
        [self.AngleArray_90 removeAllObjects];
        [self.AngleArray_180 removeAllObjects];
        [self.AngleArray_270 removeAllObjects];
    }
    NSInteger conut = [self.currentParser getParticlePartitionCount];
    for (int i = 0; i<conut; i++) {
        NSArray* emitter = [self.currentParser getParticlePartitionEmitter:i];
        for (NSString *emitterString in emitter) {
            if ([emitterString hasSuffix:@"90"]) {
                [self.AngleArray_90 addObject:emitterString];
            }else if ([emitterString hasSuffix:@"180"]){
                [self.AngleArray_180 addObject:emitterString];
            }else if ([emitterString hasSuffix:@"270"]){
                [self.AngleArray_270 addObject:emitterString];
            }else{
                [self.AngleArray_0 addObject:emitterString];
            }
        }
    }
}

#pragma mark 把粒子特效中当前方向开启，其他方向禁用
- (void)useAngleParticle_Use{
//    NSLog(@"%@",self.currentAngleArray);
    for (NSString *usrString in self.currentAngleArray) {
        [self.particleContext setEmitterEnabled:usrString
                                  emitterEnable:YES];
    }
    if (_stMobileDtected.rotate_type == 0) {
        [self noUsrArray:self.AngleArray_90];
        [self noUsrArray:self.AngleArray_180];
        [self noUsrArray:self.AngleArray_270];
    }else if(_stMobileDtected.rotate_type == 1){
        [self noUsrArray:self.AngleArray_0];
        [self noUsrArray:self.AngleArray_180];
        [self noUsrArray:self.AngleArray_270];
    }else if(_stMobileDtected.rotate_type == 2){
        [self noUsrArray:self.AngleArray_0];
        [self noUsrArray:self.AngleArray_90];
        [self noUsrArray:self.AngleArray_270];
    }else if(_stMobileDtected.rotate_type == 3){
        [self noUsrArray:self.AngleArray_0];
        [self noUsrArray:self.AngleArray_90];
        [self noUsrArray:self.AngleArray_180];
    }
}

- (void)noUsrArray:(NSMutableArray *)array{
    for (NSString *usrString in array) {
        [self.particleContext setEmitterEnabled:usrString
                                  emitterEnable:NO];
    }
}

#pragma mark 增加粒子提示视图
- (void)AddtipBoxView:(NSString *)title WithImage:(UIImage *)imageFile{
    
    if (!self.tipBoxView) {
        self.tipBoxView = [[UIView alloc]init];
        self.tipBoxView.layer.masksToBounds = YES;
        self.tipBoxView.layer.cornerRadius = 8;
        self.tipBoxView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#454A4A4A"];
        [self.liveWindow addSubview:self.tipBoxView];
        [self.tipBoxView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.particlePanelView.mas_top).offset(40 * SCREANSCALE);
            make.centerX.equalTo(self.view.mas_centerX);
            make.width.offset(185 * SCREANSCALE);
            make.height.offset(60 * SCREANSCALE);
        }];
        
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = imageFile;
        [self.tipBoxView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tipBoxView.mas_top).offset(8 * SCREANSCALE);
            make.centerX.equalTo(self.tipBoxView.mas_centerX);
            make.width.offset(21 * SCREANSCALE);
            make.height.offset(21 * SCREANSCALE);
        }];
        
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.textColor = UIColor.whiteColor;
        titleLabel.font = [UIFont systemFontOfSize:14 * SCREANSCALE];
        titleLabel.text = title;
        [self.tipBoxView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(5 * SCREANSCALE);
            make.centerX.equalTo(self.tipBoxView.mas_centerX);
        }];
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(deleteTip:) userInfo:nil repeats:NO];
}

- (void)deleteTip:(NSTimer *)timer{
    [self.timer invalidate];
    [self.tipBoxView removeFromSuperview];
    self.tipBoxView = nil;
}

#pragma mark NvAlbumViewControllerDelegate
- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    NvAlbumAsset *asset = [assets firstObject];
    NvParEditViewController *editVC = [[NvParEditViewController alloc]init];
    editVC.selectAssets = assets;
    if (asset.asset.pixelHeight > asset.asset.pixelWidth) {
        editVC.editMode = NvEditMode9v16;
    }else{
        editVC.editMode = NvEditMode16v9;
    }
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark 给手动对焦视图添加动画
- (void)animateFocusView:(CGPoint)currentPoint{
    self.focusView.center = currentPoint;
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = 0.8;
    
    CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    alphaAnimation.fromValue = @1;
    alphaAnimation.toValue   = @1;
    alphaAnimation.repeatCount = 1;
    alphaAnimation.duration = .8;
    
    CABasicAnimation *focusAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    focusAnimation.fromValue = @1.7;
    focusAnimation.toValue   = @1;
    focusAnimation.repeatCount = 1;
    focusAnimation.duration = .3;
    
    CABasicAnimation *focusAnimation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    focusAnimation1.fromValue = @1;
    focusAnimation1.toValue   = @1;
    focusAnimation1.repeatCount = 1;
    focusAnimation1.beginTime = 0.3;
    focusAnimation1.duration = 0.5;
    
    [group setAnimations:@[alphaAnimation,focusAnimation,focusAnimation1]];
    [self.focusView.layer addAnimation:group forKey:@"transform.scale"];
}

#pragma mark 点击空白显示界面按钮
- (void)singleTap:(UITapGestureRecognizer *)recognizer {
    if (self.clickState) {
        self.clickState = NO;
        [self faceHiddenBtn:NO];
        [UIView animateWithDuration:0.1 animations:^{
            self.particlePanelView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, self.particlePanelView.frame.size.height);
        }];
        if (_videoPathArray.count == 0) {
            self.timeLabel.hidden = YES;
            self.deleteBtn.hidden = YES;
            self.finishBtn.hidden = YES;
        }else{
            self.timeLabel.hidden = NO;
            self.deleteBtn.hidden = NO;
            self.finishBtn.hidden = NO;
        }
    }else{
        CGPoint point = [recognizer locationInView:_curLiveWindow];
        if (point.x >= SCREEN_WDITH - 70 * SCREANSCALE || point.y >= SCREEN_HEIGTH - 190 * SCREANSCALE){
            return;
        }
        [_streamingContext startAutoFocus:point];
        [_streamingContext startAutoExposure:point];
        [self animateFocusView:point];
    }
}

#pragma mark 功能待开发中提示
- (void)showTip {
    if (!self.tipAIView) {
        self.tipAIView = [[NvTipsView alloc]initWithFrame:CGRectMake(0, 0, SCREANWIDTH, SCREANHEIGHT) withPrompt:@"提示" describeTitle:[NSString stringWithFormat:@"Demo此功能正在开发中，敬请期待。SDK内部已支持。"] describeContent:nil buttonText:@"知道了" withCenter:YES];
        [self.tipAIView.clickBtn addTarget:self action:@selector(removeTip) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.tipAIView];
    }
}

- (void)removeTip {
    [self.tipAIView removeFromSuperview];
    self.tipAIView = nil;
}

#pragma mark 注册应用前台后台通知事件
- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    /**
     *  添加 设备旋转 通知
     *
     *  当监听到 UIDeviceOrientationDidChangeNotification 通知时，调用handleDeviceOrientationDidChange:方法
     *  @param handleDeviceOrientationDidChange: handleDeviceOrientationDidChange: description
     *
     *  @return return value description
     */
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleDeviceOrientationDidChange:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil
     ];
}

- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation{
    //1.获取 当前设备 实例
    UIDevice *device = [UIDevice currentDevice] ;

    /**
     *  2.取得当前Device的方向，Device的方向类型为Integer
     *
     *  必须调用beginGeneratingDeviceOrientationNotifications方法后，此orientation属性才有效，否则一直是0。orientation用于判断设备的朝向，与应用UI方向无关
     *
     *  @param device.orientation
     *
     */

    switch (device.orientation) {
        case UIDeviceOrientationFaceUp:
            NSLog(@"屏幕朝上平躺");
            break;

        case UIDeviceOrientationFaceDown:
            NSLog(@"屏幕朝下平躺");
            break;

            //系統無法判斷目前Device的方向，有可能是斜置
        case UIDeviceOrientationUnknown:
            NSLog(@"未知方向");
            break;

        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"屏幕向左横置");
            self.angleString = @"270";
            _stMobileDtected.rotate_type = 3;
            self.currentAngleArray = self.AngleArray_270;
            break;
            
        case UIDeviceOrientationLandscapeRight:
            NSLog(@"屏幕向右橫置");
            self.angleString = @"90";
            _stMobileDtected.rotate_type = 1;
            self.currentAngleArray = self.AngleArray_90;
            break;
            
        case UIDeviceOrientationPortrait:
            NSLog(@"屏幕直立");
            self.angleString = @"正常";
            _stMobileDtected.rotate_type = 0;
            self.currentAngleArray = self.AngleArray_0;
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"屏幕直立，上下顛倒");
            self.angleString = @"180";
            _stMobileDtected.rotate_type = 2;
            self.currentAngleArray = self.AngleArray_180;
            break;

        default:
            NSLog(@"无法辨识");
            break;
    }
    _stMobileDtected.curentTirection = self.currentAngleArray;
    [self useAngleParticle_Use];
}

#pragma mark 懒加载权限视图
- (NvTipsView *)permissions{
    if (!_permissions)
    {
        _permissions = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"提示" describeTitle:@"需要打开摄像头和麦克风权限 请在手机设置中进行允许" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [_permissions.clickBtn addTarget:self action:@selector(knowClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _permissions;
}

#pragma mark 权限按钮点击事件
- (void)knowClick{
    [_permissions removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}


// 应用进入后台，停止采集
- (void)applicationWillResignActive:(NSNotification*)notification {
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_CaptureRecording) {
        self.shootingBtn.selected = NO;
        [self faceHiddenBtn:NO];
        [self stopRecording];
        self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
        self.timeLabel.textColor = UIColor.whiteColor;
        self.videoCount.hidden = NO;
        self.duration = self.duration + self.lastDuration;
        [self.durationArray addObject:[NSNumber numberWithLongLong:self.lastDuration]];
    }
    
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_CapturePreview ||[_streamingContext getStreamingEngineState] == NvsStreamingEngineState_Playback) {
        [_streamingContext stop];
    }
}

// 应用进入前台，开始采集
- (void)applicationDidBecomeActive:(NSNotification*)notification {
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_Stopped) {
        if (self.preView) {
            
        }else{
            [self startCapturePreview];
        }
        
    }
}

#pragma mark 防止锁屏
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

- (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
