//
//  NvAudioPlayerView.m
//  SDKDemo
//
//  Created by 刘东旭 on 2018/7/3.
 //
//

#import "NvAudioPlayerView.h"
#import "NVHeader.h"
#import "REDRangeSlider.h"
#import "NvUtils.h"

@interface NvAudioPlayerView()<REDRangeSliderDelegate>

@property (strong, nonatomic) UIImageView *musicImage;
@property (strong, nonatomic) UIButton *useButton;
@property (strong, nonatomic) UIButton *noMusicButton;
@property (strong, nonatomic) REDRangeSlider *slider;
@property (strong, nonatomic) UIView *progress;
@property (strong, nonatomic) UIImageView *cutPointView;

@property (strong, nonatomic) NvEditSelectMusicItem *item;

@end

@implementation NvAudioPlayerView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor nv_colorWithHexARGB:@"#99000000"];
        self.musicImage = [UIImageView new];
        self.musicImage.image = [NvUtils imageWithName:@"NvEditMusic"];
        [self addSubview:self.musicImage];
        self.nameLabel = [UILabel nv_labelWithText:@"" fontSize:12 textColor:[UIColor nv_colorWithHexRGB:@"#909293"]];
        self.nameLabel.textAlignment = NSTextAlignmentLeft;
        [self addSubview:self.nameLabel];
//        self.singerLabel = [UILabel nv_labelWithText:@"" fontSize:12 textColor:[UIColor nv_colorWithHexRGB:@"#909293"]];
//        [self addSubview:self.singerLabel];
        
        self.currentLabel = [UILabel nv_labelWithText:@"" fontSize:12 textColor:[UIColor nv_colorWithHexRGB:@"#909293"]];
        self.currentLabel.textAlignment = NSTextAlignmentLeft;
//        self.currentLabel.hidden = YES;
        [self addSubview:self.currentLabel];
        
        CGRect sliderFrame = CGRectMake(77*SCREANSCALE,35*SCREANSCALE, 283*SCREANSCALE, 20);

        self.slider = [[REDRangeSlider alloc] initWithFrame:sliderFrame];
        self.slider.delegate = self;
        self.slider.maxValue = 100;
        self.slider.minValue = 0;
        self.slider.stepValue = 1;
        self.slider.minimumSpacing = 3;
        self.slider.leftHandleImage = [NvUtils imageWithName:@"NvCutMusicHandle"];
        self.slider.rightHandleImage = [NvUtils imageWithName:@"NvCutMusicHandle"];
        [self addSubview:self.slider];
        
        _progress = [[UIView alloc] init];
        _progress.frame = CGRectZero;
        _progress.backgroundColor = [UIColor redColor];
        [self.slider addSubview:_progress];
        [self.slider bringSubviewToFront:_progress];
        
        self.cutPointView = [[UIImageView alloc] initWithFrame:CGRectMake(sliderFrame.origin.x, sliderFrame.origin.y, 10, sliderFrame.size.height)];
        self.cutPointView.centerY = self.slider.centerY;
        self.cutPointView.layer.cornerRadius = 2.5;
        self.cutPointView.image = [NvUtils imageWithName:@"NvCutMusicHandle"];
        self.cutPointView.backgroundColor = [UIColor whiteColor];
        self.cutPointView.userInteractionEnabled = YES;
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(imageHandlePan:)];
        [self addGestureRecognizer:pan];
        [self addSubview:self.cutPointView];
        self.cutPointView.hidden = YES;
        
        [self.musicImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(@(13*SCREANSCALE));
            make.width.height.equalTo(@(49*SCREANSCALE));
        }];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.musicImage.mas_right).offset(8*SCREANSCALE);
            make.top.equalTo(@(13*SCREANSCALE));
            make.width.equalTo(@(200*SCREANSCALE));
        }];
        [self.singerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.musicImage.mas_right).offset(8*SCREANSCALE);
            make.top.equalTo(self.nameLabel.mas_bottom).offset(5 * SCREANSCALE);
        }];
        [self.currentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.musicImage.mas_right).offset(8*SCREANSCALE);
            make.top.equalTo(self.nameLabel.mas_bottom).offset(2*SCREANSCALE);
        }];
        
        self.useButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.useButton setTitle:@"使用" forState:UIControlStateNormal];
        self.useButton.titleLabel.textColor = [UIColor whiteColor];
        self.useButton.backgroundColor = [UIColor colorWithPatternImage:[NvUtils imageWithName:@"NvMusicUse"]];
        self.useButton.titleLabel.font = [NvUtils regularFontWithSize:10];
        [self addSubview:self.useButton];
        [self.useButton addTarget:self action:@selector(useButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.useButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@(-13*SCREANSCALE));
            make.top.equalTo(@(13*SCREANSCALE));
            make.width.equalTo(@(35*SCREANSCALE));
            make.height.equalTo(@(20*SCREANSCALE));
        }];
    }
    return self;
}

