//
//  SubControlVC.m
//  Temperature
//
//  Created by RD on 2023/4/14.
//

#import "RDSSubControlVC.h"
#import "CYCircularSlider.h"
#import "RDSlider.h"
#import "GCDTimer.h"// 轮询定时器
#import "RDSRoomSetVC.h"
#import "RDSUserProtocolViewController.h"
#import "UIImage+Extension.h"

@interface RDSSubControlVC () <senderValueChangeDelegate, UIGestureRecognizerDelegate>

@property (nonatomic,strong) CYCircularSlider *cirSlider;// 温度圆形滑条

@property (weak, nonatomic) IBOutlet UIView *tempView;// 温度
@property (weak, nonatomic) IBOutlet UILabel *airTempLab;

@property (weak, nonatomic) IBOutlet UILabel *roomTempLab;
@property (weak, nonatomic) IBOutlet UILabel *roomHumidityLab;

@property (weak, nonatomic) IBOutlet RDSlider *fanSlider;
@property (weak, nonatomic) IBOutlet UIButton *powerBtn;

@property (nonatomic, strong) GCDTimer *gcdTimer;

@property (strong, nonatomic) UITapGestureRecognizer *fanTap;
@end

@implementation RDSSubControlVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //当前页面禁用全屏右滑返回
    self.fd_interactivePopDisabled = YES;
    
    self.navigationItem.title = _roomModel.name;
    
    [self p_initUI];
    [self p_navEditItem];
    [self p_setUpTimer];// 初始化轮询
    
    _fanTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(p_onSliderTap:)];
    _fanTap.delegate = self;
    [self.fanSlider addGestureRecognizer:_fanTap];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [_gcdTimer pauseTimer];// 暂停轮询
}

- (void)p_navEditItem{
    UIBarButtonItem *item = [RDSBarButtonItem barButtonItemWithImage:@"icon_edit" target:self action:@selector(onEditAction)];
    [self.navigationItem setRightBarButtonItem:item];
}


- (void)p_initUI{
    
    
//    UIImage *greenImg = [UIImage rds_imageWithColor:RDSGreenColor];
//    UIImage *lightGreenImg = [UIImage rds_imageWithColor:RDSLightGreenColor];
//    
//    [_powerBtn setBackgroundImage:lightGreenImg forState:UIControlStateNormal];
//    [_powerBtn setBackgroundImage:greenImg forState:UIControlStateSelected];
    

    
    CGFloat width = 300;
    _cirSlider =[[CYCircularSlider alloc]initWithFrame:CGRectMake((246 - width) / 2, (246 - width) / 2, width, width)];
    _cirSlider.delegate = self;
    _cirSlider.backgroundColor = UIColor.clearColor;
    _cirSlider.filledColor = RDSGreenColor;
    _cirSlider.unfilledColor = RDSLightGreenColor;
    _cirSlider.lineWidth = 20;
    _cirSlider.minimumValue = 16;
    _cirSlider.maximumValue = 30;
    _cirSlider.value = 28;
    
//    _cirSlider.userInteractionEnabled = NO;
//    _cirSlider.handleColor = UIColor.clearColor;
//    _cirSlider.handleColor2 = UIColor.clearColor;
//    _cirSlider.handleColor3 = RDSGreenColor;
    
    [self.tempView addSubview:_cirSlider];
    
    

    _fanSlider.minimumTrackTintColor = RDSGreenColor;
    [_fanSlider setThumbImage:[UIImage imageNamed:@"icon_point"] forState:UIControlStateNormal];
    [_fanSlider setThumbImage:[UIImage imageNamed:@"icon_point"] forState:UIControlStateHighlighted];
}

// cirSlider delegate
- (void)senderVlueChangingWithNum:(int)num{
//    _airTempLab.text = @(num).description;
}

- (void)senderVlueWithNum:(int)num{
    
}


- (void)onEditAction {
    RDSRoomSetVC *vc = [[RDSRoomSetVC alloc] init];
    vc.roomModel = _roomModel;
    [self pushViewController:vc animated:YES];
}

- (IBAction)didTapTemperature:(id)sender {
    [self openPageWithType:@"temp" title:@"温度"];
}

- (IBAction)didTapHumidity:(id)sender {
    [self openPageWithType:@"humidity" title:@"湿度"];
}

- (void)openPageWithType:(NSString *)type title:(NSString *)title {
    NSString *urlStr = [NSString stringWithFormat:@"%@/#/DataChart/%@/%@", kBaseUrlHeadImg, self.roomModel.record_id, type];
    RDSUserProtocolViewController *vc = [[RDSUserProtocolViewController alloc] init];
    vc.url = urlStr;
    vc.vcTitle = title;
    [self pushViewController:vc animated:YES];
}

#pragma mark - Action 设备控制

- (IBAction)onPowerAction:(UIButton *)sender {
    
    [_gcdTimer restartTimer];// 重新开始轮询
    
    sender.selected = !sender.isSelected;
    
    [RDSDemoApiHelper rds_setSubDevPower:sender.isSelected control_number:_roomModel.control_number success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}

- (IBAction)fanValueChanged:(RDSlider *)sender {
    
    // 四舍五入 1~5挡位
    int value = round(sender.value);
    if (value < 1) value = 1;
    sender.value = value;
}

- (IBAction)fanValueDidChanged:(RDSlider *)sender {
    
    [_gcdTimer restartTimer];// 重新开始轮询
    [self p_sendFanSpeed:sender.value];
}


- (void)p_onSliderTap:(UITapGestureRecognizer *)sender {
    
    [_gcdTimer restartTimer];// 重新开始轮询
    
    UISlider *slider = (UISlider *)sender.view;
    
    CGPoint touchPoint = [sender locationInView:slider];
    float value = (slider.maximumValue - slider.minimumValue) * (touchPoint.x / slider.frame.size.width );
    int v = roundf(value);
    if (v<1) v = 1;
    [slider setValue:v animated:YES];
    
    [self p_sendFanSpeed:v];
}

- (void)p_sendFanSpeed:(int)value{
    
    if(kNULLString(_roomModel.control_number)) return;
    
    [RDSDemoApiHelper rds_setSubDevSpeed:value control_number:_roomModel.control_number success:^(id responseObject) {

        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}


#pragma mark - 轮询
// 轮询设备状态 3秒一次
- (void)p_setUpTimer{
    
    self.gcdTimer = [[GCDTimer alloc] init];
    RDS_WEAKSELF(weakSelf)
    [_gcdTimer scheduledTimerWithTimeInterval:3 afterTime:0 repeats:YES block:^{
        [weakSelf p_getRoomDetail];
    }];
}


- (void)p_getRoomDetail{
    
    RDS_WEAKSELF(weakSelf)
    [self.roomModel rds_getRoomDetailFinished:^(NSError * error) {
        [weakSelf p_refreshUI];
    }];
}


- (void)p_refreshUI{
    
    
    // 用户拖动的时候不刷新
    if(!_cirSlider.isTouchInside){
        _cirSlider.value = _roomModel.set_temp;
        _airTempLab.text = @(_roomModel.set_temp).description;
    }
    if (!_fanSlider.isTouchInside){
        [_fanSlider setValue:_roomModel.fan_value animated:YES];
    }

    _roomTempLab.text = [NSString stringWithFormat:@"%d℃", _roomModel.temperature];// 温度
    _roomHumidityLab.text = [NSString stringWithFormat:@"%d%%", _roomModel.humidity];// 湿度
    _powerBtn.selected = _roomModel.power;
    
}



- (void)dealloc{
    
    [_gcdTimer stopTimer];;
    DDLog(@"dealloc~~");
    
}
@end
