//
//  RDSBindSubDeviceVC.m
//  Temperature
//
//  Created by RD on 2023/4/17.
//

#import "RDSBindSubDeviceVC.h"
#import <WebKit/WebKit.h>
#import <SDWebImage/SDWebImage.h>

@interface RDSBindSubDeviceVC ()

@property (weak, nonatomic) IBOutlet UIView *gifView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UIImageView *ringImgView;
@property (weak, nonatomic) IBOutlet UIButton *finishBtn;

@property (nonatomic, strong) CADisplayLink *displayLink;

@end

@implementation RDSBindSubDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"绑定设备";
    [self startAnimation];
    
    
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_addRoomName:_roomName control_number:_deviceID success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }else{
            [weakSelf p_cancelTimeout];
            [RDSHudShower showCenterToast:@"绑定成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf p_setupGif];
            });
        }
        
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(p_timeout) withObject:nil afterDelay:120];
    });
}

// 配对超时 延时任务
- (void)p_timeout{
    [RDSHudShower showCenterToast:@"绑定失败，配对超时。"];
}

// 取消执行延时任务
- (void)p_cancelTimeout{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(p_timeout) object:nil];
    });
    
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self stopAnimation];
}

- (IBAction)finishAciton {
    
    [self popToRootViewControllerAnimated:YES];
}


#pragma mark - 爱的魔力转圈圈
- (void)startAnimation{
    
    // 爱的魔力转圈圈
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(d_displayLinkAnimation)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    
    // 每秒调用次数 = 60/frameInterval
    //self.displayLink.preferredFramesPerSecond = 3;
    self.displayLink.paused = NO;
}

- (void)stopAnimation{
    self.displayLink.paused = YES;
    [self.displayLink invalidate];
    self.displayLink = nil;
}

static CGFloat const RDSNormalAngle = 0.08;// 1/60秒旋转的角度
static CGFloat const RDSLowAngle = 0.08;   // 秒旋转的角度
static CGFloat const RDSHighAngle = 0.08;  // 秒旋转的角度
static CGFloat curAngle = 0;
- (void)d_displayLinkAnimation {
    
    if (curAngle >= 2*M_PI) {
        curAngle -= 2*M_PI;
    }
    
    if (curAngle >= 0 && curAngle <= M_PI/3.0) {
        self.ringImgView.transform = CGAffineTransformRotate(self.ringImgView.transform, RDSNormalAngle);
        curAngle += RDSNormalAngle;
    }
    else if (curAngle > M_PI/3.0 && curAngle <= M_PI_2*3) {
        self.ringImgView.transform = CGAffineTransformRotate(self.ringImgView.transform, RDSHighAngle);
        curAngle += RDSHighAngle;
    }
    else {
        self.ringImgView.transform = CGAffineTransformRotate(self.ringImgView.transform, RDSLowAngle);
        curAngle += RDSLowAngle;
    }
}


#pragma mark - GIF
- (void)p_setupGif{
    
    _finishBtn.hidden = NO;
    
    if(_searchView.hidden) return;
    
    _searchView.hidden = YES;
    [self stopAnimation];
    
    NSData *gifData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"finish" ofType:@"gif"]];
    
    // gif只播放1次
    CGImageSourceRef gifSource = CGImageSourceCreateWithData(CFBridgingRetain(gifData), nil);
    size_t gifCount = CGImageSourceGetCount(gifSource);
    NSMutableArray *frames = [NSMutableArray array];
    UIImage *lastImg;
    for (size_t i = 0; i < gifCount; i++) {
        
        CGImageRef imageRef =CGImageSourceCreateImageAtIndex(gifSource, i,NULL);
        UIImage*image = [UIImage imageWithCGImage:imageRef];
        [frames addObject:image];
        CGImageRelease(imageRef);
        
        if(i == gifCount-1){
            lastImg = image;
        }
    }
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.frame = CGRectMake(0, 0, _gifView.rds_width, _gifView.rds_height);
    [_gifView addSubview:imgView];
    imgView.animationImages = frames;
    imgView.animationDuration = 2.5;
    imgView.animationRepeatCount = 1;
    [imgView startAnimating];
    
    RDS_WEAKSELF(weakSelf)
    UIImageView *ok = [[UIImageView alloc] init];
    ok.frame = CGRectMake(0, 0, weakSelf.gifView.rds_width, weakSelf.gifView.rds_height);
    ok.alpha = 0;
    [self.gifView addSubview:ok];
    [ok setImage:lastImg];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ok.alpha = 1;
    });
    
    

}


- (void)dealloc{

    [kNotificationCenter removeObserver:self];
    
    DDLog(@"dealloc~~ 绑定设备");
}
@end
