//
//  ViewController.m
//  SDKDemo
//
//  Created by Meicam on 2018/5/24.
//  Copyright © 2018年 刘东旭. All rights reserved.
//

#import "ViewController.h"
#import "NvSetUpViewController.h"
#import "NvCaptureViewController.h"
#import "NvEditViewController.h"
#import "NvEditMaterialViewController.h"
#import "NvCustomStickerShapeViewController.h"
#import "NvTipsView.h"
#import "NvDouyinCaptureViewController.h"
#import "NvAlbumViewController.h"
#import "NvSizeViewController.h"
#import "NvParCaptureViewController.h"
#import "NvAssetManager.h"
#import "NvVKeyerViewController.h"
#import "NvPIPEditViewController.h"
#import "NvSDKUtils.h"
#import "NvHomeCViewCell.h"
#import "NvFeedbackViewController.h"

typedef enum : NSUInteger {
    NvEdit,
    NvPIPEdit,
} AlbumMode;

@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) NvAssetManager *assetManager;
//反馈按钮
@property (nonatomic, strong) UIButton *feedbackBtn;
//设置按钮
@property (nonatomic, strong) UIButton *setUpBtn;
//视频拍摄按钮
@property (nonatomic, strong) UIButton *shootingBtn;
//视频编辑按钮
@property (nonatomic, strong) UIButton *editorBtn;

@property (nonatomic, assign) AlbumMode model;//标明选择的模块

//scrollView视图数据，存放的是NvHomeArrayModel，结构：一个CollectionView，一个数组NvHomeModel
@property (nonatomic, strong) NSMutableArray *dataSource;
//滚动视图，每一页放一个CollectionView
@property (nonatomic, strong) UIScrollView *scrollView;
//当前页面对应的model
@property (nonatomic, strong) NvHomeArrayModel *currentModel;
//显示的小点点
@property (nonatomic, strong) UIPageControl *pageControl;

//自定义相册底部按钮
@property (nonatomic, weak) UIButton *custumButton;

