//
//  GMVideoWaitingView.m
//  Gengmei
//
//  Created by yefengming on 2020/3/6.
//  Copyright © 2020 更美互动信息科技有限公司. All rights reserved.
//

#import "GMVideoWaitingView.h"
#import "GMWaitingSuccessView.h"
#import "GMNoticeInfoObject.h"
#import "GMVideoPhobos.h"
#import "GMLibraryHeader.h"

#import <GMBase/GMBaseTool.h>
#import "NSBundle+GMAILab.h"

#define centerPoint CGPointMake(MAINSCREEN_WIDTH / 2, MAINSCREEN_HEIGHT / 2)
#define circleAnimaitionTime 2
#define fromRadius sqrtf((centerPoint.x * centerPoint.x) + (centerPoint.y * centerPoint.y))
#define toRadius (92.0 / 375 * MAINSCREEN_WIDTH)
#define circleRadius (80.0 / 375 * MAINSCREEN_WIDTH)
#define showAnimaitionTime .35
#define hideAnimaitionTime .35

@interface GMVideoWaitingView ()
{
    NSTimer *_timer;
    CAShapeLayer *_maskLayer;
}
@property (nonatomic, strong) GMLabel *topLabel;
@property (nonatomic, strong) GMLabel *bottomLabel;
@property (nonatomic, strong) GMButton *cancelBtn;
@property (nonatomic, strong) GMLabel *infoLabel;
@property (nonatomic, strong) GMWaitingSuccessView *successView;
@property (nonatomic, strong) SDAnimatedImageView *animationView;
@property (nonatomic, strong) GMImageView *beijingView;
@property (nonatomic, assign) BOOL isCanceling;

@end

@implementation GMVideoWaitingView

- (void)setup {
    [super setup];
    // 监听 是否有人抢单成功（信令消息）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchAndPingCurrentDispatch) name:@"gm_push_consouller_accept" object:nil];

    self.container.size = CGSizeMake(MAINSCREEN_WIDTH, 380 + UIView.safeAreaInsetsBottom);
    [self containerRectCorner:self.container];
    
    self.animationView.hidden = NO;
    
    self.topLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:16];
    self.topLabel.font = [UIFont gmBoldFont:16];
    self.topLabel.text = @"正在匹配";
    self.topLabel.textAlignment = NSTextAlignmentCenter;
    [self.container addSubview:self.topLabel];
    
    self.bottomLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x282828) fontSize:16];
    self.bottomLabel.font = [UIFont gmBoldFont:16];
    self.bottomLabel.text = @"60s";
    [self.container addSubview:self.bottomLabel];
    
    self.cancelBtn = [[GMButton alloc] init];
    [self.cancelBtn setTitle:@"取消连线" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.cancelBtn.backgroundColor = RGBCOLOR_HEX(0xCCCCCC);
    self.cancelBtn.layer.cornerRadius = 23;
    self.cancelBtn.layer.masksToBounds = YES;
    [self.container addSubview:self.cancelBtn];
    [self.cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.infoLabel = [GMLabel labelWithTextColor:RGBCOLOR_HEX(0x464646) fontSize:14];
    self.infoLabel.text = @"正在全力为您匹配";
    self.infoLabel.textAlignment = NSTextAlignmentCenter;
    [self.container addSubview:self.infoLabel];
    
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(27);
        make.centerX.mas_equalTo(0);
    }];
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-16-UIView.safeAreaInsetsBottom);
        make.left.mas_equalTo(42);
        make.right.mas_equalTo(-42);
        make.height.mas_equalTo(46);
    }];
    
    [self.bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.cancelBtn.mas_top).offset(-23);
        make.centerX.mas_equalTo(0);
    }];
    
    [self.infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topLabel.mas_bottom).offset(5);
        make.centerX.mas_equalTo(0);
    }];
    
    _maskLayer = [CAShapeLayer layer];
    _maskLayer.bounds = self.bounds;
    _maskLayer.fillColor = [UIColor greenColor].CGColor; // Any color but clear will be OK
    _maskLayer.path = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:fromRadius startAngle:0 endAngle:2 * M_PI clockwise:YES].CGPath;
    _maskLayer.opacity = 1;
    _maskLayer.position = centerPoint;
    
    self.beijingView = [[GMImageView alloc] initWithImage:[UIImage imageNamed:@"waiting_image"]];
    self.beijingView.hidden = YES;
    [self.container addSubview:self.beijingView];
    [self.beijingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(88);
        make.centerX.mas_equalTo(0);
    }];
}