- (void)imageHandlePan:(UIGestureRecognizer *)pan {
    CGPoint point = [pan locationInView:self];
    float y = self.cutPointView.center.y;
    if (point.x < (self.slider.frame.origin.x)) {
        return;
    }
    if (point.x > (self.slider.frame.origin.x + self.slider.frame.size.width)) {
        return;
    }

    float value = (point.x - self.slider.frame.origin.x) / (self.slider.frame.size.width);
    if ((1-value) * self.item.duration < 15.0) {
        return;
    }
    NSLog(@"------%f",value);
    self.cutPointView.center = CGPointMake(point.x, y);
    if ([self.delegate respondsToSelector:@selector(audioPlayerView:imageHandlePanChanged:)]) {
        [self.delegate audioPlayerView:self imageHandlePanChanged:value*self.item.duration];
    }
    self.slider.trimInLabel.text = [self convertTimecode:self.item.duration*value];
}

- (void)setCutHandleImageValue:(float)value {
    self.cutPointView.center = CGPointMake(value * self.slider.frame.size.width + self.slider.frame.origin.x, self.cutPointView.center.y);
}

- (void)hiddenHandleButton {
    self.slider.leftHandle.hidden = YES;
    self.slider.rightHandle.hidden = YES;
    self.slider.trimInLabel.hidden = YES;
    self.slider.trimOutLabel.hidden = YES;
}

- (void)showCutHandleImage {
    self.cutPointView.hidden = NO;
}

// 进度值更新
- (void)reloadProgress:(CGFloat)progress {
    CGFloat h = 10;
    //    handleImage
    if (progress <= (self.slider.rightValue )/(self.slider.maxValue )) {
        if (self.cutPointView.hidden) {
            _progress.frame = CGRectMake((self.slider.leftHandleImage.size.width/2) +progress *(self.slider.width - (self.slider.leftHandleImage.size.width)) , self.slider.height/ 2.f - h / 2.f , 2, h);
        } else {//如果只有一个裁剪控件
            _progress.frame = CGRectMake((self.slider.leftHandleImage.size.width/2) +progress *(self.slider.width - (self.slider.leftHandleImage.size.width/2)) , self.slider.height/ 2.f - h / 2.f , 2, h);
        }
    } else {
//        [self stop];
    }
    [self.slider bringSubviewToFront:_progress];
}

- (void)renderViewWithItem:(NvEditSelectMusicItem *)item {
    self.item = item;
    self.nameLabel.text = item.musicName;
    self.singerLabel.text = item.authorName;
    self.slider.trimInLabel.text = [self convertTimecode:_currentValue];
    self.slider.trimOutLabel.text = [self convertTimecode:item.duration];
    NSString *duration = [self convertTimecode:item.duration];
    self.currentLabel.text = [NSString stringWithFormat:@"00:00/%@",duration];
}