@property (nonatomic, weak) NvAlbumViewController *albumViewController;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSNumber *num = NV_UserInfo(@"NvRecordResolution");
    if (num==nil) {
        [[NSUserDefaults standardUserDefaults] setValue:@720 forKey:@"NvRecordResolution"];
        [[NSUserDefaults standardUserDefaults] setValue:@720 forKey:@"NvCompileResolution"];
        [[NSUserDefaults standardUserDefaults] setValue:@0 forKey:@"NvBackgroudBlurFilled"];
        [[NSUserDefaults standardUserDefaults] setValue:@(7 * NV_TIME_BASE) forKey:@"NvCompileBitrate"];
    }
    [self addSubViews];
    [self configDataSource];
    [self installPackage];
    [self installPIPPackage];
    [self installParticlePackage];
    NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sticker/custom"];
    [self.assetManager searchReservedAssets:ASSET_CUSTOM_ANIMATED_STICKER bundlePath:itemPath];
    //创建目录，清除一些资源
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *pathArray = @[VIDEO_PATH(@"Recordmp3"),VIDEO_PATH(@"Record"),VIDEO_PATH(@"Particle"),VIDEO_PATH(@"Virtual"),WATEMARK_PATH,CONVERTPATH];
    for (NSString *path in pathArray) {
        if (![fm fileExistsAtPath:path]) {
            [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        } else {
            [fm removeItemAtPath:path error:nil];
            [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
    }
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
//为抖音demo安装package
- (void)installPackage {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([[userDefault objectForKey:@"douyinInstall"] boolValue]) {
        return;
    }
    BOOL isInstall = YES;
    NSString *packagePath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"douyinPackage"];
    NSString *jsonPath = [packagePath stringByAppendingPathComponent:@"fx.json"];
    NSString *jsontext = [NSString stringWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
    NSData *data =[jsontext dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    for (int i = 0; i < array.count-1; i++) {
        NSDictionary *dic = array[i];
        NSString *path = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",dic[@"fxFileName"]]];
        NSString *license;
        if (i == array.count - 1) {
            license = @"";
        }else{
            license = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",dic[@"fxLicFileName"]]];
        }
        NvsAssetPackageManagerError error = [[NvSDKUtils getSDKContext].assetPackageManager installAssetPackage:path license:license type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:[NSMutableString string]];
        if (error == NvsAssetPackageManagerError_NoError || error == NvsAssetPackageManagerError_AlreadyInstalled || error == NvsAssetPackageManagerError_WorkingInProgress) {
            NSLog(@"%@安装成功！",dic[@"fxid"]);
        } else {
            NSLog(@"%@安装失败！",dic[@"fxid"]);
            isInstall = NO;
        }
    }
    
    [userDefault setObject:@(isInstall) forKey:@"douyinInstall"];
}

#pragma mark 为画中画安装package
- (void)installPIPPackage {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([[userDefault objectForKey:@"PIPInstall"] boolValue]) {
        return;
    }
    BOOL isInstall = YES;

    NSString *packagePath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"PIPPackage"];
    NSString *jsonPath = [packagePath stringByAppendingPathComponent:@"pipFileInfo.json"];
    NSString *jsontext = [NSString stringWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
    NSData *data =[jsontext dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *path = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",dic[@"fileDirName"],dic[@"pipPackageName1"]]];
        NSString *path1 = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",dic[@"fileDirName"],dic[@"pipPackageName2"]]];
        //            NSString *license;
        
        //            license = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",dic[@"fxLicFileName"]]];
        
        NvsAssetPackageManagerError error = [[NvSDKUtils getSDKContext].assetPackageManager installAssetPackage:path license:nil type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:[NSMutableString string]];
        if (error == NvsAssetPackageManagerError_NoError || error == NvsAssetPackageManagerError_AlreadyInstalled || error == NvsAssetPackageManagerError_WorkingInProgress) {
            NSLog(@"pipPackage1：%@安装成功！",dic[@"pipPackage1"]);
        } else {
            NSLog(@"%@安装失败！",dic[@"pipPackage1"]);
            isInstall = NO;
        }
        
        NvsAssetPackageManagerError error1 = [[NvSDKUtils getSDKContext].assetPackageManager installAssetPackage:path1 license:nil type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:[NSMutableString string]];
        if (error1 == NvsAssetPackageManagerError_NoError || error1 == NvsAssetPackageManagerError_AlreadyInstalled || error1 == NvsAssetPackageManagerError_WorkingInProgress) {
            NSLog(@"pipPackage2：%@安装成功！",dic[@"pipPackage2"]);
        } else {
            NSLog(@"%@安装失败！",dic[@"pipPackage2"]);
            isInstall = NO;
        }
    }
    //安装沙盒package
    NSString *jsonPath2 = [PIPPACKAGE_PATH stringByAppendingPathComponent:@"pipFileInfo.json"];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:PIPPACKAGE_PATH]) {
        [fm createDirectoryAtPath:PIPPACKAGE_PATH withIntermediateDirectories:YES attributes:nil error:nil];
        [fm copyItemAtPath:jsonPath toPath:jsonPath2 error:nil];
        NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:jsonPath2];
        [fh truncateFileAtOffset:0];
        [fh writeData:[@"[]" dataUsingEncoding:NSUTF8StringEncoding]];
        [fh closeFile];
    }
    
    NSString *jsontext2 = [NSString stringWithContentsOfFile:jsonPath2 encoding:NSUTF8StringEncoding error:nil];
    NSData *data2 =[jsontext2 dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array2 =[NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
    for (int i = 0; i < array2.count; i++) {
        NSDictionary *dic = array2[i];
        NSString *path = [PIPPACKAGE_PATH stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",dic[@"fileDirName"],dic[@"pipPackageName1"]]];
        NSString *path1 = [PIPPACKAGE_PATH stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",dic[@"fileDirName"],dic[@"pipPackageName2"]]];
        //            NSString *license;
        
        //            license = [packagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",dic[@"fxLicFileName"]]];
        
        NvsAssetPackageManagerError error = [[NvSDKUtils getSDKContext].assetPackageManager installAssetPackage:path license:nil type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:[NSMutableString string]];
        if (error == NvsAssetPackageManagerError_NoError || error == NvsAssetPackageManagerError_AlreadyInstalled || error == NvsAssetPackageManagerError_WorkingInProgress) {
            NSLog(@"pipPackage1：%@安装成功！",dic[@"pipPackage1"]);
        } else {
            NSLog(@"%@安装失败！",dic[@"pipPackage1"]);
            isInstall = NO;
        }
        
        NvsAssetPackageManagerError error1 = [[NvSDKUtils getSDKContext].assetPackageManager installAssetPackage:path1 license:nil type:NvsAssetPackageType_VideoFx sync:YES assetPackageId:[NSMutableString string]];
        if (error1 == NvsAssetPackageManagerError_NoError || error1 == NvsAssetPackageManagerError_AlreadyInstalled || error1 == NvsAssetPackageManagerError_WorkingInProgress) {
            NSLog(@"pipPackage2：%@安装成功！",dic[@"pipPackage2"]);
        } else {
            NSLog(@"%@安装失败！",dic[@"pipPackage2"]);
            isInstall = NO;
        }
    }
    
    [userDefault setObject:@(isInstall) forKey:@"PIPInstall"];
}

#pragma mark 为粒子demo安装package
- (void)installParticlePackage {
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
        self.assetManager = [NvAssetManager sharedInstance];
        NSString *packagePath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"ParticlePackage"];
        [self.assetManager searchReservedAssets:ASSET_PARTICLE bundlePath:packagePath];
//    });
}

#pragma mark 敬请期待提示视图
- (void)tipView{
   NvTipsView *tipView = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"提示" describeTitle:@"敬请期待！" describeContent:@"可移步官网联系商务人员" buttonText:@"知道了" withCenter:YES];
    [tipView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tipView];
}

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

#pragma mark 添加子视图
- (void)addSubViews{
    
    UIImageView *bgImageView = [[UIImageView alloc]init];
    bgImageView.image = [NvUtils imageWithName:@"NvHomeBg.jpg"];
    bgImageView.userInteractionEnabled = YES;
    
    self.feedbackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.feedbackBtn setImage:[NvUtils imageWithName:@"NvHomeFeedback"] forState:UIControlStateNormal];
    [self.feedbackBtn addTarget:self action:@selector(feedbackBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.setUpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.setUpBtn setImage:[NvUtils imageWithName:@"NvSetting"] forState:UIControlStateNormal];
    [self.setUpBtn addTarget:self action:@selector(btnClickevent:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.image = [NvUtils imageWithName:@"NvHomeBgLogo"];
    logoImageView.contentMode = UIViewContentModeScaleAspectFit;
    
    [self.view addSubview:bgImageView];
    [self.view addSubview:self.setUpBtn];
    [self.view addSubview:self.feedbackBtn];
    [self.view addSubview:logoImageView];
    
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(34 * SCREANSCALE + NV_STATUSBARHEIGHT);
        make.left.equalTo(self.view.mas_left).offset(13 * SCREANSCALE);
        make.width.offset(105 * SCREANSCALE);
        make.height.offset(44 * SCREANSCALE);
    }];
    
    [self.setUpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(NV_STATUSBARHEIGHT + 13 * SCREANSCALE);
        make.right.equalTo(self.view.mas_right).offset(-13 * SCREANSCALE);
    }];
    
    [self.feedbackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.setUpBtn.mas_centerY);
        make.right.equalTo(self.setUpBtn.mas_left).offset(-20 * SCREANSCALE);
    }];
    
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(310 * SCREANSCALE);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.offset(110 * SCREANSCALE);
    }];
    
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.currentPageIndicatorTintColor = [UIColor nv_colorWithHexRGB:@"#50E3C2"];
    self.pageControl.pageIndicatorTintColor = [UIColor nv_colorWithHexARGB:@"#80FFFFFF"];
    self.pageControl.hidesForSinglePage = YES;
    [self.view addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom).offset(10 * SCREANSCALE);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.offset(20 * SCREANSCALE);
        make.height.offset(10 * SCREANSCALE);
    }];
    
    self.shootingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shootingBtn addTarget:self action:@selector(shootingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shootingBtn];
    [self.shootingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom).offset(50 * SCREANSCALE);
        make.left.equalTo(self.view.mas_left).offset(13 * SCREANSCALE);
        make.width.offset(170 * SCREANSCALE);
        make.height.offset(114 * SCREANSCALE);
    }];
    
    self.editorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.editorBtn addTarget:self action:@selector(editorBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.editorBtn];
    [self.editorBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom).offset(50 * SCREANSCALE);
        make.right.equalTo(self.view.mas_right).offset(-13 * SCREANSCALE);
        make.width.offset(170 * SCREANSCALE);
        make.height.offset(114 * SCREANSCALE);
    }];
    
    [self.view layoutIfNeeded];
    
    [self gradientView:self.shootingBtn withColors:@[(id)[UIColor nv_colorWithHexRGB:@"#00C9C9"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#009999"].CGColor]];
    [self gradientView:self.editorBtn withColors:@[(id)[UIColor nv_colorWithHexRGB:@"#00E8C9"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#00CC99"].CGColor]];
    
    UIImageView *shootingImage = [[UIImageView alloc]init];
    shootingImage.image = [NvUtils imageWithName:@"NvHomeCapture"];
    shootingImage.contentMode = UIViewContentModeScaleAspectFit;
    [self.shootingBtn addSubview:shootingImage];
    [shootingImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shootingBtn.mas_top).offset(30 * SCREANSCALE);
        make.centerX.equalTo(self.shootingBtn.mas_centerX);
        make.width.offset(30 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    
    UILabel *shootingLabel = [[UILabel alloc]init];
    shootingLabel.text = @"视频拍摄";
    shootingLabel.textColor = UIColor.whiteColor;
    shootingLabel.font = [NvUtils regularFontWithSize:15];
    [self.shootingBtn addSubview:shootingLabel];
    [shootingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(shootingImage.mas_bottom).offset(5 * SCREANSCALE);
        make.centerX.equalTo(self.shootingBtn.mas_centerX);
    }];
    
    UIImageView *editImage = [[UIImageView alloc]init];
    editImage.image = [NvUtils imageWithName:@"NvHomeEdit"];
    editImage.contentMode = UIViewContentModeScaleAspectFit;
    [self.editorBtn addSubview:editImage];
    [editImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.editorBtn.mas_top).offset(30 * SCREANSCALE);
        make.centerX.equalTo(self.editorBtn.mas_centerX);
        make.width.offset(30 * SCREANSCALE);
        make.height.offset(30 * SCREANSCALE);
    }];
    
    UILabel *editLabel = [[UILabel alloc]init];
    editLabel.text = @"视频编辑";
    editLabel.textColor = UIColor.whiteColor;
    editLabel.font = [NvUtils regularFontWithSize:15];
    [self.editorBtn addSubview:editLabel];
    [editLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(editImage.mas_bottom).offset(5 * SCREANSCALE);
        make.centerX.equalTo(self.editorBtn.mas_centerX);
    }];
    
    int large,minor,revision;
    [NvsStreamingContext getSdkVersion:&large minorVersion:&minor revisionNumber:&revision];
    UILabel *sdkLabel = [[UILabel alloc]init];
    sdkLabel.textColor = [UIColor nv_colorWithHexARGB:@"#CCFFFFFF"];
    sdkLabel.font = [NvUtils regularFontWithSize:12];
    sdkLabel.text = [NSString stringWithFormat:@"V %d.%d.%d",large,minor,revision];
    [self.view addSubview:sdkLabel];
    [sdkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-34 * SCREANSCALE);
    }];
}