- (void)containerRectCorner:(UIView *)view {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(12, 12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)startShowPhotoAnimation {
    CGPathRef fromPath = _maskLayer.path;
    CGPathRef toPath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:toRadius startAngle:0 endAngle:2 * M_PI clockwise:YES].CGPath;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    pathAnimation.fromValue = (__bridge id _Nullable)(fromPath);
    pathAnimation.toValue = (__bridge id _Nullable)(toPath);
    pathAnimation.duration = showAnimaitionTime;
    _maskLayer.path = toPath;
    [_maskLayer addAnimation:pathAnimation forKey:@"path"];
    [self performSelector:@selector(startCircleAnimation) withObject:nil afterDelay:showAnimaitionTime];
}

- (void)startCircleAnimation {
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
     pathAnimation.calculationMode = kCAAnimationCubicPaced;
     pathAnimation.fillMode = kCAFillModeForwards;
     pathAnimation.removedOnCompletion = NO;
     pathAnimation.duration = circleAnimaitionTime;
     pathAnimation.repeatCount = OPEN_MAX;
    CGMutablePathRef curvedPath = CGPathCreateMutable();
    //center为圆心,circleRadius为半径 （startAngle，endAngle）为起始角度和结束角度，0为顺时针，1 为逆时针
    CGPathAddArc(curvedPath, NULL, centerPoint.x + circleRadius / 2, centerPoint.y, circleRadius / 2, M_PI, 2 * M_PI, 0);
    CGPathAddArc(curvedPath, NULL, centerPoint.x, centerPoint.y, circleRadius, 0, M_PI, 0);
    CGPathAddArc(curvedPath, NULL, centerPoint.x - circleRadius / 2, centerPoint.y, circleRadius / 2, M_PI, 2 * M_PI, 0);

    pathAnimation.path = curvedPath;
    CGPathRelease(curvedPath);

    [_maskLayer addAnimation:pathAnimation forKey:@"position"];
}

- (void)startHidePhotoAnimation {
    // 删除动画
    [self.animationView removeFromSuperview];
    
    CGPathRef fromPath = _maskLayer.path;
    CGPathRef toPath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:fromRadius * 2 startAngle:0 endAngle:2 * M_PI clockwise:YES].CGPath;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    pathAnimation.fromValue = (__bridge id _Nullable)(fromPath);
    pathAnimation.toValue = (__bridge id _Nullable)(toPath);
    pathAnimation.duration = hideAnimaitionTime;
    _maskLayer.path = toPath;
    [_maskLayer addAnimation:pathAnimation forKey:@"path"];
}

- (void)addCountDownTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCountDown) userInfo:nil repeats:YES];
    [_timer fire];
    [self startShowPhotoAnimation];
}

- (void)removeAnimation {
    [_maskLayer removeAllAnimations];
}

- (void)updateCountDown {
    if (self.currentTime >= 0 ) {
        self.bottomLabel.text = [NSString stringWithFormat:@"%ds", self.currentTime];
        self.currentTime --;
        if (self.currentTime % 5 == 0) {
            [self fetchCurrentDispatchInfoWithIsNotify:NO];
        }
        // 1s请求一次
        [self pingCurrentDispatch];
        
    } else {
        NSString *str = self.counsellorType == 1 ? @"医生":@"面诊师";
        str = [NSString stringWithFormat:@"抱歉，暂无%@接单，请稍后再试，本次视频面诊订单金额将原路退还至您的账户中",str];
        [[GMBaseTool getCurrentViewController] toast:str];
        [self invalidateCountDownTimer];
        [self cancelDispatch];
        [self hide];
//        if (self.timerOverBlock) {
//            self.timerOverBlock();
//        }
    }
}

