//
//  SliderCodeView.m
//  HWMSDKDemo
//
//

#import "SliderCodeView.h"

#define HWM_Screen_Width ([[UIScreen mainScreen]bounds].size.width)
#define HWM_Left_Margin 32

@implementation SliderCodeParam

@end

@interface SliderCodeView ()
{
    dispatch_source_t timer; //定时器
}

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *contentBgView;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIImageView *moveImageView;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
/// 记录滑动完成耗时几秒
@property (nonatomic, assign) CGFloat seconds;
@property (nonatomic, strong) UILabel * successLabel;
@property (nonatomic, strong) UILabel * reminderLabel;
@property (nonatomic, strong) SliderCodeParam *sliderParam;
@property (nonatomic, strong) NSTimer *refreshSliderTimer;
@property (nonatomic, strong) UIButton *refreshBtn;
@property (nonatomic, strong) UISlider *slider;

@end

@implementation SliderCodeView

- (instancetype)initWithFrame:(CGRect)frame param:(SliderCodeParam *)param {
    self = [super initWithFrame:frame];
    if (self) {
        self.sliderParam = param;
        [self addSubviews];
    }
    return self;
}

- (void)addSubviews {
    
    [self addSubview:self.bgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dissmiss)];
    [self.bgView addGestureRecognizer:tap];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    CGFloat contentHeight = (HWM_Screen_Width - 2 * HWM_Left_Margin) * self.sliderParam.bgImageRatio;
    [self addSubview:self.contentBgView];
    [self.contentBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(HWM_Left_Margin);
        make.right.equalTo(self).offset(-HWM_Left_Margin);
        make.centerY.equalTo(self);
        make.height.equalTo(@(contentHeight + 72));
    }];
    
    [self.contentBgView addSubview:self.refreshBtn];
    [self.refreshBtn sizeToFit];
    [self.refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentBgView).offset(8);
        make.top.equalTo(self.contentBgView);
        make.height.width.equalTo(@(36));
    }];

    CGFloat bgImageHeight = (HWM_Screen_Width - 2 * HWM_Left_Margin) * self.sliderParam.bgImageRatio;
    [self.contentBgView addSubview:self.bgImageView];
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.refreshBtn.mas_bottom);
        make.left.right.equalTo(self.contentBgView);
        make.height.equalTo(@(bgImageHeight));
    }];
    
    [self.contentBgView addSubview:self.slider];
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgImageView.mas_bottom);
        make.left.right.equalTo(self.contentBgView);
        make.height.equalTo(@(36));
    }];
                       
    [self.contentBgView addSubview:self.reminderLabel];
    [self.reminderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgImageView.mas_bottom);
        make.left.right.equalTo(self.contentBgView);
        make.height.equalTo(@(36));
    }];
    
    
    [self.contentBgView addSubview:self.successLabel];
    [self.successLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgImageView.mas_bottom);
        make.left.right.equalTo(self.contentBgView);
        make.height.equalTo(@(36));
    }];
    
    [self refreshAction];
}

- (void)startTimer {
    [self stopTimer];
    self.refreshSliderTimer = [NSTimer timerWithTimeInterval:60.0
                                                      target:self
                                                    selector:@selector(refreshCodeViewClick)
                                                    userInfo:nil
                                                     repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.refreshSliderTimer forMode:NSDefaultRunLoopMode];
}

- (void)stopTimer {
    if (self.refreshSliderTimer) {
        if ([self.refreshSliderTimer isValid]) {
            [self.refreshSliderTimer invalidate];
        }
        self.refreshSliderTimer = nil;
    }
}

- (void)updateSliderCodeView:(SliderCodeParam *)sliderParam {
    // 增加hidden判断，如果滑块界面已经隐藏，则不刷新
    if (!self.hidden) {
        self.sliderParam = sliderParam;
        [self refreshAction];
    }
}

//添加可移动的图片
- (void)addMoveImgView{
    self.bgImageView.image = [self getImageWithBase64Str:self.sliderParam.shadowImage];
    self.moveImageView.image = [self getImageWithBase64Str:self.sliderParam.cutImage];
    
    CGFloat y = self.sliderParam.pointY * [self getZoom];
    self.moveImageView.frame = CGRectMake(0, y , [self getCodeSizeWid], [self getCodeSizeWid]);
    [self.bgImageView addSubview:self.moveImageView];
    self.moveImageView.userInteractionEnabled = YES;
    self.bgImageView.userInteractionEnabled = YES;
    UIPanGestureRecognizer * _panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(drageViewMoved:)];
    [self.moveImageView addGestureRecognizer:_panGR];
}

