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

#import "NvEditCaptionViewController.h"
#import "NvAddCaptionView.h"
#import "NvRectView.h"
#import "NvCaptionDialog.h"
#import "NvsTimelineCaption.h"
#import "NvCaptionStyleItem.h"
#import "NvMoreDownloadViewController.h"
#import "NvAssetManager.h"
#import "NvAsset.h"
#import "NvTimelineUtils.h"
#import "NvTimelineCaptionUtils.h"
#import "NvTimelineData.h"
#import "NvInfoModel.h"
#import "NvMoreFilterViewController.h"
#import "NvSDKUtils.h"
#import "NvStyleView.h"

@interface NvEditCaptionViewController ()<NvAddCaptionViewDelegate, NvRectViewDelegate, NvCaptionDialogDelegate, NvLiveWindowPanelViewDelegate, NvsStreamingContextDelegate,NvAssetManagerDelegate>

@property (nonatomic, strong) NvAddCaptionView *addCaptionView;
@property (nonatomic, strong) NvRectView *rectView;
@property (nonatomic, strong) NvCaptionDialog *dialog;
@property (nonatomic, strong) NvCaptionDialog *changeDialog;
@property (nonatomic, strong) NvsTimelineCaption *currentCaption;
@property (nonatomic, strong) NvStyleView *styleView;

@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NSMutableArray *styleDataSource;
//@property (nonatomic, strong) NvCaptionInfoModel *currentCaption;
//用于存储timeSpan对象，滑动timelineEditor的时候如果有字幕需要让对应的timeSpan选中，删除字幕的时候要让对应的timeSpan也删除
@property (nonatomic, strong) NSMutableArray <NvInfoModel *>*timeSpanArray;
@property (nonatomic, strong) NSMutableArray <NvCaptionInfoModel *>*captionInfoArray; //每个字幕数据

@property (nonatomic, assign) BOOL isStyleModel; //是否是样式模式
@property (nonatomic, assign) BOOL isSelect; //当前字幕是否是被选装(用于区分是否需要弹框)

@end

@implementation NvEditCaptionViewController

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"currentCaption"];
    NSLog(@"%s",__func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"字幕";
    self.timeSpanArray = [NSMutableArray array];
    [self initTimeline];
    
    [self initSubViews];
    [self.liveWindowPanel setForceHiddenControlPanel:YES];
    self.liveWindowPanel.delegate = self;
    
    [self addObserver:self forKeyPath:@"currentCaption" options:NSKeyValueObservingOptionNew context:nil];
    self.assetManager = [NvAssetManager sharedInstance];
    self.assetManager.delegate = self;
    [self.assetManager searchLocalAssets:ASSET_CAPTION_STYLE];
    
    NSString *itemPath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"caption"];
    [self.assetManager searchReservedAssets:ASSET_CAPTION_STYLE bundlePath:itemPath];
    
//    [self setViewDefaultData:self.currentCaption];
}

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

- (void)initReservedAssetName:(NvAsset *)asset {
    if ([asset isReserved]) {
        if ([asset.uuid isEqualToString:@"DF34A143-A1AF-475B-A59D-3350B2E406BC"]) {
            asset.name = @"火焰喷射";
//            asset.aspectRatio = AspectRatio_1v1|AspectRatio_16v9|AspectRatio_9v16;
        }
        if ([asset.uuid isEqualToString:@"2EFFCD4F-B03A-487E-AC6A-282694AAF238"]) {
            asset.name = @"小黄人";
//            asset.aspectRatio = AspectRatio_1v1|AspectRatio_16v9;
        }
        if ([asset.uuid isEqualToString:@"5DCC70E9-122F-455E-A72E-35FE2FACEF02"]) {
            asset.name = @"时尚闪现";
        }
     }
}