- (void)fetchCurrentDispatchInfoWithIsNotify:(BOOL)isNotify {
    if (self.isCanceling) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:@"/api/consultation_counsel/get_current_dispatch_info" method:GMHTTPMethodGet parameters:nil completion:^(GMResponseOC * _Nonnull response) {
        if (response.data[@"notice_info"]) {

            [weakSelf showSuccessView];
            weakSelf.successView.object = [[GMNoticeInfoObject alloc] initWithDictionary:response.data[@"notice_info"] error:nil];
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:response.data[@"consultation_record_info"]];
            [dict setValue:@(weakSelf.counsellorType) forKey:@"counsellor_type"];
            [dict setValue:@(weakSelf.consultationType) forKey:@"consultation_type"];
            weakSelf.successView.info = dict;
            if (!isNotify) {
                [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.Dispatch.PollDispatch" status:@"success" extraParam:@{@"consultation_record_id": SafeString(dict[@"consultation_record_id"])}];
            }
            [GMVideoPhobos video_monitoringWithActionStep:@"用户客户端收到匹配成功回执" consultId:weakSelf.successView.info[@"consultation_record_id"] traceId:nil];
        }
    }];
}

- (void)pingCurrentDispatch {
    // 只要客户端还处于等待派单的状态，就每1秒POST一次
    [GMNetworking requestOCWithApi:@"/api/consultation_counsel/current_dispatch_ping" method:GMHTTPMethodPost parameters:nil completion:nil];
}

- (void)fetchAndPingCurrentDispatch {
    if (self.isCanceling) {
        return;
    }
    [self fetchCurrentDispatchInfoWithIsNotify:YES];
    [self pingCurrentDispatch];
}


- (void)cancelDispatch {
    __weak typeof(self)weakSelf = self;
       [GMNetworking requestOCWithApi:@"/api/consultation_counsel/cancel_dispatch" method:GMHTTPMethodPost parameters:nil completion:^(GMResponseOC * _Nonnull response) {
           if (response.isSuccess) {
               [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.Dispatch.CancelButton.Click" status:@"success" extraParam:@{@"order_no": SafeString(weakSelf.orderNo)}];

               if (weakSelf.isCanceling) {
                   [weakSelf waitViewHide];
               }
           } else {
               [GMVideoPhobos consultation_traceWithActionStep:@"Consultation.Dispatch.CancelButton.Click" status:@"failed" extraParam:@{@"order_no": SafeString(weakSelf.orderNo)}];
               weakSelf.isCanceling = NO;
               [weakSelf fetchAndPingCurrentDispatch];
           }
       }];
}

- (void)cancelBtnClick {
    if (self.currentTime >= 0) {
        self.isCanceling = YES;
        [self cancelDispatch];
    } else {
        __weak __typeof(self)weakSelf = self;
        UIAlertController *alert = [UIAlertController alert:@"正在为您全力匹配医生、面诊师 真的不再等一等了么？" leftTitle:@"残忍离开" rightTitle:@"取消" leftAlterAction:^{
            [weakSelf waitViewHide];
        } rightAlertAction:^{
            
        }];
        [[GMBaseTool getCurrentViewController] presentViewController:alert animated:YES completion:nil];
    }
}

- (void)showSuccessView {
    [self invalidateCountDownTimer];
    [self removeAnimation];
    [self.successView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self hide];
}
- (void)invalidateCountDownTimer{
    [_timer invalidate];
    _timer = nil;
}

- (void)waitViewHide {
    [[GMBaseTool getCurrentViewController] toast:@"取消派单成功，本次视频面诊订单金额将原路退还至您的账户中"];
    [self invalidateCountDownTimer];
    [self removeAnimation];
    [self hide];
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

- (void)didTapView {
    if (self.currentTime < 0) {
        [self hide];
    }
}
- (GMWaitingSuccessView *)successView {
    if (!_successView) {
        _successView = [[GMWaitingSuccessView alloc] init];
        [[GMBaseTool getCurrentViewController].view addSubview:_successView];
    }
    return _successView;
}

- (SDAnimatedImageView *)animationView {
    if (!_animationView) {
        _animationView = [[SDAnimatedImageView alloc] init];
        _animationView.contentMode = UIViewContentModeScaleAspectFill;
        _animationView.runLoopMode = NSDefaultRunLoopMode;
        _animationView.frame = CGRectMake(0, 78, MAINSCREEN_WIDTH, 212);
        _animationView.centerX = centerPoint.x;
        NSString *path = [[NSBundle gm_AILabBundle:[self class]] pathForResource:@"waiting_loading" ofType:@"webp"];
        NSData *data = [[NSData alloc] initWithContentsOfFile:path];
        UIImage *img = [UIImage sd_imageWithData:data];
        _animationView.image = img;
        [self.container addSubview:_animationView];
    }
    return _animationView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
