//
//  RDSBindDeviceVC.m
//  Temperature
//
//  Created by RD on 2022/11/21.
//

#import "RDSBindDeviceVC.h"
#import "RDSBabyBluetooth.h"
#import <WebKit/WebKit.h>
#import <SDWebImage/SDWebImage.h>
#import "RDSMapHelper.h"

@interface RDSBindDeviceVC ()
@property (weak, nonatomic) IBOutlet UIView *gifView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UIButton *finishBtn;
@property (weak, nonatomic) IBOutlet UILabel *tipsLab;
@property (weak, nonatomic) IBOutlet UILabel *countDownLab;
@property (weak, nonatomic) IBOutlet UIImageView *ringImgView;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, strong) CADisplayLink *displayLinkCountDown;//倒计时
@property (nonatomic, assign) int countDown;
@property (nonatomic, strong) RDSBabyBluetooth *baby;

@end

@implementation RDSBindDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"绑定设备";
    
    [self startAnimation];
    
    
    RDSBabyBluetooth *baby = TheBabyBluetooth;
    self.baby = baby;
    [TheBabyBluetooth rds_refreshScanDeviceName:_deviceID];
    
    RDS_WEAKSELF(weakSelf)
    [TheBabyBluetooth rds_cmdResponceObserve:[self class] responce:^(RDSDeviceReply *reply) {
        [weakSelf p_receiveCmd:reply];
    }];
    
    TheBabyBluetooth.onConnectDeviceSuccessAndCanWrite = ^{
        [weakSelf p_sendWifiToDecive];
    };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(p_timeout) withObject:nil afterDelay:120];
    });
}

// 配对超时 延时任务
- (void)p_timeout{
    
    self.finishBtn.hidden = NO;
    _searchView.hidden = YES;
    [self stopAnimation];
    [TheAlertCtrl rds_alertWithTitle:@"提示" message:@"绑定失败，配对超时。"];
    
}

// 取消执行延时任务
- (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];
    [self p_cancelTimeout];
}

- (IBAction)onSendCmdClick {
    [self p_sendWifiToDecive];
}

- (IBAction)onFinishClick:(UIButton *)sender {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 设备信息

- (void)p_receiveCmd:(RDSDeviceReply *)reply{
    
    NSString *msg = [NSString stringWithFormat:@"Step %ld  ----  %d", reply.bindStep, reply.code];
    [RDSHudShower showCenterToast:msg];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.tipsLab.text = @"正在配网";
    });

    
    if (reply.bindStep == Step5 && reply.code == 0) {
        RDS_WEAKSELF(weakSelf)
        dispatch_async(dispatch_get_main_queue(), ^{
            self.finishBtn.hidden = NO;
            self.tipsLab.text = @"配网完成";
            
            [weakSelf p_cancelTimeout];
            [RDSDemoApiHelper rds_addRoomName:self->_roomName control_number:reply.deviceCode device_type_id:self.deviceTypeModel.record_id success:^(id responseObject) {
                
                if ([responseObject[@"code"] intValue] != 0) {
                    [RDSHudShower showBottomToast:responseObject[@"message"]];
                    [self.navigationController popViewControllerAnimated:YES];
                }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:@"连接服务器失败"];
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [TheMapHelper rds_startLocationSevice:^(RDSUserLocation *userLocation) {
                [weakSelf p_updateLocation];
            }];
        });
    }
}

- (void)p_updateLocation{
//    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_updateHomeInfoWithHomeId:TheDataManager.current_home_id name:TheDataManager.current_home_name city:TheMapHelper.userLocation.cityString success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 0) {
            DDLog(@"更新城市成功");
        } else{
            DDLog(@"更新城市失败:%@",responseObject[@"message"]);
        }
    } failure:^(NSError *error) {
    }];
}


- (void)p_sendWifiToDecive{
    
    NSDictionary *param = @{
        @"ssid" : _wifiName,
        @"pwd" : _pwd,
        @"user_id" : TheDataManager.currentUser.record_id,
        @"home_id" : TheDataManager.current_home_id,
        @"room_name" : _roomName,
        @"env" : @(TheApiHelper.isTest),
    };
    
    DDLog(@"发送WiFi账号密码:%@",param);
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingSortedKeys error:&parseError];
    
    [TheBabyBluetooth rds_writeValue:jsonData];
}



#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;
    
    self.countDown = 120;
    self.displayLinkCountDown = [CADisplayLink displayLinkWithTarget:self selector:@selector(p_countDown)];
    [self.displayLinkCountDown addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLinkCountDown.paused = NO;
    self.displayLinkCountDown.preferredFramesPerSecond = 1;
}

- (void)stopAnimation{
    self.displayLink.paused = YES;
    [self.displayLink invalidate];
    self.displayLink = nil;
    
    self.displayLinkCountDown.paused = YES;
    [self.displayLinkCountDown invalidate];
    self.displayLinkCountDown = nil;
    
    self.countDownLab.text = @"";
}

- (void)p_countDown{
    self.countDownLab.text = [NSString stringWithFormat:@"%d", self.countDown];
    self.countDown --;
}

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{
    
    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;
        [RDSHudShower showCenterToast:@"绑定成功"];
    });
    
    
//    WKWebView *webView = [[WKWebView alloc] initWithFrame:_gifView.bounds];
//    webView.backgroundColor=[UIColor clearColor];
//    webView.scrollView.scrollEnabled=NO;
//    [webView loadData:gifData MIMEType:@"image/gif" characterEncodingName:@"" baseURL:[NSURL URLWithString:@""]];
//    [_gifView addSubview:webView];
    

}


- (void)dealloc{
    
    [TheBabyBluetooth rds_cancelScan];
    [TheBabyBluetooth rds_cancelConnection];
    
    
    [kNotificationCenter removeObserver:self];
    
    DDLog(@"dealloc~~ 绑定设备");
}
@end