//重新创建timeline和数据结构
- (void)initTimeline {
    self.timeline = [NvTimelineUtils createTimeline:self.editMode];
    [NvTimelineUtils recreateTimeline:self.timeline];
    NvTimelineData *data = [NvTimelineData sharedInstance];
    self.captionInfoArray = [[NSMutableArray alloc] initWithArray:[data captionDataArray] copyItems:YES];
    [NvTimelineUtils resetCaption:self.timeline captionDataArray:self.captionInfoArray];
}
//设置默认数据
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setViewDefaultData:self.currentCaption];
}
//获取字幕样式默认数据
- (void)getStyleDefaultData {
    
    AspectRatio ratio;
    switch (self.editMode) {
        case NvEditMode16v9:
            ratio = AspectRatio_16v9;
            break;
        case NvEditMode1v1:
            ratio = AspectRatio_1v1;
            break;
        case NvEditMode9v16:
            ratio = AspectRatio_9v16;
            break;
        case NvEditMode3v4:
            ratio = AspectRatio_3v4;
            break;
        case NvEditMode4v3:
            ratio = AspectRatio_4v3;
            break;
        default:
            ratio = AspectRatio_All;
            break;
    }
    NSArray *array = [self.assetManager getUsableAssets:ASSET_CAPTION_STYLE aspectRatio:ratio categoryId:NV_CATEGORY_ID_ALL];
    self.styleDataSource = [NSMutableArray array];
    for (NvAsset *asset in array) {
        NvCaptionStyleItem *item = [NvCaptionStyleItem new];
        item.imageUrl = [asset.coverUrl absoluteString];
        item.name = asset.name;
        item.packageId = asset.uuid;
        [self.styleDataSource addObject:item];
        [self initReservedAssetName:asset];
    }
    NvCaptionStyleItem *item = [NvCaptionStyleItem new];
    item.imageUrl = @"NvsFilterNone";
    item.name = @"无";
    item.packageId = @"";
    item.isSelect = YES;
    [self.styleDataSource insertObject:item atIndex:0];
    
}
//给试图设置默认数据
- (void)setViewDefaultData:(NvsTimelineCaption *)currentCaption {
    [self getStyleDefaultData];
    NvCaptionInfoModel *currentModel = [self getCaptionInfoModel:currentCaption];
    //设置样式
    NSString *packageId = currentModel.styleId;
//    NSString *packageId = currentCaption.captionStylePackageId;
    if ([packageId isEqualToString:@""] || packageId == nil) {
        for (NvCaptionStyleItem *item in self.styleDataSource) {
            item.isSelect = NO;
        }
        NvCaptionStyleItem *item = [self.styleDataSource firstObject];
        item.isSelect = YES;
    } else {
        for (int i = 0; i < self.styleDataSource.count; i++) {
            NvCaptionStyleItem *item = [self.styleDataSource objectAtIndex:i];
            if ([item.packageId isEqualToString:packageId]) {
                item.isSelect = YES;
            } else {
                item.isSelect = NO;
            }
        }
    }
    [self.styleView.styleListView renderListWithItems:self.styleDataSource];
    //设置颜色
//    NvsColor nvColor = [currentCaption getTextColor];
    
//    const CGFloat *currentColor = CGColorGetComponents(currentModel.color.CGColor);
    CGFloat colorR,colorG,colorB,colorA;
    BOOL succes = [currentModel.color getRed:&colorR green:&colorG blue:&colorB alpha:&colorA];
    if (succes) {
        NvsColor nvColor;
        nvColor.r = colorR;
        nvColor.g = colorG;
        nvColor.b = colorB;
        nvColor.a = colorA;
        float colorAlpha = nvColor.a;
        NSMutableArray *colorDataSource = self.styleView.colorListView.dataSource;
        for (NvCaptionColorItem *item in colorDataSource) {
            const CGFloat *components = CGColorGetComponents(item.color.CGColor);
            if (nvColor.r == components[0] && nvColor.g == components[1] && nvColor.b == components[2]) {
                colorAlpha = nvColor.a;
                item.isSelect = YES;
            } else {
                item.isSelect = NO;
            }
        }
        [self.styleView.colorListView setDefaultDataSource:colorDataSource alpha:colorAlpha];
    } else {
        NSMutableArray *colorDataSource = self.styleView.colorListView.dataSource;
        for (NvCaptionColorItem *item in colorDataSource) {
            item.isSelect = NO;
        }
        [self.styleView.colorListView setDefaultDataSource:colorDataSource alpha:1];
    }

    //设置描边
//    NvsColor outline = [currentCaption getOutlineColor];
//    UIColor *outlineColor = currentModel.outlineColor;
//    const CGFloat *currentOutlineColor = CGColorGetComponents(currentModel.color.CGColor);
    
    CGFloat outlineR,outlineG,outlineB,outlineA;
    BOOL outlineSucces = [currentModel.outlineColor getRed:&outlineR green:&outlineG blue:&outlineB alpha:&outlineA];
    if (outlineSucces) {
        NvsColor outline = {outlineR,outlineG,outlineB,outlineA};
        float strokeAlpha = 1;
        float strokeWidth = 10;
        NSMutableArray *strokeDataSource = self.styleView.strokeListView.dataSource;
        if ([currentCaption getDrawOutline]) {
            NvCaptionStrokeItem *item_first = strokeDataSource.firstObject;
            item_first.isNone = YES;
            item_first.isSelect = NO;
            
            for (int i = 1; i < strokeDataSource.count; i++) {
                NvCaptionStrokeItem *item = strokeDataSource[i];
                if (outline.r == item.color.r && outline.g == item.color.g && outline.b == item.color.b) {
                    strokeAlpha = outline.a;
                    strokeWidth = [currentCaption getOutlineWidth]/10.0;
                    item.isSelect = YES;
                    item.isNone = NO;
                } else {
                    item.isSelect = NO;
                    item.isNone = NO;
                }
            }
            
        } else {
            for (NvCaptionStrokeItem *item in strokeDataSource) {
                item.isSelect = NO;
            }
            strokeAlpha = 1;
            strokeWidth = 10;
            NvCaptionStrokeItem *item = strokeDataSource[0];
            item.isSelect = YES;
            item.isNone = YES;
        }
        
        
        [self.styleView.strokeListView setDefaultDataSource:strokeDataSource width:strokeWidth alpha:strokeAlpha];
    } else {
        float strokeAlpha = 1;
        float strokeWidth = 10;
        NSMutableArray *strokeDataSource = self.styleView.strokeListView.dataSource;
 
        for (NvCaptionStrokeItem *item in strokeDataSource) {
            item.isSelect = NO;
            item.isNone = NO;
        }
        strokeAlpha = 1;
        strokeWidth = 10;
        NvCaptionStrokeItem *item = strokeDataSource.firstObject;
        item.isSelect = YES;
        item.isNone = YES;

        [self.styleView.strokeListView setDefaultDataSource:strokeDataSource width:strokeWidth alpha:strokeAlpha];
    }

    //设置字体
//    NSString *fontFilePath = [currentCaption getFontFilePath];
    NSString *fontFilePath = currentModel.fontFilePath;
    if (!fontFilePath) {
        fontFilePath = @"";
    }
    NSMutableArray *fontDataSource = self.styleView.fontListView.dataSource;
    for (NvCaptionFontItem *item in fontDataSource) {
        if ([fontFilePath isEqualToString:item.fontPath]) {
            item.isSelect = YES;
        } else {
            item.isSelect = NO;
        }
    }
    [self.styleView.fontListView setDefauleDataSource:fontDataSource];
    [self.styleView.fontListView setDefaultFontBoldButton:currentModel.isBold italic:currentModel.isItalic shadow:currentModel.isDrawShadow];
//    //设置大小
//    float size = currentModel.fontSize;
//    [self.styleView.sizeListView setDefaultValue:size];
    
    //设置位置
    [self.styleView.positionListView resetApplyButton];
}