//图片验证滑块的所有事件
- (void)buttonAction:(UISlider*)slider forEvent:(UIEvent *)event{
    UITouchPhase phase = event.allTouches.anyObject.phase;
    if (phase == UITouchPhaseBegan) {
        [self sliderBeganMoveActions];
    }
    else if(phase == UITouchPhaseEnded){
        [self sliderEndedMoveActions];
    }else if (phase == UITouchPhaseMoved){
        [self changeSliderWithVlue:slider.value];
    }
}

//设置默认的滑动
- (void)resetSliderValue{
    self.slider.value = 0.0;
    [self changeReminderLabelHiddenStatus:NO];
    [self changeSliderWithVlue:self.slider.value];
}


//图片位置随着Slider滑动
- (void)changeSliderWithVlue:(CGFloat)value{
    CGRect rect = self.moveImageView.frame;
    CGFloat x = value * (self.bgImageView.frame.size.width) - (value * [self getCodeSizeWid]);
    rect.origin.x = x;
    self.moveImageView.frame = rect;
}

//刷新按钮事件
- (void)refreshAction{
    [self startTimer];
    self.hidden = NO;
    self.seconds = 0;
    if (timer) {
        dispatch_source_cancel(timer);
        timer = nil;
    }
    [self addMoveImgView];
    [self resetSliderValue];
    [self changeViewsStatus:NO];
    [self changeSuccessViewHidden:YES];
}

- (void)changeViewsStatus:(BOOL)isMoveSuccess {
    self.slider.hidden = isMoveSuccess;
    [self refreshBtnUserInteraction:!isMoveSuccess];
    [self changeReminderLabelHiddenStatus:isMoveSuccess];
}

- (void)changeSuccessViewHidden:(BOOL)isHidden {
    self.successLabel.hidden = isHidden;
}

- (void)refreshBtnUserInteraction:(BOOL)enable {
    self.refreshBtn.userInteractionEnabled = enable;
}

- (void)changeReminderLabelHiddenStatus:(BOOL)isHidden {
    self.reminderLabel.hidden = isHidden;
}

//成功的操作
- (void)sliderCheckSuccess{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __weak SliderCodeView *codeView = self;
        [codeView changeViewsStatus:YES];
    });
}

- (void)drageViewMoved:(UIPanGestureRecognizer *)pan {
    if (pan.state == UIGestureRecognizerStateChanged ||
        pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateBegan) {
        UIView *view = pan.view;

        if (pan.state == UIGestureRecognizerStateBegan) {
            [self sliderBeganMoveActions];
            self.slider.highlighted = YES;
        }
        else if(pan.state == UIGestureRecognizerStateEnded){
            [self sliderEndedMoveActions];
            self.slider.highlighted = NO;
        }else if (pan.state == UIGestureRecognizerStateChanged){
            
            CGPoint offset = [pan translationInView:view];
            
            CGRect viewRect = view.frame;
            viewRect = [self changeRectXWithViewFrame:viewRect offset:offset];
            
            view.frame = CGRectMake(viewRect.origin.x, viewRect.origin.y, view.bounds.size.width, view.bounds.size.height);
        }

        [pan setTranslation:CGPointMake(0, 0) inView:view];
    }
}

// 滑块开始拖动时一些操作处理
- (void)sliderBeganMoveActions {
    [self changeReminderLabelHiddenStatus:YES];
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.seconds = 0;
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        self.seconds+=0.1;
    });
    dispatch_resume(timer);
}

// 滑块结束拖动时的一些操作处理
- (void)sliderEndedMoveActions {
    if (timer) {
        dispatch_source_cancel(timer);
        timer = nil;
    }
    [self checkSliderCode];
}

- (CGRect)changeRectXWithViewFrame:(CGRect)viewFrame offset:(CGPoint)offset
{
    CGRect rect = viewFrame;
    CGPoint viewRect = viewFrame.origin;
    viewRect.x += offset.x;
    if (viewRect.x >= CGRectGetWidth(self.bgImageView.frame) - CGRectGetWidth(self.moveImageView.frame)) {
        viewRect.x = CGRectGetWidth(self.bgImageView.frame) - CGRectGetWidth(self.moveImageView.frame);
    }
    if (viewRect.x <= 0) {
        viewRect.x = 0;
    }
    rect.origin = viewRect;
    self.slider.value = rect.origin.x / (CGRectGetWidth(self.bgImageView.frame) - CGRectGetWidth(self.moveImageView.frame));
    
    return rect;
}

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.3];
    }
    return _bgView;
}

