//
//  NvDouyinCaptureViewController.m
//  SDKDemo
//
//  Created by shizhouhu on 2018/8/30.
 //
//

#import "NvDouyinCaptureViewController.h"
#import "NvDouyinCaptureView.h"
#import "NVHeader.h"
#import <CoreMotion/CoreMotion.h>
#import <AVFoundation/AVFoundation.h>
#import "NvTipsView.h"
#import "NVDefineConfig.h"
#import "UIView+Dimension.h"
#import "NvDouyinEditViewController.h"
#import "NvTimelineDataModel.h"
#import "NvTimelineData.h"
#import "NvAudioPlayer.h"
#import "NvAudioPlayerView.h"
#import "NvRecordingInfo.h"
#import "NvsCaptureVideoFx.h"
#import "NvDouyinFilter.h"
#import "NvFilterItem.h"
#import "NvMoreFilterViewController.h"
#import "NvSDKUtils.h"
#import "NvAssetManager.h"
#import "UIImageView+WebCache.h"
#import "NvTimelineUtils.h"

#import "NvBeautyLogic.h"
#import "NvDouyinBeautyView.h"
#import "NvAlbumViewController.h"
#import "NvTrimVideoViewController.h"
#import "NvTipsView.h"
#import "NvSelectMusicViewController.h"
#import "NvBaseNavigationController.h"
#import "NvCountDownView.h"
#import "NvCountDownAnimationView.h"
#import "NvFilterCell.h"
#import "NvsStreamingContext.h"
#import "NvCaptureFilterView.h"
#import "NvCaptureFilterModel.h"

@interface NvDouyinCaptureViewController ()<NvsStreamingContextDelegate, NvDouyinCaptureViewDelegate, NvDouyinCaptureViewDelegate,NvSelectMusicViewControllerDelegate,NvCountDownAnimationViewDelegate,NvCaptureFilterViewDelegate, UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NvAudioPlayerView *audioPlayerView;

@property (nonatomic, assign) float trimIn;
@property (nonatomic, assign) float trimOut;
@property (nonatomic, assign) BOOL isNoMusic;

//@property (nonatomic, strong) NvDouyinFilter *filterView;
@property (nonatomic, strong) NvCaptureFilterView *filterView;
@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NSMutableArray *filterDataSource;//滤镜数组
@property (nonatomic, strong) NvsCaptureVideoFx *currentFilter;//滤镜

//道具视图
@property (nonatomic, strong) UIView *propsPanelView;//最外层
@property (nonatomic, strong) UICollectionView *propsCollectionView;//道具滑动视图
@property (nonatomic, strong) NSMutableArray *propsDataSource;//道具数组
@property (nonatomic, assign) int currentPropsIndex;

//摄像头的能力
@property (nonatomic, strong) NvsCaptureDeviceCapability *capability;

@property (nonatomic, assign) BOOL isNeedGopSize;

@property (nonatomic, strong) NvAudioPlayer *player;

@property (nonatomic, strong) NvBeautyLogic *beautyLogic;
@property (nonatomic, strong) NvDouyinBeautyView *beautyView;

@property (nonatomic, strong) NvTipsView *tipView;

@property (nonatomic, strong) NvCountDownView *countDownView;

@property (nonatomic, strong) NvCountDownAnimationView *animationView;

@property (nonatomic, assign) int64_t countDownTime;

@end

@implementation NvDouyinCaptureViewController {
    NvDouyinCaptureView *captureView;
    NvTipsView *permissions;
    NvsStreamingContext *streamingContext;
    NvsLiveWindow *liveWindow;
    int currentDeviceIndex;
    NSMutableArray *videoPathArray;
    NSString *musicPath;
    float recordingSpeed;
}