/**
 应用样式后会更改大小等数据，需要更新一下默认数据
 */
- (void)applyStyleUpdateDefaultData:(NvsTimelineCaption *)currentCaption {
    NvCaptionInfoModel *currentModel = [self getCaptionInfoModel:currentCaption];
//    //设置大小                                                           
//    float size = currentModel.fontSize;
//    [self.styleView.sizeListView setDefaultValue:size];
    
    //设置字体
    NSString *fontFilePath = currentModel.fontFilePath;
    if (!fontFilePath) {
        fontFilePath = @"";
    }
    NSMutableArray *fontDataSource = self.styleView.fontListView.dataSource;
    for (NvCaptionFontItem *item in fontDataSource) {
        if ([fontFilePath isEqualToString:item.fontPath]) {
            item.isSelect = YES;
        } else {
            item.isSelect = NO;
        }
    }
    [self.styleView.fontListView setDefauleDataSource:fontDataSource];
    [self.styleView.fontListView setDefaultFontBoldButton:currentModel.isBold italic:currentModel.isItalic shadow:currentModel.isDrawShadow];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentCaption"]) {
        self.addCaptionView.styleButton.hidden = self.currentCaption?NO:YES;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)stylePlay {
    if (![[NvSDKUtils getSDKContext] playbackTimeline:self.timeline startTime:0 endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
        NSLog(@"播放时间线失败！");
        return;
    }
    self.addCaptionView.playButton.selected = NO;
}

/**
 获取当前字幕的NvInfoModel
 
 @param currentCaption 当前字幕信息
 @return 当前字幕的NvInfoModel
 */
- (NvInfoModel *)getCurrentTimeSpan:(NvsTimelineCaption *)currentCaption {
    NvInfoModel *infoModel = nil;
    for (int i = 0; i < self.timeSpanArray.count; i++) {
        infoModel = self.timeSpanArray[i];
        if (infoModel.currentCaption == self.currentCaption) {
            return infoModel;
        }
    }
    return infoModel;
}
//重现显示字幕及选中框
- (void)showCaption {
    if (self.currentCaption == nil) {
        self.rectView.hidden = YES;
        return;
    }
    
    //    NSArray *array = [NvTimelineCaptionUtils getCaptionBoundingPoints:self.timeline liveWindow:self.liveWindowPanel.liveWindow captionInfo:self.currentCaption];
    //    [self.rectView setPoints:array];
    self.rectView.hidden = NO;
    [self updateCaptionView:self.currentCaption];
}
//更新字幕框的位置
- (void)updateCaptionView: (NvsTimelineCaption*) caption {
    NSArray *array = [caption getBoundingRectangleVertices];
    NSValue *leftTopValue = array[0];
    NSValue *leftBottomValue = array[1];
    NSValue *rightBottomValue = array[2];
    NSValue *rightTopValue = array[3];
    CGPoint topLeftCorner = [leftTopValue CGPointValue];
    CGPoint bottomLeftCorner = [leftBottomValue CGPointValue];
    CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
    CGPoint rightTopCorner = [rightTopValue CGPointValue];
    
    topLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:topLeftCorner];
    rightBottomCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightBottomCorner];
    bottomLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:bottomLeftCorner];
    rightTopCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightTopCorner];
    
    [self.rectView setPoints:@[[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:topLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:bottomLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightBottomCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightTopCorner toView:self.rectView]]]];
    if ([caption getTextAlignment] == NvsTextAlignmentLeft) {
        [self.rectView setTextAlign:NvLeft];
    } else if ([caption getTextAlignment] == NvsTextAlignmentCenter) {
        [self.rectView setTextAlign:NvCenter];
    } else if ([caption getTextAlignment] == NvsTextAlignmentRight) {
        [self.rectView setTextAlign:NvRight];
    }
    
    [self seekTimeline];
}

- (void)updateCaptionViewNOSeek:(NvsTimelineCaption*) caption {
    NSArray *array = [caption getBoundingRectangleVertices];
    NSValue *leftTopValue = array[0];
    NSValue *leftBottomValue = array[1];
    NSValue *rightBottomValue = array[2];
    NSValue *rightTopValue = array[3];
    CGPoint topLeftCorner = [leftTopValue CGPointValue];
    CGPoint bottomLeftCorner = [leftBottomValue CGPointValue];
    CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
    CGPoint rightTopCorner = [rightTopValue CGPointValue];
    
    topLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:topLeftCorner];
    rightBottomCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightBottomCorner];
    bottomLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:bottomLeftCorner];
    rightTopCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightTopCorner];
    
    [self.rectView setPoints:@[[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:topLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:bottomLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightBottomCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightTopCorner toView:self.rectView]]]];
    if ([caption getTextAlignment] == NvsTextAlignmentLeft) {
        [self.rectView setTextAlign:NvLeft];
    } else if ([caption getTextAlignment] == NvsTextAlignmentCenter) {
        [self.rectView setTextAlign:NvCenter];
    } else if ([caption getTextAlignment] == NvsTextAlignmentRight) {
        [self.rectView setTextAlign:NvRight];
    }
}