#pragma mark feedbackBtnClick——反馈按钮点击
- (void)feedbackBtnClick:(UIButton *)sender{
    [self addTipsViewString:@"功能待开放"];
//    NvFeedbackViewController *vc = [[NvFeedbackViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark shootingBtnClick——视频拍摄按钮点击
- (void)shootingBtnClick:(UIButton *)sender{
    NvCaptureViewController *vc = [[NvCaptureViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark editorBtnClick——视频编辑按钮点击
- (void)editorBtnClick:(UIButton *)sender{
    NvAlbumViewController *vc = [NvAlbumViewController new];
    vc.delegate = self;
    self.model = NvEdit;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 提示视图
- (void)addTipsViewString:(NSString *)text{
    NvTipsView *tip = [[NvTipsView alloc]initWithFrame:self.view.frame withTitle:text withColor:[UIColor nv_colorWithHexRGB:@"#4D4F51"] withCenter:YES];
    [self.view addSubview:tip];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tip removeFromSuperview];
    });
}
#pragma mark 给拍摄、编辑配置颜色渐变效果
- (void)gradientView:(UIButton *)sender withColors:(NSArray *)colors{
    //创建CAGradientLayer 对象
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    //设置CAGradientLayer 对象的位置大小和承接视图等同
    gradientLayer.frame = CGRectMake(0, 0, sender.frame.size.width, sender.frame.size.height);
    //设置渐变色(即颜色数组)
    gradientLayer.colors = colors;
    //变化位置或变化点
    gradientLayer.locations = @[@(0.0f),@(1.0f)];
    //渐变方向
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1);
    gradientLayer.masksToBounds = YES;
    gradientLayer.cornerRadius = 10 * SCREANSCALE;
    //添加
    [sender.layer addSublayer:gradientLayer];
}

#pragma mark 配置数据
- (void)configDataSource{
    self.dataSource = [NSMutableArray array];
    NSArray *nameArray = @[@[@"抖音特效", @"粒子特效", @"背景抠像", @"画中画"]];
    NSArray *coverArray = @[@[@"NvHomeDuanShiPin", @"NvHomeParticle", @"NvHomeVirtualKeyer", @"NvHomePIP"]];
//    NSArray *nameArray = @[@[@"抖音特效", @"粒子特效", @"背景抠像", @"画中画"], @[@"翻转字幕", @"音乐歌词", @"推镜拍摄", @"Boomrang"]];
//    NSArray *coverArray = @[@[@"NvHomeDuanShiPin", @"NvHomeParticle", @"NvHomeVirtualKeyer", @"NvHomePIP"], @[@"NvHomeFlipSubtitles", @"NvHomeMusicLyrics", @"NvHomePhotoWall", @"NvHomeBoomrang"]];
    NSArray *colorArray = @[@[(id)[UIColor nv_colorWithHexRGB:@"#B885E7"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#824ECA"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#67FAAC"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#06D592"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#00BBBB"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#008686"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#7C89B7"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#465181"].CGColor]];
    NSArray *colorArray_1 = @[@[(id)[UIColor nv_colorWithHexRGB:@"#67FAAC"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#06D592"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#00BBBB"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#008686"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#B885E7"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#824ECA"].CGColor], @[(id)[UIColor nv_colorWithHexRGB:@"#7C89B7"].CGColor, (id)[UIColor nv_colorWithHexRGB:@"#465181"].CGColor]];
    
    self.scrollView.contentSize = CGSizeMake(nameArray.count * SCREANWIDTH, 110 * SCREANSCALE);
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = nameArray.count;
    
    //给scrollView配置视图，和数据
    for (int i = 0; i < nameArray.count; i++) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(77*SCREANSCALE, 110*SCREANSCALE);
        layout.minimumLineSpacing = 13*SCREANSCALE;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 13*SCREANSCALE, 0, 0);
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(i * SCREANWIDTH, 0, SCREANWIDTH, 110 * SCREANSCALE) collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.showsHorizontalScrollIndicator = NO; // 去掉滚动条
        [collectionView registerClass:[NvHomeCViewCell class] forCellWithReuseIdentifier:@"NvHomeCViewCell"];
        [self.scrollView addSubview:collectionView];
        
        NvHomeArrayModel *model = [NvHomeArrayModel new];
        model.array = [NSMutableArray array];
        model.collectionView = collectionView;
        NSArray *temporary = nameArray[i];
        NSArray *temporary1 = coverArray[i];
        for (int j = 0; j < temporary.count; j++) {
            NvHomeModel *model_1 = [NvHomeModel new];
            model_1.name = temporary[j];
            model_1.cover = temporary1[j];
            if (i == 0) {
                model_1.color = colorArray[j];
            }else{
                model_1.color = colorArray_1[j];
            }
            [model.array addObject:model_1];
        }
        
        if (i == 0) {
            self.currentModel = model;
        }
        [self.dataSource addObject:model];
        [collectionView reloadData];
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    for (NvHomeArrayModel *model in self.dataSource) {
        if ([model.collectionView isEqual:collectionView]) {
            return model.array.count;
        }
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    for (NvHomeArrayModel *model in self.dataSource) {
        if ([model.collectionView isEqual:collectionView]) {
            NvHomeCViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvHomeCViewCell" forIndexPath:indexPath];
            [cell renderCellWithItem:model.array[indexPath.item]];
            return cell;
        }
    }
    return [UICollectionViewCell new];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NvHomeModel *model = self.currentModel.array[indexPath.item];
    UIViewController *vc;
    if ([model.name isEqualToString:@"抖音特效"]) {
        vc = [NvDouyinCaptureViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.name isEqualToString:@"粒子特效"]){
        vc = [NvParCaptureViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.name isEqualToString:@"背景抠像"]){
        vc = [NvVKeyerViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.name isEqualToString:@"画中画"]){
        vc = [NvAlbumViewController new];
        NvAlbumViewController *albumVC = (NvAlbumViewController *)vc;
        albumVC.delegate = self;
        albumVC.mutableSelect = YES;
        albumVC.minSelectCount = 2;
        albumVC.maxSelectCount = 2;
        albumVC.hiddenSelectAll = YES;
        albumVC.alwaysShowCustomBottom = YES;
        vc = albumVC;
        self.albumViewController = albumVC;
//        [albumVC customSelectAssetButtonText:@"选择2个素材进行制作"];
        self.model = NvPIPEdit;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([model.name isEqualToString:@"翻转字幕"]){
        [self tipView];
    }else if ([model.name isEqualToString:@"音乐歌词"]){
        [self tipView];
    }else if ([model.name isEqualToString:@"推镜拍摄"]){
        [self tipView];
    }else if ([model.name isEqualToString:@"Boomrang"]){
        [self tipView];
    }
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewWith:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self scrollViewWith:scrollView];
    }
}
//判断当前页面，给当前model赋值
- (void)scrollViewWith:(UIScrollView *)scrollView{
    NSUInteger page = scrollView.contentOffset.x/SCREANWIDTH;
    self.currentModel = self.dataSource[page];
    self.pageControl.currentPage = page;
}

#pragma mark btnClickevent——设置按钮点击
- (void)btnClickevent:(UIButton *)btn{
    NvSetUpViewController *vc = [[NvSetUpViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 相册回调
- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    if (self.model == NvEdit) {
        NvSizeViewController *sizeVC = [NvSizeViewController new];
        sizeVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:sizeVC animated:NO completion:NULL];
        __weak typeof(self)weakSelf = self;
        [sizeVC selectSizeTypeBlock:^(NvEditMode type) {
            NvEditViewController *vc = [[NvEditViewController alloc] init];
            vc.selectAssets = assets;
            vc.editMode = type;
            vc.isFromAlbum = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
    }
}

- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssetsOverMaxCountLimit:(NSMutableArray <NvAlbumAsset *>*)assets {
    if (self.model == NvEdit) {
        //没有限制
    } else if (self.model == NvPIPEdit) {//超过限制
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多选2个素材" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alertVC addAction:sureAction];
        [self presentViewController:alertVC animated:YES completion:NULL];
    }
}

- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController didSelectAlbumAssets:(NSMutableArray <NvAlbumAsset *>*)assets {
    if (self.model == NvEdit) {
        //没有限制
    } else if (self.model == NvPIPEdit) {//超过限制
        if (assets.count == 1) {
            [self.custumButton setTitle:@"选择第2个素材" forState:UIControlStateNormal];
            [self.custumButton setTitleColor:[UIColor nv_colorWithHexRGB:@"#FFA3A3A3"] forState:UIControlStateNormal];
        } else if (assets.count == 2) {
            [self.custumButton setTitle:@"开始制作" forState:UIControlStateNormal];
            [self.custumButton setTitleColor:[UIColor nv_colorWithHexRGB:@"#4A90E2"] forState:UIControlStateNormal];
        } else if (assets.count == 0) {
            [self.custumButton setTitle:@"选择2个素材进行制作" forState:UIControlStateNormal];
            [self.custumButton setTitleColor:[UIColor nv_colorWithHexRGB:@"#FFA3A3A3"] forState:UIControlStateNormal];
        }
    }
}

- (void)customButtonClick:(UIButton *)button {
    if (self.albumViewController.selectAssetSource.count<2) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择两个素材" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:sureAction];
        [self presentViewController:alertVC animated:YES completion:NULL];
    } else {
        NvPIPEditViewController *pipEdit = [NvPIPEditViewController new];
        pipEdit.selectAsset = self.albumViewController.selectAssetSource;
        [self.navigationController pushViewController:pipEdit animated:YES];
    }
    
}

- (UIView *)nvAlbumViewControllerCustomBottomButton {
    if (self.model == NvEdit) {
        return nil;
    } else if (self.model == NvPIPEdit) {
        UIView *bottomView = [[UIView alloc] init];
        bottomView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#363738"];
        UIButton *custumButton = [UIButton buttonWithType:UIButtonTypeCustom];
        custumButton.frame = CGRectMake(0, 0, SCREANWIDTH, 49*SCREANSCALE);
        self.custumButton = custumButton;
        [self.custumButton addTarget:self action:@selector(customButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.custumButton setTitle:@"选择2个素材进行制作" forState:UIControlStateNormal];
        [self.custumButton setTitleColor:[UIColor nv_colorWithHexARGB:@"#FFA3A3A3"] forState:UIControlStateNormal];
        self.custumButton.titleLabel.font = [NvUtils fontWithSize:16];
        [bottomView addSubview:self.custumButton];
        return bottomView;
    }
    return nil;
}

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

@end