- (void)dealloc {
    NSLog(@"%s",__FUNCTION__);
    [streamingContext removeAllCaptureVideoFx];
    [captureView removeObserver:self forKeyPath:@"recordingProgress.getCount"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.propsDataSource = [NSMutableArray array];
    self.beautyLogic = [[NvBeautyLogic alloc] init];
    //初始化数据
    [self initData];
    //初始化播放器
    [self initPlayer];
    //初始化滤镜视图
    [self initFilterView];
    //请求权限
    [self checkAuth];
    [self prefersStatusBarHidden];
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    self.beautyView = [[NvDouyinBeautyView alloc] initWithFrame:CGRectZero];
    self.beautyView.delegate = self;
    [self.view addSubview:self.beautyView];
    [self.beautyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    self.beautyView.hidden = YES;
    self.countDownView = [[NvCountDownView alloc] initWithFrame:CGRectZero];
    self.countDownView.delegate = self;
    [self.view addSubview:self.countDownView];
    self.countDownView.hidden = YES;
    [self.countDownView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
    }];
    [self addPropsView];
}

- (void)initData {
    self.filterDataSource = [NSMutableArray array];
    self.assetManager = [NvAssetManager sharedInstance];
    [self.assetManager searchLocalAssets:ASSET_FILTER];
    NSString *itemPath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"filter"];
    [self.assetManager searchReservedAssets:ASSET_FILTER bundlePath:itemPath];
    musicPath = @"";
    self.isNoMusic = YES;
    recordingSpeed = 1;
    self.countDownTime = 15*NV_TIME_BASE;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"recordingProgress.getCount"]) {
        NSUInteger count = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        if (count == 0) {
            //如果录制的没有有数据
            captureView->deleteBtn.hidden = YES;
            captureView->nextBtn.hidden = YES;
            captureView.album.hidden = NO;
            captureView.selectMusic.userInteractionEnabled = YES;
            [captureView.selectMusic setTitleColor:[UIColor nv_colorWithHexRGB:@"#FFFFFF"] forState:UIControlStateNormal];
            [captureView.selectMusic setImage:[NvUtils imageWithName:@"NvSelectMusic"] forState:UIControlStateNormal];
        } else {
            //如果录制的有数据
            captureView->deleteBtn.hidden = NO;
            captureView->nextBtn.hidden = NO;
            captureView.album.hidden = YES;
            captureView.selectMusic.userInteractionEnabled = NO;
            if (musicPath == nil || [musicPath isEqualToString:@""]) {
                [captureView.selectMusic setTitleColor:[UIColor nv_colorWithHexRGB:@"#FFFFFF"] forState:UIControlStateNormal];
                [captureView.selectMusic setImage:[NvUtils imageWithName:@"NvSelectMusic"] forState:UIControlStateNormal];
            } else {
                [captureView.selectMusic setImage:[NvUtils imageWithName:@"NvMusicRecorded"] forState:UIControlStateNormal];
                [captureView.selectMusic setTitleColor:[UIColor nv_colorWithHexRGB:@"#F8E71C"] forState:UIControlStateNormal];
            }
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    streamingContext.delegate = self;
    if ([streamingContext getStreamingEngineState] != NvsStreamingEngineState_CapturePreview)
        [self startCapturePreview];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self updateFilters];
    if (!self.propsPanelView.hidden) {
        [self updateFaceStickers];
        [self.propsCollectionView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)checkAuth {
    __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];
    }
}

- (void)initPlayer {
    
    self.player = [NvAudioPlayer new];
    self.player.delegate = self;
    [self.player setUrlString:musicPath];
    self.trimOut = self.player.duration;
    
    [self.view addSubview:self.audioPlayerView];
    self.audioPlayerView.delegate = self;
    [self.audioPlayerView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            // Fallback on earlier versions
            make.top.equalTo(self.view.mas_bottom);
        }
        make.left.right.equalTo(@0);
        make.height.equalTo(@(74*SCREANSCALE));
    }];
    
    NvEditSelectMusicItem *item = NvEditSelectMusicItem.new;
    item.musicName = @"";
    item.musicPath = musicPath;
    item.duration = self.player.duration;
    [self.audioPlayerView renderViewWithItem:item];
    [self.audioPlayerView setLeftValue:0 rightValue:100];
    
}

- (void)initFilterView {
    self.filterView = [[NvCaptureFilterView alloc] initWithFrame:CGRectMake(0, SCREANHEIGHT, SCREANWIDTH, 173 * SCREANSCALE + INDICATOR)];
    self.filterView.delegate = self;
    [self.view addSubview:self.filterView];
//    [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(@0);
//        make.top.equalTo(self.view.mas_bottom).offset(40*SCREANSCALE);
//        make.height.equalTo(@(173 * SCREANSCALE + INDICATOR));
//    }];
    //MARK:初始化滤镜数据
    NSArray *videoFxArray = @[@"NvsFilterNone"];
    NSArray *videoFxDisplayArray = @[@"无"];
    for (int i = 0; i<videoFxArray.count; i++) {
        NvCaptureFilterModel *model = [[NvCaptureFilterModel alloc]init];
        model.selected = NO;
        model.displayName = videoFxDisplayArray[i];
        model.coverName = videoFxArray[i];
        [self.filterDataSource addObject:model];
    }
    [self updateFilters];
}

- (void)updateFilters {
    
    NSArray *array = [self.assetManager getUsableAssets:ASSET_FILTER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([self isFilterExist:asset.uuid]){
            continue;
        }
        if ([asset isReserved]) {
            NvCaptureFilterModel *filter = [[NvCaptureFilterModel alloc]init];
            [self initReservedAssetName:asset];
            filter.displayName = asset.name;
            filter.coverName = [asset.coverUrl absoluteString];
            filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
            filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
            filter.packageId = asset.uuid;
            [_filterDataSource insertObject:filter atIndex:1];
        }
    }
    for (NvAsset *asset in array) {
        if ([self isFilterExist:asset.uuid]){
            continue;
        }
        if (![asset isReserved]) {
            NvCaptureFilterModel *filter = [[NvCaptureFilterModel alloc]init];
            filter.displayName = asset.name;
            filter.coverName = [asset.coverUrl absoluteString];
            filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
            filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
            filter.packageId = asset.uuid;
            [_filterDataSource insertObject:filter atIndex:1];
        }
    }
    
    [self.filterView configDataSource:self.filterDataSource];
}