- (CGPoint)getCenterWithArray:(NSArray*)array {
    NSValue *leftTopValue = array[0];
    NSValue *rightBottomValue = array[2];
    CGPoint topLeftCorner = [leftTopValue CGPointValue];
    CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
    return CGPointMake((topLeftCorner.x+rightBottomCorner.x)/2, (topLeftCorner.y+rightBottomCorner.y)/2);
}


// MARK: NvAddCaptionViewDelegate
- (void)nvAddCaptionViewdidAddCaptionClick {
    //距离末尾小于1秒时不加字幕
    if (self.timeline.duration-[self.streamingContext getTimelineCurrentPosition:self.timeline] < 1000000) {
        [NvToast showInfoWithMessage:@"距离末尾小于1秒时不加字幕"];
        return;
    }
    self.dialog = [[[NSBundle mainBundle] loadNibNamed:@"CaptionDialog" owner:self options:nil] firstObject];
    [self.view addSubview:self.dialog];
    self.dialog.delegate = self;
    [self.dialog mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(@(80*SCREANSCALE));
        make.width.equalTo(@(320*SCREANSCALE));
        make.height.equalTo(@(180*SCREANSCALE));
    }];
}
// 点击样式
- (void)nvAddCaptionViewdidAddStyleClick {
    [self.streamingContext stop];
    self.styleView.hidden = NO;
    self.styleView.caption = self.currentCaption;
    self.styleView.models = self.captionInfoArray;
    NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
    self.styleView.model = modelInfo.infoModel;
    [self.styleView.styleListView renderListWithItems:self.styleDataSource];
    self.isStyleModel = YES;
    self.isSelect = YES;
    
//    self.liveWindowPanel.outPoint = self.currentCaption.outPoint;
    
    //给编辑UI设置需要修改的数据源（因为切换数据源了）字幕
    self.styleView.caption = self.currentCaption;
    self.styleView.model = [self getCaptionInfoModel:self.currentCaption];
    
    [self setViewDefaultData:self.currentCaption];
}
// MARK: NvStyleViewDelegate
- (void)styleOkClick {
    [self.streamingContext stop];
    self.styleView.hidden = YES;
    [self.addCaptionView.timelineEditor setTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
    self.isStyleModel = NO;
    self.isSelect = NO;
    [self.streamingContext stop];
    
    self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    self.rectView.hidden = self.currentCaption?NO:YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        NvInfoModel *modelnext = [self getCurrentTimeSpan:self.currentCaption];
        if (self.currentCaption) {
            [self updateCaptionView:self.currentCaption];
            [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
        }
    });
}

- (void)moreStyleClick {
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.editModel = self.editMode;
    vc.type = ASSET_CAPTION_STYLE;
    vc.isCapture = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)moreFontClick {
    [NvToast showInfoWithMessage:@"目前没有更多字体"];
}

- (void)nvseekTimeline {
    //    [self showCaption];
    [self updateCaptionViewNOSeek:self.currentCaption];
    [self seekTimeline];
}
//样式播放
- (void)stylePlayFromTime:(int64_t)time {
    [self.liveWindowPanel playBackStart:time end:self.currentCaption.outPoint];
}

- (NvRectView *)getRectView {
    return self.rectView;
}

// MARK: NvCaptionDialogDelegate
- (void)captionDialog:(NvCaptionDialog *)captionDialog clickButtonIndex:(NSInteger)index {
    //添加字幕页面修改字幕
    if (self.changeDialog == captionDialog) {
        if (index == 0) {
            NSString* text = [captionDialog getCaptionText];
            text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NvCaptionInfoModel *model = [self getCaptionInfoModel:self.currentCaption];
            model.text = text;
            [self.currentCaption setText:text];
            [self updateCaptionView:self.currentCaption];
        } else {
            //不做处理
        }
        [self.changeDialog removeFromSuperview];
        self.changeDialog = nil;
        return;
    }
    //编辑模式下修改字幕
    if (self.isStyleModel) {
        if (index == 0) {
            NSString* text = [captionDialog getCaptionText];
            text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            [self.currentCaption setText:text];
            [self updateCaptionView:self.currentCaption];
            NvCaptionInfoModel *model = [self getCaptionInfoModel:self.currentCaption];
            model.text = text;
        } else {
            //不做处理
        }
        [self.dialog removeFromSuperview];
        self.dialog = nil;
    } else {
        //添加字幕
        if (index == 0) {//确定
            NSString* text = [captionDialog getCaptionText];
            text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if(text.length == 0) {
                [NvToast showInfoWithMessage:@"您输入的字幕为空，请重新输入"];
            } else {
                // 添加字幕
                int64_t inPoint = [[NvSDKUtils getSDKContext] getTimelineCurrentPosition:self.timeline];
                int64_t duration = 5000000;
                if (inPoint + duration > self.timeline.duration) {
                    duration = self.timeline.duration - inPoint;
                }
                
                //添加字幕
                NvCaptionInfoModel *captionModel = [NvCaptionInfoModel new];
                NvsTimelineCaption* caption = [self.timeline addCaption:text inPoint:inPoint duration: duration captionStylePackageId:nil];
                [caption translateCaption:CGPointMake(0, 0)];
                self.currentCaption = caption;
                [caption setDrawShadow:NO];
                [caption setAttachment:captionModel forKey:@"captionInfoModel"];
                [caption setFontSize:self.timeline.videoRes.imageHeight/10];
                [caption setCaptionTranslation:CGPointMake(0, 0)];
                [caption setScaleX:[caption getScaleX]];
                [caption setRotationZ:[caption getRotationZ]];
                [caption setBold:[caption getBold]];
                [caption setItalic:[caption getItalic]];
                [caption setAnchorPoint:CGPointMake(0, 0)];
                
                captionModel.category = caption.category;
                captionModel.text = text;
                NvsColor capColor = [caption getTextColor];
                captionModel.color = [UIColor colorWithRed:capColor.r green:capColor.g blue:capColor.b alpha:capColor.a];
                captionModel.inPoint = inPoint;
                captionModel.outPoint = inPoint + duration;
                captionModel.fontSize = [caption getFontSize];
                captionModel.translation = [caption getCaptionTranslation];
                captionModel.isBold = [caption getBold];
                captionModel.isItalic = [caption getItalic];
                captionModel.isDrawShadow = [caption getDrawShadow];
                captionModel.anchorPoint = [caption getAnchorPoint];
                captionModel.rotation = [caption getRotationZ];
                captionModel.scale = [caption getScaleX];
                captionModel.alignment = [caption getTextAlignment];
                [self.captionInfoArray addObject:captionModel];
                
                [self showCaption];
                int64_t inpoint = [self.streamingContext getTimelineCurrentPosition:self.timeline];
                NvsCTimelineTimeSpan *timeSpan = [self.addCaptionView.timelineEditor addTimeSpan:inpoint outPoint:inpoint+duration];
                //选中某一个timeSpan
                [self.addCaptionView.timelineEditor selectTimeSpan:timeSpan];
                //存储一个infoModel对象用于使timelineEditor高亮
                NvInfoModel *infoModel = [NvInfoModel new];
                infoModel.currentCaption = self.currentCaption;
                infoModel.infoModel = captionModel;
                infoModel.timeSpan = timeSpan;
                if (self.currentCaption) {
                    [self.timeSpanArray addObject:infoModel];
                }
                
            }
        } else {//取消
            //不作处理
        }
        [self.dialog removeFromSuperview];
        self.dialog = nil;
    }
}