- (UIView *)contentBgView {
    if (!_contentBgView) {
        _contentBgView = [[UIView alloc] init];
        _contentBgView.backgroundColor = [UIColor whiteColor];
        _contentBgView.layer.cornerRadius = 2.0f;
        _contentBgView.clipsToBounds = YES;
    }
    return _contentBgView;
}
- (UIImageView *)bgImageView{
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
        _bgImageView.contentMode =  UIViewContentModeScaleAspectFill;
        _bgImageView.clipsToBounds = YES;
    }
    return _bgImageView;
}

- (UIImageView *)moveImageView{
    if (!_moveImageView) {
        _moveImageView = [[UIImageView alloc] init];
        _moveImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _moveImageView;
}

- (UISlider *)slider{
    if (!_slider) {
        _slider = [[UISlider alloc] init];
        [_slider addTarget:self action:@selector(buttonAction:forEvent:) forControlEvents:UIControlEventAllTouchEvents];
    }
    return _slider;
}

- (UIButton *)refreshBtn{
    if (!_refreshBtn) {
        _refreshBtn = [[UIButton alloc] init];
        [_refreshBtn setTitle:@"换一张" forState:UIControlStateNormal];
        _refreshBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_refreshBtn addTarget:self action:@selector(refreshCodeViewClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _refreshBtn;
}

- (CGFloat)width{
    if (!_width) {
        _width = self.frame.size.width - 2 * HWM_Left_Margin;
    }
    return _width;
}

- (CGFloat)height{
    if (!_height) {
        _height = self.frame.size.height;
    }
    return _height;
}

- (UILabel *)successLabel {
    if (!_successLabel) {
        _successLabel = [[UILabel alloc] init];
        _successLabel.font = [UIFont systemFontOfSize:12];
    }
    return _successLabel;
}

- (void)checkSliderIsSuccess:(BOOL)isSuccess {
    self.successLabel.text = isSuccess ? @"验证成功" : @"验证失败，重新滑块完成校验";
}

- (UILabel *)reminderLabel {
    if (!_reminderLabel) {
        _reminderLabel = [[UILabel alloc] init];
        _reminderLabel.text = @"向右拖动滑块填充饼图";
        _reminderLabel.textAlignment = NSTextAlignmentCenter;
        _reminderLabel.font = [UIFont systemFontOfSize:12];
    }
    return _reminderLabel;
}

- (CGFloat)getCodeSizeWid {
    return 49.0 * [self getZoom];
}

- (CGFloat)getZoom {
    return self.width / self.sliderParam.bgImageWidth;
}

- (void)checkSliderCode {
    [self changeSliderEnable:NO];
    CGFloat x = self.moveImageView.frame.origin.x * self.sliderParam.bgImageWidth / self.width;
    NSLog(@"test slider check %f width:%f %f", self.moveImageView.frame.origin.x, self.sliderParam.bgImageWidth, self.width);
    if (_delegate && [_delegate respondsToSelector:@selector(checkSliderCodeWithPointX:slideTime:)]) {
        [_delegate checkSliderCodeWithPointX:x slideTime:self.seconds * 1000];
    }
}

- (void)changeSliderEnable:(BOOL)isEnabled {
    self.slider.enabled = isEnabled;
}

- (void)refreshCodeViewClick {
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickRefreshSlider)]) {
        [self.delegate clickRefreshSlider];
    }
}

- (UIImage *)getImageWithBase64Str:(NSString *)str {
    if (str.length <= 0) {
        return nil;
    }
    NSURL *baseImageUrl = [NSURL URLWithString:str];
    NSData *imageData = [NSData dataWithContentsOfURL:baseImageUrl];
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

- (void)changeSliderViewWithSuccessViewHidden:(BOOL)isHidden sliderIsSuccess:(BOOL)isSuccess sliderEnable:(BOOL)isEnabled {
    [self changeSuccessViewHidden:isHidden];
    [self checkSliderIsSuccess:isSuccess];
    [self changeSliderEnable:isEnabled];
}

- (void)dissmiss {
    [self stopTimer];
    self.hidden = YES;
}

@end