#pragma mark - NvCaptureFilterViewDelegate
- (void)NvCaptureFilterView:(NvCaptureFilterView *)view withModel:(NvCaptureFilterModel *)model{
    
    if (self.currentFilter) {
        [streamingContext removeCaptureVideoFx:self.currentFilter.index];
    }
    if (model.builtinName) {
        self.currentFilter = [streamingContext appendBuiltinCaptureVideoFx:model.builtinName];
    } else {
        self.currentFilter = [streamingContext appendPackagedCaptureVideoFx:model.packageId];
    }

}

- (void)NvCaptureFilterView:(NvCaptureFilterView *)view sliderValueChanged:(UISlider *)slider{
    [self.currentFilter setFilterIntensity:slider.value];
}

- (void)NvCaptureFilterView:(NvCaptureFilterView *)view moreClick:(UIButton *)sender{
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.type = ASSET_FILTER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)isFilterExist:(NSString *)uuid {
    for (NvCaptureFilterModel *item in _filterDataSource) {
        if ([item.packageId isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (void)initReservedAssetName:(NvAsset *)asset {
    if ([asset isReserved]) {
        if ([asset.uuid isEqualToString:@"0FBCC8A1-C16E-4FEB-BBDE-D04B91D98A40"]) {
            asset.name = @"白皙";
        }
        if ([asset.uuid isEqualToString:@"6439CF7E-42D5-4239-8187-358323292FF4"]) {
            asset.name = @"冰激凌";
        }
        if ([asset.uuid isEqualToString:@"FAE50247-F14C-40CE-AD43-29CA3E604838"]) {
            asset.name = @"晨曦";
        }
        if ([asset.uuid isEqualToString:@"BD9D5DA9-581E-4B80-95D4-218D95FC78F2"]) {
            asset.name = @"风语";
        }
        if ([asset.uuid isEqualToString:@"394EB525-1B7A-4AA1-BBAD-3FD75527A60C"]) {
            asset.name = @"过往";
        }
        if ([asset.uuid isEqualToString:@"12FCD2E7-1F80-4DFC-A8FD-C820CF754855"]) {
            asset.name = @"雷耶斯";
        }
        if ([asset.uuid isEqualToString:@"D65436B7-D19F-47E0-9A2A-28CECC73D4F2"]) {
            asset.name = @"蜜桃";
        }
        if ([asset.uuid isEqualToString:@"B7F1F498-B310-4E2D-9A75-7D8AFBBC71D8"]) {
            asset.name = @"切尔西";
        }
        if ([asset.uuid isEqualToString:@"C9CE10F1-7C77-423C-BB7F-7F090C33D5C5"]) {
            asset.name = @"青春";
        }
        if ([asset.uuid isEqualToString:@"F7204261-41D8-454A-99DC-3522444739EB"]) {
            asset.name = @"斋普尔";
        }
        if ([asset.uuid isEqualToString:@"E1202F90-F2C8-4A14-BFCB-8F62BBD72F56"]) {
            asset.name = @"筑地";
        }
    }
}

#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;
}

- (void)startupCapture {
    // 初始化SDK
    streamingContext = [NvSDKUtils getSDKContext];
    if (!streamingContext) {
        NSLog(@"初始化失败！");
        return;
    }
    
    // 设置回调接口
    streamingContext.delegate = self;
    
    // 检查可用采集设备的数量
    if ([streamingContext captureDeviceCount] == 0) {
        NSLog(@"没有可用于采集的设备！");
    }
    
    // 创建采集预览窗口并连接到摄像头采集次输出
    liveWindow = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:liveWindow];

    if (![streamingContext connectCapturePreviewWithLiveWindow:liveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }
    
    currentDeviceIndex = [self frontCameraDeviceIndex];
    if (![self startCapturePreview]) {
        NSLog(@"启动摄像头采集预览失败！");
    }
    
    captureView = [[NvDouyinCaptureView alloc] initWithFrame:SCREANBOUNDS];
    [self.view addSubview:captureView];
    captureView.delegate = self;
    [liveWindow addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLiveWindow:)]];
    //有录制视频时不能点击裁剪音乐
    [captureView addObserver:self forKeyPath:@"recordingProgress.getCount" options:NSKeyValueObservingOptionNew context:nil];
    captureView->deleteBtn.hidden = YES;
    captureView->nextBtn.hidden = YES;
    
    //开启美颜
    [self.beautyLogic startBeauty];
    [self.beautyLogic startFaceEffect];
    
    [self.beautyView setStrength:0.5 eyeEnlarging:0 cheekThinning:0];
}

- (void)tapLiveWindow:(UITapGestureRecognizer *)ges {
    if (!self.audioPlayerView.hidden) {
        [self hiddenPlayerViewAnimationFinish:^{
            NSLog(@"防止重复点击");
//            [self->captureView->cutMusicBtn setEnabled:YES];
        }];
        captureView.hidden = NO;
        [self.player pause];
        [self.player seekToTime:self.trimIn];
    }
    captureView.hidden = NO;
    //隐藏滤镜
    [UIView animateWithDuration:0.2 animations:^{
        self.filterView.frame = CGRectMake(0, SCREANHEIGHT, SCREANWIDTH, 173 * SCREANSCALE + INDICATOR);
    } completion:NULL];
    //隐藏美颜控制板
    if (self.beautyView.hidden == NO) {
        self.beautyView.hidden = YES;
    }
    //隐藏倒计时控制板
    if (self.countDownView.hidden == NO) {
        self.countDownView.hidden = YES;
    }
    if (!self.propsPanelView.hidden) {
        captureView.hidden = NO;
        [UIView animateWithDuration:0.1 animations:^{
            self.propsPanelView.frame = CGRectMake(0, SCREEN_HEIGTH+40*SCREANSCALE, SCREEN_WDITH, self.propsPanelView.height);
            self.propsPanelView.hidden = YES;
        }];
    }
}

#pragma mark NvDouyinBeautyViewDelegate

/**
 @param type type 0为磨皮，1为大眼，2为瘦脸
 */
- (void)slider:(int)type valueChanged:(float)value {
    if (type == 0) {
        self.beautyLogic.strength = value;
    } else if (type == 1) {
        self.beautyLogic.eyeEnlarging = value;
    } else if (type == 2) {
        self.beautyLogic.cheekThinning = value;
    }
}


#pragma mark 启动摄像头采集预览
- (BOOL)startCapturePreview {
    NSNumber *num = NV_UserInfo(@"NvRecordResolution");
    NvsVideoCaptureResolutionGrade captureResGrade = [num intValue] == 1080? NvsVideoCaptureResolutionGradeHigh:NvsVideoCaptureResolutionGradeMedium;
    if ([streamingContext isCaptureDeviceBackFacing:currentDeviceIndex]){
        captureResGrade = NvsVideoCaptureResolutionGradeMedium;
    }
    CGPoint point = CGPointMake(0.49*SCREANWIDTH, 0.49*SCREANHEIGHT);
    if (self.capability.supportAutoFocus) {
        [streamingContext startAutoFocus:point];
    }
    
    if (self.capability.supportAutoExposure) {
        [streamingContext startAutoExposure:point];
    }
    
    return [streamingContext startCapturePreview:currentDeviceIndex
                                   videoResGrade:captureResGrade
                                           flags:NvsStreamingEngineCaptureFlag_CaptureBuddyHostVideoFrame | NvsStreamingEngineCaptureFlag_StrictPreviewVideoSize
                                     aspectRatio:nil];
}

#pragma mark 选择音乐点击
- (void)selectMusicClick {
    NvSelectMusicViewController *selectMusic = NvSelectMusicViewController.new;
    selectMusic.delegate = self;
    selectMusic.hiddenTrimButton = YES;
    [selectMusic showCutHandleImage];
    NvBaseNavigationController *nav = [[NvBaseNavigationController alloc] initWithRootViewController:selectMusic];
    [self presentViewController:nav animated:YES completion:NULL];
}

#pragma mark 道具点击
- (void)propsBtnClicked {
#ifdef NV_AI_FU
    [self updateFaceStickers];
    captureView.hidden = YES;
    self.propsPanelView.hidden = NO;
    [_propsCollectionView reloadData];
    [self.view bringSubviewToFront:self.propsPanelView];
    [UIView animateWithDuration:0.1 animations:^{
        self.propsPanelView.frame = CGRectMake(0, SCREEN_HEIGTH - self.propsPanelView.height, SCREEN_WDITH, self.propsPanelView.height);
    }];
#else
    [self showTip];
#endif
}

- (void)showTip {
    if (!self.tipView) {
        self.tipView = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"提示" describeTitle:@"请移步官网，联系商务人员索要有人脸识别授权" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [self.tipView.clickBtn addTarget:self action:@selector(removeTip) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.tipView];
    }
}

- (void)removeTip {
    [self.tipView removeFromSuperview];
    self.tipView = 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 获取后置摄像头
- (unsigned int)backCameraDeviceIndex {
    for (unsigned int i = 0; i < streamingContext.captureDeviceCount; i++) {
        if ([streamingContext isCaptureDeviceBackFacing:i])
            return i;
    }
    return 0;
}

#pragma mark 添加道具视图
- (void)addPropsView{
    _propsPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 123*SCREANSCALE)];
    _propsPanelView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#99000000"];
    [self.view addSubview:_propsPanelView];
    
    UIButton *moreB = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreB setImage:[NvUtils imageWithName:@"NvsFilterMore"] forState:UIControlStateNormal];
    moreB.frame = CGRectMake(13 * SCREANSCALE, 30 * SCREANSCALE, 35 * SCREANSCALE, 25 * SCREANSCALE);
    [_propsPanelView addSubview:moreB];
    [moreB addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moreL = [[UILabel alloc]initWithFrame:CGRectMake(18 * SCREANSCALE, moreB.frame.origin.y + moreB.frame.size.height + 10, 30 * SCREANSCALE, 21 * SCREANSCALE)];
    moreL.text = @"更多";
    moreL.textColor = [UIColor nv_colorWithHexARGB:@"#CCFFFFFF"];
    moreL.font = [NvUtils regularFontWithSize:11];
    [_propsPanelView addSubview:moreL];
    
    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);
    _propsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(60 * SCREANSCALE, 25*SCREANSCALE, SCREEN_WDITH - 60 * SCREANSCALE, 70*SCREANSCALE) collectionViewLayout:layout];
    _propsCollectionView.delegate = self;
    _propsCollectionView.dataSource = self;
    _propsCollectionView.backgroundColor = [UIColor clearColor];
    _propsCollectionView.showsHorizontalScrollIndicator = NO;
    [_propsPanelView addSubview:_propsCollectionView];
    [_propsCollectionView registerClass:[NvFilterCell class] forCellWithReuseIdentifier:@"NvPropsCell"];
    
    [self.assetManager searchLocalAssets:ASSET_FACE1_STICKER];
    NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"face1sticker"];
    [self.assetManager searchReservedAssets:ASSET_FACE1_STICKER bundlePath:itemPath];
}