// MARK: NvRectViewDelegate(NvRectView回调)
- (void)rectView:(NvRectView*)rectView close:(UIButton*)close {
    if (self.isStyleModel) {
        self.styleView.hidden = YES;
        self.isStyleModel = NO;
    }
    //获取数据删除timelineEditor框
    NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
    [self.addCaptionView.timelineEditor selectTimeSpan:modelInfo.timeSpan];
    [self.addCaptionView.timelineEditor deleteSelectedTimeSpan];
    //删除字幕
    [self.timeline removeCaption:self.currentCaption];
    //删除数据
    [self.captionInfoArray removeObject:modelInfo.infoModel];
    [self.timeSpanArray removeObject:modelInfo];
    
    self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    if (self.currentCaption) {
        NvInfoModel *modelInfonext = [self getCurrentTimeSpan:self.currentCaption];
        [self.addCaptionView.timelineEditor selectTimeSpan:modelInfonext.timeSpan];
        [self showCaption];
    } else {//删完了，就直接隐藏
        self.rectView.hidden = YES;
    }
    //如果在末尾删除会导致黑屏
    int64_t curentTime = [self.streamingContext getTimelineCurrentPosition:self.timeline];
    if (curentTime-100000 < 0) {
        curentTime = 0;
    } else {
        curentTime = curentTime-100000;
    }
    [self seekTimeline:curentTime];
}
//todo: 缺少图片
- (void)rectView:(NvRectView *)rectView align:(UIButton *)align {
    NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
    switch ([self.currentCaption getTextAlignment]) {
        case NvsTextAlignmentLeft:
            [self.currentCaption setTextAlignment:NvsTextAlignmentCenter];
            [align setImage:[UIImage imageNamed:@"NvTextAlignedCenter"] forState:UIControlStateNormal];
            modelInfo.infoModel.alignment = NvsTextAlignmentCenter;
            break;
        case NvsTextAlignmentCenter:
            [self.currentCaption setTextAlignment:NvsTextAlignmentRight];
            [align setImage:[UIImage imageNamed:@"NvTextAlignedRight"] forState:UIControlStateNormal];
            modelInfo.infoModel.alignment = NvsTextAlignmentRight;
            break;
        case NvsTextAlignmentRight:
            [self.currentCaption setTextAlignment:NvsTextAlignmentLeft];
            [align setImage:[UIImage imageNamed:@"NvTextAlignedLeft"] forState:UIControlStateNormal];
            modelInfo.infoModel.alignment = NvsTextAlignmentLeft;
            break;

        default:
            [self.currentCaption setTextAlignment:NvsTextAlignmentLeft];
            [align setImage:[UIImage imageNamed:@"NvTextAlignedLeft"] forState:UIControlStateNormal];
            modelInfo.infoModel.alignment = NvsTextAlignmentLeft;
            break;
    }
    [self seekTimeline];
}

- (void)rectView:(NvRectView*)rectView rotate:(float)rotate scale:(float)scale {
    NSArray *array = [self.currentCaption getBoundingRectangleVertices];
    CGPoint center = [self getCenterWithArray:array];
    //字幕缩放大于5倍则不允许再放大
    if (scale > 1 && [self.currentCaption getScaleX] > 5) {
        return;
    }
    [self.currentCaption scaleCaption:scale anchor:center];
    [self.currentCaption rotateCaption:rotate anchor:center];
    [self updateCaptionView:self.currentCaption];
    
    NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
    modelInfo.infoModel.rotation = [self.currentCaption getRotationZ];
    modelInfo.infoModel.scale = [self.currentCaption getScaleX];
}