-(void)setIsCaptureModel:(BOOL)isCaptureModel {
    _isCaptureModel = isCaptureModel;
    if (_isCaptureModel) {
        [self.useButton removeFromSuperview];
        [self.noMusicButton removeFromSuperview];
        self.noMusicButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.noMusicButton setTitle:@"无音乐" forState:UIControlStateNormal];
        self.noMusicButton.titleLabel.textColor = [UIColor whiteColor];
        self.noMusicButton.backgroundColor = [UIColor colorWithRed:214.0/255 green:157.0/255 blue:62.0/255 alpha:1];
        self.noMusicButton.titleLabel.font = [NvUtils fontWithSize:10];
        [self addSubview:self.noMusicButton];
        [self.noMusicButton addTarget:self action:@selector(noMusicButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.noMusicButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@(-13*SCREANSCALE));
            make.top.equalTo(@(13*SCREANSCALE));
            make.width.equalTo(@(35*SCREANSCALE));
            make.height.equalTo(@(20*SCREANSCALE));
        }];
    } else {
        [self.useButton removeFromSuperview];
        [self.noMusicButton removeFromSuperview];
        self.useButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.useButton setTitle:@"使用" forState:UIControlStateNormal];
        self.useButton.titleLabel.textColor = [UIColor whiteColor];
        self.useButton.backgroundColor = [UIColor colorWithPatternImage:[NvUtils imageWithName:@"NvMusicUse"]];
        self.useButton.titleLabel.font = [NvUtils regularFontWithSize:10];
        [self addSubview:self.useButton];
        [self.useButton addTarget:self action:@selector(useButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.useButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@(-13*SCREANSCALE));
            make.top.equalTo(@(13*SCREANSCALE));
            make.width.equalTo(@(35*SCREANSCALE));
            make.height.equalTo(@(20*SCREANSCALE));
        }];
    }
}

- (void)setLeftValue:(float)leftValue rightValue:(float)rightValue {
    self.slider.leftValue = leftValue;
    self.slider.rightValue = rightValue;
}

- (void)useButtonClick:(UIButton *)button {
    if (self.cutPointView.hidden) {
        if ([self.delegate respondsToSelector:@selector(audioPlayerView:withItem:trimIn:trimOut:)]) {
            [self.delegate audioPlayerView:self withItem:self.item trimIn:self.slider.leftValue/100.0*self.item.duration trimOut:self.slider.rightValue/100.0*self.item.duration];
        }
    } else {
        float value = (self.cutPointView.center.x - self.slider.frame.origin.x) / self.slider.frame.size.width;
        if ([self.delegate respondsToSelector:@selector(audioPlayerView:withItem:trimIn:trimOut:)]) {
            float trimOut = self.item.duration>15?15:self.item.duration;
            [self.delegate audioPlayerView:self withItem:self.item trimIn:value * self.item.duration trimOut:value * self.item.duration + trimOut];
        }
    }
    
}

- (void)noMusicButtonClick:(UIButton *)button {
    if ([self.delegate respondsToSelector:@selector(audioPlayerViewNoMusicClick:)]) {
        [self.delegate audioPlayerViewNoMusicClick:self];
    }
}

-(void)setCurrentValue:(CGFloat)currentValue {
    _currentValue = currentValue;
    self.currentLabel.text = [NSString stringWithFormat:@"%@/%@",[self convertTimecode:_currentValue],[self convertTimecode:self.item.duration]];
    if (self.item) {//(0-1)
        [self reloadProgress:currentValue/self.item.duration];
    }
    
}

- (NSString *)convertTimecode:(float)time {
    time = (time + 0.5) / 1;
    int min = (int)time / 60;
    int sec = (int)time % 60;
    if (min >= 10 && sec >= 10)
        return [NSString stringWithFormat:@"%d:%d", min, sec];
    else if (min >= 10)
        return [NSString stringWithFormat:@"%d:0%d", min, sec];
    else if (sec >= 10)
        return [NSString stringWithFormat:@"0%d:%d", min, sec];
    else
        return [NSString stringWithFormat:@"0%d:0%d", min, sec];
}

// MARK: REDRangeSliderDelegate(0-1)
- (void)leftPan:(CGFloat)left {
    NSLog(@"这个值的范围left：%f",left);
    if (self.item) {//转换秒数
        float s = left*self.item.duration;
        self.slider.trimInLabel.text = [self convertTimecode:s];
        if ([self.delegate respondsToSelector:@selector(audioPlayerView:leftValueChanged:)]) {
            [self.delegate audioPlayerView:self leftValueChanged:s];
        }
    }
    [self reloadProgress:left];
    
}

- (void)rightPan:(CGFloat)right {
    NSLog(@"这个值的范围right：%f",right);
    if (self.item) {
        float s = right*self.item.duration;
        self.slider.trimOutLabel.text = [self convertTimecode:s];
        if ([self.delegate respondsToSelector:@selector(audioPlayerView:rightValueChanged:)]) {
            [self.delegate audioPlayerView:self rightValueChanged:s];
        }
    }

}

@end