- (BOOL)isFaceStickerExist:(NSString *)uuid {
    for (NvFilterItem *item in _propsDataSource) {
        if ([item.package isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (void)updateFaceStickers {
    NSArray *array = [self.assetManager getUsableAssets:ASSET_FACE1_STICKER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([self isFaceStickerExist:asset.isReserved ? asset.bundledLocalDirPath : asset.localDirPath])
            continue;
        NvFilterItem *filter = NvFilterItem.new;
        filter.displayName = asset.name;
        filter.cover = [asset.coverUrl absoluteString];
        filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
        filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
        filter.package = asset.isReserved ? asset.bundledLocalDirPath : asset.localDirPath;
        if (asset.isReserved) {
            [_propsDataSource addObject:filter];
        } else {
            if (_propsDataSource.count > 0) {
                [_propsDataSource insertObject:filter atIndex:1];
            } else {
                [_propsDataSource insertObject:filter atIndex:0];
            }
        }
    }
    
    [self addNoneFaceSticker];
}

- (void)addNoneFaceSticker {
    for (NvFilterItem *item in _propsDataSource) {
        if ([item.cover isEqualToString:@"NvsFilterNone"])
            return;
    }
    NvFilterItem *item = [NvFilterItem new];
    item.builtinName = nil;
    item.package = nil;
    item.selected = NO;
    item.cover = @"NvsFilterNone";
    item.displayName = @"";
    [_propsDataSource insertObject:item atIndex:0];
    [_propsCollectionView reloadData];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _propsDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvFilterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvPropsCell" forIndexPath:indexPath];
    [cell renderCellWithItem:_propsDataSource[indexPath.item]];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    for (NvFilterItem *item in _propsDataSource) {
        item.selected = NO;
    }
    _currentPropsIndex = (unsigned int)indexPath.row;
    NvFilterItem *item = _propsDataSource[indexPath.row];
    item.selected = YES;
    [_propsCollectionView reloadData];
    if (indexPath.item != 0) {
        [self.beautyLogic.arfaceVideoFx setStringVal:@"Face Ornament" val:item.package];
    }else{
        [self.beautyLogic.arfaceVideoFx  setStringVal:@"Face Ornament" val:@""];
    }
}

#pragma mark 更多按钮点击
- (void)moreClick:(UIButton *)sender{
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.type = ASSET_FACE1_STICKER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 界面响应函数
- (void)countDownBtnClick {
    captureView.hidden = YES;
    self.countDownView.hidden = NO;
    float progress = [captureView->recordingProgress value]*1.0/TotalTime;
    self.countDownView.progress = progress;
    self.countDownView.currentValue = 1;
}

- (void)countDownView:(NvCountDownView *)countDownView didClickCountDownValue:(float)value {
    self.countDownTime = (int64_t)(15*NV_TIME_BASE * value);
    
    //隐藏倒计时控制板
    if (self.countDownView.hidden == NO) {
        self.countDownView.hidden = YES;
    }
    
    self.animationView = [[NvCountDownAnimationView alloc] initWithFrame:CGRectMake(30, 50, SCREANWIDTH - 2*30, SCREANHEIGHT - 2*50)];
    self.animationView.delegate = self;
    [self.view addSubview:self.animationView];
    [self.animationView startAnimation];
}

- (void)countDownAnimationStopAnimationView:(NvCountDownAnimationView *)countDownAnimationView {
    [self.animationView removeFromSuperview];
    self.animationView = nil;
    captureView.hidden = NO;
    [captureView hiddenAllButtonExceptRecordingButton];
    [captureView countDownStartRecording];
}

#pragma mark 对焦
- (void)focusOnPoint:(CGPoint)point {
    [streamingContext startAutoFocus:point];
}
#pragma mark 曝光
- (void)exposureOnPoint:(CGPoint)point {
    [streamingContext startAutoExposure:point];
}

#pragma mark 点击美颜
- (void)faceBtnClicked {
    [self.beautyLogic startBeauty];
    self.beautyView.hidden = NO;
    captureView.hidden = YES;
}

#pragma mark 点击切换摄像头
- (void)caremaButtonClicked {
    //前置摄像头
    if ([streamingContext isCaptureDeviceBackFacing:currentDeviceIndex]) {
        currentDeviceIndex = [self frontCameraDeviceIndex];
        [captureView->flashBtn setImage:[NvUtils imageWithName:@"Nvflash_off"] forState:UIControlStateNormal];
        [captureView->flashBtn setEnabled:NO];
    } else {//后置摄像头
        currentDeviceIndex = [self backCameraDeviceIndex];
        [captureView->flashBtn setImage:[NvUtils imageWithName:@"Nvflash_off"] forState:UIControlStateNormal];
        [captureView->flashBtn setEnabled:YES];
    }
    
    [self startCapturePreview];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self->_currentPropsIndex != 0) {
            NvFilterItem *item = self->_propsDataSource[self->_currentPropsIndex];
            [self.beautyLogic.arfaceVideoFx setStringVal:@"Face Ornament" val:item.package];
        }
    });
}
#pragma mark 点击返回
- (void)backButtonClicked {
    [streamingContext removeAllCaptureVideoFx];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [streamingContext stop];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 点击删除
- (void)deleteBtnClicked {
    NvRecordingInfo *info = [videoPathArray lastObject];
    float musicStartPos = info.musicStartPos;
    NSFileManager *fm = [NSFileManager defaultManager];
    [fm removeItemAtPath:info.recordingPath error:nil];
    [videoPathArray removeLastObject];
    NvRecordingInfo *infolast = [videoPathArray lastObject];
    if (infolast == nil) {
        [self.player seekToTime:musicStartPos];
    } else {
        [self.player seekToTime:infolast.musicEndPos];
    }
}
#pragma mark 点击下一步
- (void)nextBtnClicked {
    NSMutableArray *files = [NSMutableArray array];
    for (NvRecordingInfo *info in videoPathArray) {
        NvsAVFileInfo *fileInfo = [streamingContext getAVFileInfo:info.recordingPath];
        info.trimIn = 0;
        info.trimOut = fileInfo.duration;

        [files addObject:info.recordingPath];
    }
    NvDouyinEditViewController *vc = NvDouyinEditViewController.new;
    vc.videoPathArray = videoPathArray;
    if (self.isNoMusic) {
        vc.musicPath = nil;
    } else {
        vc.musicPath = musicPath;
        vc.trimIn = self.trimIn*NV_TIME_BASE;
        vc.trimOut = self.trimOut*NV_TIME_BASE;
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark 点击相册
- (void)albumClick {
    NvAlbumViewController *album = [[NvAlbumViewController alloc] init];
    album.mutableSelect = NO;
    album.isOnlyVideo = YES;
    album.delegate = self;
    [self.navigationController pushViewController:album animated:YES];
}

#pragma mark 点击滤镜
- (void)filterBtnClicked {
    captureView.hidden = YES;
    [self.view bringSubviewToFront:self.filterView];
    [UIView animateWithDuration:0.2 animations:^{
        self.filterView.frame = CGRectMake(0, SCREEN_HEIGTH - self.filterView.frame.size.height, SCREEN_WDITH, self.filterView.frame.size.height);
    } completion:NULL];
}

- (void)filterView:(NvDouyinFilter *)filterView selectFilter:(NvFilterItem *)item {
    if (self.currentFilter) {
        [streamingContext removeCaptureVideoFx:self.currentFilter.index];
    }
    if (item.builtinName) {
        self.currentFilter = [streamingContext appendBuiltinCaptureVideoFx:item.builtinName];
    } else {
        self.currentFilter = [streamingContext appendPackagedCaptureVideoFx:item.package];
    }
}

- (void)filterViewMoreClick:(NvDouyinFilter *)filterView {
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.type = ASSET_FILTER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 点击闪光灯
- (void)flashBtnClicked {
    if ([streamingContext isFlashOn]) {
        [streamingContext toggleFlash:NO];
        [captureView->flashBtn setImage:[NvUtils imageWithName:@"Nvflash_off"] forState:UIControlStateNormal];
    } else {
        [streamingContext toggleFlash:YES];
        [captureView->flashBtn setImage:[NvUtils imageWithName:@"Nvflash_on"] forState:UIControlStateNormal];
    }
}

#pragma mark 选择速率
- (void)douyinCaptureView:(NvDouyinCaptureView *)douyinCaptureView selectSpeed:(float)speed {
    recordingSpeed = speed;
}

#pragma mark 选择相册回调
- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    PHAsset *asset = assets.firstObject.asset;
    PHImageRequestOptions *option = [PHImageRequestOptions new];
    option.synchronous = YES;
    __weak typeof(self)weakSelf = self;
    __block BOOL isIClould = NO;
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset
                                                    options:options
                                              resultHandler:^(AVAsset * avAsset, AVAudioMix * audioMix, NSDictionary * info) {
                                                  if (avAsset && [avAsset isKindOfClass:[AVURLAsset class]]) {
                                                      dispatch_semaphore_signal(semaphore);
                                                  } else {
                                                      weakSelf.tipView = [[NvTipsView alloc]initWithFrame:weakSelf.view.bounds withPrompt:@"提示" describeTitle:@"选择视频再iCloud中" describeContent:nil buttonText:@"知道了" withCenter:YES];
                                                      [weakSelf.tipView.clickBtn addTarget:weakSelf action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
                                                      [albumViewController.view addSubview:weakSelf.tipView];
                                                      isIClould = YES;
                                                      dispatch_semaphore_signal(semaphore);
                                                  }
                                                  
                                              }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    if (isIClould) {
        return;
    }
    NSTimeInterval time = asset.duration;
    if (time < 3.0) {
        self.tipView = [[NvTipsView alloc]initWithFrame:self.view.bounds withPrompt:@"提示" describeTitle:@"请选择长于3秒的视频" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [self.tipView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
        [albumViewController.view addSubview:self.tipView];
        return;
    }
    
    NvTrimVideoViewController *vc = NvTrimVideoViewController.new;
    NvsTimeline *timeline = [NvTimelineUtils createTimeline:NvEditMode9v16];
    NvsVideoTrack *videoTrack = [timeline getVideoTrackByIndex:0];
    [videoTrack appendClip:assets.firstObject.asset.localIdentifier];
    
    if (self.isNoMusic) {
        vc.musicPath = @"";
    } else {
        vc.musicPath = musicPath;
        vc.musicTrimIn = self.trimIn*NV_TIME_BASE;
        vc.musicTrimOut = self.trimOut*NV_TIME_BASE;
    }
    NvRecordingInfo *info = [NvRecordingInfo new];
    info.asset = assets.firstObject.asset;
    vc.timeline = timeline;
    vc.editMode = NvEditMode9v16;
    vc.info = info;
    vc.isNoMusic = self.isNoMusic;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)knowClick:(NvTipsView *)tipView {
    [self.tipView removeFromSuperview];
}

#pragma mark 选音乐的回调
- (void)selectMusicViewController:(NvSelectMusicViewController *)selectMusicViewController withItem:(NvEditSelectMusicItem *)item trimIn:(float)trimIn trimOut:(float)trimOut {
    if (item.duration<15.0) {
        self.tipView = [[NvTipsView alloc]initWithFrame:self.view.bounds withPrompt:@"提示" describeTitle:@"音乐选择不能小于15秒" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [self.tipView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
        [selectMusicViewController.view addSubview:self.tipView];
        return;
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
    
    self.isNoMusic = NO;
    musicPath = item.musicPath;
    
    [self.player setUrlString:musicPath];
    [self.player seekToTime:trimIn];
    self.trimIn = trimIn;
    self.trimOut = trimOut;
    [captureView.selectMusic setTitle:item.musicName forState:UIControlStateNormal];
}

- (void)selectNoneMusic {
    [self dismissViewControllerAnimated:YES completion:NULL];
    self.isNoMusic = YES;
    [captureView.selectMusic setTitle:@"选音乐" forState:UIControlStateNormal];
}

#pragma mark 播放音乐回调
- (void)nvAudioPlayer:(NvAudioPlayer *)player currentTime:(double)currentTime {
    self.audioPlayerView.currentValue = currentTime;
}

#pragma mark 裁剪音乐回调
- (void)audioPlayerView:(NvAudioPlayerView *)audioPlayerView leftValueChanged:(float)value {
    [self.player seekToTime:value];
    self.trimIn = value;
    [self.player play];
    
    NSLog(@"trimIn:%f",value);
}

- (void)nvAudioPlayerPlayEOF:(NvAudioPlayer *)player {
    [player seekToTime:self.trimIn];
    [player play];
}

- (void)audioPlayerView:(NvAudioPlayerView *)audioPlayerView rightValueChanged:(float)value {
    self.trimOut = value;
    NSLog(@"trimOut:%f",value);
}

- (void)audioPlayerViewNoMusicClick:(NvAudioPlayerView *)audioPlayerView {
    [self hiddenPlayerViewAnimationFinish:^{
        NSLog(@"防止重复点击");
//        [self->captureView->cutMusicBtn setEnabled:YES];
    }];
    captureView.hidden = NO;
    self.trimOut = self.player.duration;
    self.trimIn = 0;
    [self.player seekToTime:0];
    self.isNoMusic = YES;
    [self.player pause];
}

- (void)startRecord {
    [self startRecording];
    [captureView hiddenAllButtonExceptRecordingButton];
    if (!self.isNoMusic) {
        float rate = 1;
        if (recordingSpeed == 0.5) {
            rate = 2;
        } else if (recordingSpeed == 0.75) {
            rate = 1.5;
        } else if (recordingSpeed == 1) {
            rate = 1;
        } else if (recordingSpeed == 1.5) {
            rate = 0.75;
        } else if (recordingSpeed == 2) {
            rate = 0.5;
        }
        [self.player rate:rate];
//        [player play];
    }
}

- (void)endRecord {
    [self stopRecording];
    [self.player pause];
    [captureView showAllButton];
}
#pragma mark 开始录制
- (void)startRecording{
    if (!videoPathArray) {
        videoPathArray = NSMutableArray.new;
    }
    NSString *path = [VIDEO_PATH(@"Record") stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [NvUtils currentDateAndTime]]];
    NSMutableDictionary *config = [[NSMutableDictionary alloc] init];
    [streamingContext startRecordingWithFx:path withFlags:0 withRecordConfigurations:config];
    NvRecordingInfo *info = [NvRecordingInfo new];
    info.recordingPath = path;
    info.musicStartPos = self.player.currentTime;
    info.speed = recordingSpeed;
    [videoPathArray addObject:info];
}
#pragma mark 停止录制
- (void)stopRecording{
    [streamingContext stopRecording];
    self.countDownTime = 15*NV_TIME_BASE;
    NvRecordingInfo *info = [videoPathArray lastObject];
    info.musicEndPos = self.player.currentTime;
}

- (void)didCaptureRecordingDurationUpdated:(int)captureDeviceIndex duration:(int64_t)duration {
    if (duration > NV_TIME_BASE/2) {
        [captureView enableRecordingButton];
    }
    [captureView updateCaptureClipDuration: duration];
    if ([captureView->recordingProgress value] >= self.countDownTime) {
        [captureView recordingEnd];
        //录制大于等于15秒倒计时按钮禁止点击
        if ([captureView->recordingProgress value] >= 15000000) {
            captureView.countDownBtn.enabled = NO;
        }
    }
}

- (void)didCaptureDeviceCapsReady:(unsigned int)captureDeviceIndex {
    // 获取采集设备的能力描述
    self.capability = [[NvSDKUtils getSDKContext] getCaptureDeviceCapability:captureDeviceIndex];
    
    CGPoint point = CGPointMake(0.49*liveWindow.width, 0.49*liveWindow.height);
    if (self.capability.supportAutoFocus) {
        [[NvSDKUtils getSDKContext] startAutoFocus:point];
    }
    if (self.capability.supportAutoExposure) {  // 支持自动曝光则自动曝光
        [[NvSDKUtils getSDKContext] startAutoExposure:point];
    }
}

- (BOOL)supportAutoFocus {
    return self.capability.supportAutoFocus;
}

- (BOOL)supportAutoExposure {
    return self.capability.supportAutoExposure;
}

- (void)didCaptureRecordingFinished:(unsigned int)captureDeviceIndex {
}

- (void)setupEditData {
    [[[NvTimelineData sharedInstance] editDataArray] removeAllObjects];
    for (NvRecordingInfo *info in videoPathArray) {
        NvEditDataModel *clipData = NvEditDataModel.new;
        clipData.videoPath = info.recordingPath;
        clipData.trimIn = 0;
        clipData.trimOut = [NvSDKUtils getVideoDuration:info.recordingPath];
        clipData.duration = [NvSDKUtils getVideoDuration:info.recordingPath];
        [[[NvTimelineData sharedInstance] editDataArray] addObject:clipData];
    }
}

- (void)knowClick {
    [permissions removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)applicationWillResignActive:(NSNotification*)notification {
}

- (void)applicationDidBecomeActive:(NSNotification*)notification {
    if ([streamingContext getStreamingEngineState] != NvsStreamingEngineState_CapturePreview)
        [self startCapturePreview];
}
//MARK:隐藏音乐控件
- (void)showPlayerViewAnimationFinish:(void(^)(void))block {
    [self.audioPlayerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            // Fallback on earlier versions
            make.bottom.equalTo(self.view.mas_bottom);
        }
        make.left.right.equalTo(@0);
        make.height.equalTo(@(74*SCREANSCALE));
    }];
    self.audioPlayerView.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        block();
    }];
}
//MARK:显示音乐控件
- (void)hiddenPlayerViewAnimationFinish:(void(^)(void))block {
    [self.audioPlayerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            // Fallback on earlier versions
            make.top.equalTo(self.view.mas_bottom);
        }
        make.left.right.equalTo(@0);
        make.height.equalTo(@(74*SCREANSCALE));
    }];
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        block();
        self.audioPlayerView.hidden = YES;
    }];
}

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

// MARK: Getter
-(NvAudioPlayerView *)audioPlayerView {
    if (!_audioPlayerView) {
        _audioPlayerView = [NvAudioPlayerView new];
        _audioPlayerView.isCaptureModel = YES;
        _audioPlayerView.nameLabel.textColor = [UIColor whiteColor];
        _audioPlayerView.currentLabel.textColor = [UIColor whiteColor];
    }
    return _audioPlayerView;
}
//是否需要使用gopsize
//- (BOOL)isIsNeedGopSize {
//    NSString *phoneType = [NvUtils iphoneType];
//    NSSet *set = [NSSet setWithObjects:@"iPhone 4S",@"iPhone 5",@"iPhone 5s",@"iPhone 6 Plus",@"iPhone 6", nil];
//    return [set containsObject:phoneType];
//}

@end