- (void)rectView:(NvRectView*)rectView currentPoint:(CGPoint)currentPoint previousPoint:(CGPoint)previousPoint {
    CGPoint p1 = [self.liveWindowPanel.liveWindow mapViewToCanonical:currentPoint];
    CGPoint p2 = [self.liveWindowPanel.liveWindow mapViewToCanonical:previousPoint];
    CGPoint newPoint = CGPointMake(p1.x-p2.x, p1.y-p2.y);
    [self.currentCaption translateCaption:newPoint];
    
    [self updateCaptionView:self.currentCaption];
    NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
    modelInfo.infoModel.translation = [self.currentCaption getCaptionTranslation];
    
}

- (void)rectView:(NvRectView *)rectView touchUpInside:(CGPoint)point {
    
    if (!self.isSelect) {
        NSLog(@"!isSelect播放");
        if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
            if (![[NvSDKUtils getSDKContext] playbackTimeline:self.timeline startTime:self.liveWindowPanel.currentTime endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                NSLog(@"播放时间线失败！");
                return;
            }
        } else {
            [[NvSDKUtils getSDKContext] stop];
        }
        return;
    }
//    if (self.isStyleModel) {
        if (self.currentCaption) {
            NSArray *array = [self.currentCaption getBoundingRectangleVertices];
            NSValue *leftTopValue = array[0];
            NSValue *leftBottomValue = array[1];
            NSValue *rightBottomValue = array[2];
            NSValue *rightTopValue = array[3];
            CGPoint topLeftCorner = [leftTopValue CGPointValue];
            CGPoint bottomLeftCorner = [leftBottomValue CGPointValue];
            CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
            CGPoint rightTopCorner = [rightTopValue CGPointValue];
            
            topLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:topLeftCorner];
            rightBottomCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightBottomCorner];
            bottomLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:bottomLeftCorner];
            rightTopCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightTopCorner];
            
            CGMutablePathRef pathRef=CGPathCreateMutable();
            CGPathMoveToPoint(pathRef, NULL, topLeftCorner.x, topLeftCorner.y);
            CGPathAddLineToPoint(pathRef, NULL, bottomLeftCorner.x, bottomLeftCorner.y);
            CGPathAddLineToPoint(pathRef, NULL, rightBottomCorner.x, rightBottomCorner.y);
            CGPathAddLineToPoint(pathRef, NULL, rightTopCorner.x, rightTopCorner.y);
            CGPathCloseSubpath(pathRef);
            bool isIn = CGPathContainsPoint(pathRef, nil, point, false);
            CGPathRelease(pathRef);
            if(isIn){
                [self.rectView setPoints:@[[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:topLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:bottomLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightBottomCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightTopCorner toView:self.rectView]]]];
                NSLog(@"在内部");
                self.changeDialog = [[[NSBundle mainBundle] loadNibNamed:@"CaptionDialog" owner:self options:nil] firstObject];
                [self.changeDialog setCaptionText:[self.currentCaption getText]];
                [self.view addSubview:self.changeDialog];
                self.changeDialog.delegate = self;
                [self.changeDialog mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(self.view);
                    make.top.equalTo(@(80*SCREANSCALE));
                    make.width.equalTo(@(320*SCREANSCALE));
                    make.height.equalTo(@(180*SCREANSCALE));
                }];
            } else {
                NSLog(@"touchUpInside播放");
                if ([NvSDKUtils getSDKContext].getStreamingEngineState != NvsStreamingEngineState_Playback) {
                    if (![[NvSDKUtils getSDKContext] playbackTimeline:self.timeline startTime:self.liveWindowPanel.currentTime endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0]) {
                        NSLog(@"播放时间线失败！");
                        return;
                    }
                } else {
                    [[NvSDKUtils getSDKContext] stop];
                }
            }
        }
//    }
    
}

- (void)rectView:(NvRectView *)rectView isHidden:(BOOL)isHidden {
    if (isHidden) {
        [self.liveWindowPanel addTapScreenPause];
    } else {
        [self.liveWindowPanel removeTapScreenPause];
    }
}

- (void)rectView:(NvRectView*)rectView touchBeganPoint:(CGPoint)point{
    if (self.isStyleModel) {//不是编辑模式不能切换
        return;
    }
    NSArray *captionArray = [self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
    captionArray = [self removeThemeCaption:captionArray];
    for (int i = 0; i < captionArray.count; i++) {
        NvsTimelineCaption *cap = captionArray[i];
        NSArray *array = [cap getBoundingRectangleVertices];
        NSValue *leftTopValue = array[0];
        NSValue *leftBottomValue = array[1];
        NSValue *rightBottomValue = array[2];
        NSValue *rightTopValue = array[3];
        CGPoint topLeftCorner = [leftTopValue CGPointValue];
        CGPoint bottomLeftCorner = [leftBottomValue CGPointValue];
        CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
        CGPoint rightTopCorner = [rightTopValue CGPointValue];
        
        topLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:topLeftCorner];
        rightBottomCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightBottomCorner];
        bottomLeftCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:bottomLeftCorner];
        rightTopCorner = [self.liveWindowPanel.liveWindow mapCanonicalToView:rightTopCorner];
        
        CGMutablePathRef pathRef=CGPathCreateMutable();
        CGPathMoveToPoint(pathRef, NULL, topLeftCorner.x, topLeftCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, bottomLeftCorner.x, bottomLeftCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, rightBottomCorner.x, rightBottomCorner.y);
        CGPathAddLineToPoint(pathRef, NULL, rightTopCorner.x, rightTopCorner.y);
        CGPathCloseSubpath(pathRef);
        bool isIn = CGPathContainsPoint(pathRef, nil, point, false);
        CGPathRelease(pathRef);
        if(isIn){
            if (self.currentCaption == cap) {
                self.isSelect = YES;
            } else {
                self.isSelect = NO;
            }
            [self.rectView setPoints:@[[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:topLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:bottomLeftCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightBottomCorner toView:self.rectView]],[NSValue valueWithCGPoint:[self.liveWindowPanel.liveWindow convertPoint:rightTopCorner toView:self.rectView]]]];
            //设为当前字幕
            self.currentCaption = cap;
            NvInfoModel *info = [self getCurrentTimeSpan:cap];
            //选中timeSpan
            [self.addCaptionView.timelineEditor selectTimeSpan:info.timeSpan];
        }
    }
}

// MARK: 返回按钮事件
- (void)nvAddCaptionViewdidAddOkClick {
    [self.streamingContext removeTimeline:self.timeline];
    NvTimelineData *data = [NvTimelineData sharedInstance];
    data.captionDataArray = self.captionInfoArray;
    NSMutableArray *order = [[NvTimelineData sharedInstance] dataOrder];
    [order removeObject:@"Caption"];
    [order addObject:@"Caption"];
    [self.navigationController popViewControllerAnimated:YES];
}
//放大timelineEditor
- (void)captionTimelineEditorZoomIn {
    [self.addCaptionView.timelineEditor zoomIn];
    [self.addCaptionView setcurrentTime:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
}
//缩小timelineEditor
- (void)captionTimelineEditorZoomOut {
    [self.addCaptionView.timelineEditor zoomOut];
    [self.addCaptionView setcurrentTime:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
}

//MARK:拖拽timelineEditor回调
- (void)dragTimelineEditor:(int64_t)timestamp {
    self.liveWindowPanel.progressSlider.value = 1.0*timestamp/self.timeline.duration;
    self.liveWindowPanel.currentTime = timestamp;
    self.rectView.hidden = YES;
    
    //拖动过程中显示时间
    [self.addCaptionView setcurrentTime:timestamp];
    [self seekTimeline:timestamp];
    
}
//timespan滑块拖拽结束
- (void)timelineEditor:(id)timelineEditor dragHandleEnded:(int64_t)timestamp isInPoint:(bool)isInPoint {
    [self.addCaptionView.timelineEditor setTimelinePosition:timestamp];
    NvInfoModel *modelnext = [self getCurrentTimeSpan:self.currentCaption];
    if (self.currentCaption) {
        [self updateCaptionViewNOSeek:self.currentCaption];
        [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
    }
    
    if (isInPoint) {
        [self.currentCaption changeInPoint:timestamp];
        [self seekTimeline:timestamp];
    } else {
        [self.currentCaption changeOutPoint:timestamp];
        [self seekTimeline:timestamp-10000];
    }
}
//timespan滑块拖拽过程中
- (void)timelineEditor:(id)timelineEditor draggingHandle:(int64_t)timestamp isInPoint:(bool)isInPoint {
    //    self.rectView.hidden = YES;
    //更改出入点
    NvInfoModel *model = [self getCurrentTimeSpan:self.currentCaption];
    if (isInPoint) {
        model.infoModel.inPoint = timestamp;
        [self seekTimeline:timestamp];
        //播放过程中显示时间
        [self.addCaptionView setcurrentTime:timestamp];
    } else {
        model.infoModel.outPoint = timestamp;
        [self seekTimeline:timestamp-10000];
        //播放过程中显示时间
        [self.addCaptionView setcurrentTime:timestamp-10000];
    }
    
}

//拖拽timelineEditor结束回调
- (void)dragScrollTimelineEnded:(int64_t)timestamp {
    NvInfoModel *model = [self getCurrentTimeSpan:self.currentCaption];
    [self.addCaptionView.timelineEditor selectTimeSpan:model.timeSpan];
    
    self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    self.rectView.hidden = self.currentCaption?NO:YES;
    
    if (self.currentCaption) {
        [self updateCaptionViewNOSeek:self.currentCaption];
        NvInfoModel *modelInfo = [self getCurrentTimeSpan:self.currentCaption];
        [self.addCaptionView.timelineEditor selectTimeSpan:modelInfo.timeSpan];
    } else {
        [self.addCaptionView.timelineEditor selectTimeSpan:nil];
    }
    [self nvseekTimeline];
}

// MARK:播放过程中的回调
- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position {
    [self.addCaptionView.timelineEditor selectTimeSpan:nil];
    self.addCaptionView.playButton.selected = YES;
    NvsTimelineCaption *captemp = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
    self.addCaptionView.styleButton.hidden = !captemp;
    if (self.isStyleModel) {
        self.rectView.hidden = YES;
    } else {
        [self.addCaptionView.timelineEditor setTimelinePosition:position];
        self.rectView.hidden = YES;
        
        //播放过程中显示时间
        [self.addCaptionView setcurrentTime:position];
    }
}
//播放停止的回调
- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    [self.addCaptionView.timelineEditor setTimelinePosition:[self.streamingContext getTimelineCurrentPosition:timeline]];
    self.addCaptionView.playButton.selected = NO;
    if (self.isStyleModel) {
        NvsTimelineCaption *captemp= [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
        self.addCaptionView.styleButton.hidden = !captemp;
        int64_t currentTime = [self.streamingContext getTimelineCurrentPosition:self.timeline];
        if (currentTime > self.currentCaption.outPoint || currentTime < self.currentCaption.inPoint) {
            self.rectView.hidden = YES;
        } else {
            self.rectView.hidden = NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NvInfoModel *modelnext = [self getCurrentTimeSpan:captemp];
            if (captemp) {
                if (!self.rectView.hidden) {
                    [self updateCaptionView:captemp];
                }
                
                [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
            }
        });
    } else {
        
        self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
        self.rectView.hidden = self.currentCaption?NO:YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            NvInfoModel *modelnext = [self getCurrentTimeSpan:self.currentCaption];
            if (self.currentCaption) {
                [self updateCaptionView:self.currentCaption];
                [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
            }
        });
    }
}
//播放到末尾的回调
- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    if (self.isStyleModel) {
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf seekTimeline:weakSelf.currentCaption.inPoint];
//            self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
            NvInfoModel *modelnext = [self getCurrentTimeSpan:self.currentCaption];
            if (self.currentCaption) {
                [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
                self.rectView.hidden = self.currentCaption?NO:YES;
                [self updateCaptionView:self.currentCaption];
            }
        });
        [self.addCaptionView.timelineEditor setTimelinePosition:self.currentCaption.inPoint];
    } else {
        [self.addCaptionView.timelineEditor setTimelinePosition:0];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf seekTimeline:0];
            self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:[self.streamingContext getTimelineCurrentPosition:self.timeline]] lastObject];
            NvInfoModel *modelnext = [self getCurrentTimeSpan:self.currentCaption];
            if (self.currentCaption) {
                [self.addCaptionView.timelineEditor selectTimeSpan:modelnext.timeSpan];
                self.rectView.hidden = self.currentCaption?NO:YES;
                [self updateCaptionView:self.currentCaption];
            }
        });
    }
}


// MARK: initSubviews
- (void)initSubViews {
    self.rectView = [[NvRectView alloc] init];
    self.rectView.delegate = self;
    self.rectView.layer.masksToBounds = YES;
    [self.liveWindowPanel.liveWindow addSubview:self.rectView];
    [self.rectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    self.rectView.hidden = YES;
    self.addCaptionView = [NvAddCaptionView new];
    self.addCaptionView.delegate = self;
    self.addCaptionView.timeline = self.timeline;
    self.addCaptionView.styleButton.hidden = YES;
    [self.view addSubview:self.addCaptionView];
    [self.addCaptionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(SCREEN_WDITH));
        make.left.right.bottom.equalTo(@0);
        make.height.equalTo(@(234*SCREANSCALE + INDICATOR));
    }];
    //显示时间
    [self.addCaptionView setcurrentTime:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
    
    //恢复数据
    NvsTimelineCaption *nextCaption = [self.timeline getFirstCaption];
    self.currentCaption = nextCaption;
    do {
        NSLog(@"=======%d,%d,%@",nextCaption.category,nextCaption.roleInTheme,nextCaption.getText);
        if (nextCaption.category == NvsThemeCategory && nextCaption.roleInTheme != NvsRoleInThemeGeneral) {
            
        }else{
            NvsCTimelineTimeSpan *timeSpan = [self.addCaptionView.timelineEditor addTimeSpan:nextCaption.inPoint outPoint:nextCaption.outPoint];
            [self.addCaptionView.timelineEditor selectTimeSpan:timeSpan];
            [self updateCaptionView:nextCaption];
            //存储一个infoModel对象用于使timelineEditor高亮
            NvInfoModel *infoModel = [NvInfoModel new];
            infoModel.currentCaption = nextCaption;
            infoModel.infoModel =  [self getCaptionInfoModel:nextCaption];
            infoModel.timeSpan = timeSpan;
            if (nextCaption) {
                [self.timeSpanArray addObject:infoModel];
            }
        }
        nextCaption = [self.timeline getNextCaption:nextCaption];
    } while (nextCaption);
    
    self.currentCaption = [[self.timeline getCaptionsByTimelinePosition:0] firstObject];
    if (self.currentCaption) {
        self.isSelect = YES;
        NvInfoModel *infoModel =  [self getCurrentTimeSpan:self.currentCaption];
        [self.addCaptionView.timelineEditor selectTimeSpan:infoModel.timeSpan];
        __weak typeof(self)weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.rectView.hidden = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf updateCaptionView:weakSelf.currentCaption];
            });
            weakSelf.addCaptionView.styleButton.hidden = NO;
        });
    } else {
        self.rectView.hidden = YES;
        self.addCaptionView.styleButton.hidden = YES;
        [self.addCaptionView.timelineEditor selectTimeSpan:nil];
    }
    
    self.styleView = [NvStyleView new];
    self.styleView.delegate = self;
    self.styleView.timeline = self.timeline;
    [self.view addSubview:self.styleView];
    [self.styleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.addCaptionView);
    }];
    self.styleView.hidden = YES;
}
//获取字幕对应的infoModel对象
- (NvCaptionInfoModel *)getCaptionInfoModel:(NvsTimelineCaption *) nextCaption {
    return (NvCaptionInfoModel *)[nextCaption getAttachment:@"captionInfoModel"];
}

- (void)setCurrentCaption:(NvsTimelineCaption *)currentCaption{
    if (currentCaption.category == NvsThemeCategory && currentCaption.roleInTheme != NvsRoleInThemeGeneral) {
        _currentCaption = nil;
    }else{
        _currentCaption = currentCaption;
    }
}

- (NSArray *)removeThemeCaption:(NSArray *)captionArray {
    NSMutableArray *array = [NSMutableArray array];
    [captionArray enumerateObjectsUsingBlock:^(NvsTimelineCaption*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.category == NvsThemeCategory && obj.roleInTheme != NvsRoleInThemeGeneral) {
            
        } else {
            [array addObject:obj];
        }
    }];
    return [array copy];
}

@end
