//
//  RDSAirControlVC.m
//  Temperature
//
//  Created by RD on 2022/11/15.
//

#import "RDSAirControlVC.h"
#import "CYCircularSlider.h"
#import "RDSlider.h"
#import "UIImage+Extension.h"
#import "RDSCtrlModeView.h"
#import "SPAlertController.h"
#import "GCDTimer.h"// 轮询定时器
#import "RDSRoomSetVC.h"
#import <YBPopupMenu/YBPopupMenu.h>
#import "RDSUserProtocolViewController.h"

@interface RDSAirControlVC () <senderValueChangeDelegate, UIGestureRecognizerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, YBPopupMenuDelegate>

// 工作模式(0：制冷,1：制热,2：除湿3：送风4：加湿)
@property (nonatomic, strong) RDSCtrlModeView *modeView;
@property (nonatomic, strong) UIButton *curModel;

@property (weak, nonatomic) IBOutlet UIView *tempView;// 调节温度
@property (nonatomic,strong) CYCircularSlider *cirSlider;// 温度圆形滑条
@property (weak, nonatomic) IBOutlet UILabel *airTempLab;// 空调温度
@property (weak, nonatomic) IBOutlet UILabel *modeLab;// 模式 档位
@property (weak, nonatomic) IBOutlet UILabel *timingLab;// 定时



@property (weak, nonatomic) IBOutlet UILabel *roomTempLab;// 室内温度
@property (weak, nonatomic) IBOutlet UILabel *roomHumidityLab;// 湿度
@property (weak, nonatomic) IBOutlet UILabel *roomPm25Lab;// pm2.5
@property (weak, nonatomic) IBOutlet UILabel *roomCo2Lab;// co2


@property (weak, nonatomic) IBOutlet RDSlider *fanSlider;// 风扇滑条


@property (weak, nonatomic) IBOutlet UIButton *newairBtn;
@property (weak, nonatomic) IBOutlet UIButton *powerBtn;
@property (weak, nonatomic) IBOutlet UIButton *timingBtn;
@property (weak, nonatomic) IBOutlet UIButton *sleepBtn;

@property (nonatomic, strong) GCDTimer *gcdTimer;
@property (nonatomic, strong) SPAlertController *timerAlert;
@property (nonatomic, strong) NSMutableArray *timerData;// 定时picker数据源
@property (nonatomic, strong) NSNumber *selectTimer;

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

@implementation RDSAirControlVC

- (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{
    UIButton *editButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [editButton setImage:[UIImage imageNamed:@"icon_edit"] forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(onEditAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editButton];
}



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

    
    CGFloat width = 260;
    _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;
    [self.tempView addSubview:_cirSlider];
    
    
    _fanSlider.minimumTrackTintColor = RDSGreenColor;
    [_fanSlider setThumbImage:[UIImage imageNamed:@"icon_point"] forState:UIControlStateNormal];
    [_fanSlider setThumbImage:[UIImage imageNamed:@"icon_point"] forState:UIControlStateHighlighted];
    
    if ([self.roomModel.code isEqualToString:@"YXK-Z/86-FG-A"]) {
        self.sleepBtn.hidden = YES;
    }
    
//    UIBezierPath *path = [UIBezierPath bezierPath];
//
//    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
//    shapeLayer.frame = CGRectMake(11, 4, 12, 6);
//    shapeLayer.path = path.CGPath;
//    shapeLayer.strokeColor = [UIColor grayColor].CGColor;
//    shapeLayer.fillColor = [UIColor whiteColor].CGColor;
//
//    [self.fanSlider.layer insertSublayer:shapeLayer atIndex:0];
//
    //循环创建（自己加个循环就好了） offset 计算每个分段的距离
//    CGFloat offset = _fanSlider.rds_width/5.0;
//    UIBezierPath *linePath = [UIBezierPath bezierPath];
//    [linePath moveToPoint:CGPointMake(offset * 1 , 0)];
//    [linePath addLineToPoint:CGPointMake(offset * 1 , 6)];
//
//    CAShapeLayer *lineLayer = [CAShapeLayer layer];
//    lineLayer.path = linePath.CGPath;
//    lineLayer.strokeColor = [UIColor whiteColor].CGColor;
//    lineLayer.fillColor = [UIColor clearColor].CGColor;
//    [shapeLayer insertSublayer:lineLayer atIndex:0];
}

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

- (void)senderVlueWithNum:(int)num{    
    [self setTemp];
}

- (void)p_setupModeView{
    
    CGFloat viewW = (SCREEN_WIDTH-20*6)/5;// 一行显示4个，算上左右2边空白，共5个间隔
    RDSCtrlModeView *modeView = [[RDSCtrlModeView alloc] init];
    self.modeView = modeView;
    [self.view addSubview:modeView];
    [modeView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).with.offset(10);
        } else {
            make.top.equalTo(self.view).offset(10);
        }
        make.height.equalTo(@(viewW));
        make.left.equalTo(self.view);//.offset(10);
        make.right.equalTo(self.view);//.offset(-10);
    }];
    
    RDS_WEAKSELF(weakSelf)
    modeView.onModeClick = ^(int mode) {
        [weakSelf onModeAction:mode];
    };
}


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

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

- (IBAction)didTapPm25:(id)sender {
    [self openPageWithType:@"pm25" title:@"PM 2.5"];
}

- (IBAction)didTapCo2:(id)sender {
    [self openPageWithType:@"co2" 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 设备控制

- (void)onEditAction:(UIButton *)button {
    [YBPopupMenu showRelyOnView:button titles:@[@"编辑名称", @"设备信息"] icons:@[@"menu_edit", @"menu_info"] menuWidth:150 otherSettings:^(YBPopupMenu *popupMenu) {
        popupMenu.delegate = self;
        popupMenu.animationManager.duration = 0.25;
        popupMenu.textColor = [UIColor colorWithHexString:@"#333333"];
    }];
}

#pragma mark - YPPopupMenuDelegate
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index {
    if (index == 0) {
        // 编辑名称
        RDSRoomSetVC *vc = [[RDSRoomSetVC alloc] init];
        vc.roomModel = _roomModel;
        [self pushViewController:vc animated:YES];
        return;
    }
    RDSUserProtocolViewController *vc = [[RDSUserProtocolViewController alloc] init];
    vc.url = [NSString stringWithFormat:@"%@/#/DeviceInfo/%@", kBaseUrlHeadImg, self.roomModel.record_id];
    vc.vcTitle = @"设备信息";
    [self pushViewController:vc animated:YES];
}


// 点击模式
- (void)onModeAction:(int)mode{
    
    [_gcdTimer restartTimer];// 重新开始轮询
    [RDSDemoApiHelper rds_setMode:mode control_number:_roomModel.control_number success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showCenterToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showCenterToast:@"连接服务器失败"];
    }];
}
// 温度-1
- (IBAction)onMovTempAction:(UIButton *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_cirSlider setMovAngel];
    
    [self setTemp];
}

// 温度+1
- (IBAction)onAddTempAction:(UIButton *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_cirSlider setAddAngel];
    
    [self setTemp];
}

// 设置温度
- (void)setTemp{
    
    [_gcdTimer restartTimer];// 重新开始轮询
    [RDSDemoApiHelper rds_setTemp:_cirSlider.value control_number:_roomModel.control_number success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showCenterToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showCenterToast:@"连接服务器失败"];
    }];
}

- (IBAction)onFanSliderValueChanged:(RDSlider *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    // 四舍五入 1~5挡位
    int value = round(sender.value);
    if (value < 1) value = 1;
    sender.value = value;
}

- (IBAction)onFanSliderValueDidChanged:(RDSlider *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_gcdTimer restartTimer];// 重新开始轮询
    [self p_sendFanSpeed:sender.value];
}

- (void)p_onSliderTap:(UITapGestureRecognizer *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_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{
    
    [RDSDemoApiHelper rds_setSpeed:value control_number:_roomModel.control_number success:^(id responseObject) {

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

// 新风开关
- (IBAction)onNewAirPowerAction:(UIButton *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_gcdTimer restartTimer];// 重新开始轮询
    
    sender.selected = !sender.isSelected;
    
    
    [RDSDemoApiHelper rds_setNewFanPower:sender.isSelected control_number:_roomModel.control_number success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showCenterToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showCenterToast:@"连接服务器失败"];
    }];
}

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

- (IBAction)onSleepAction:(UIButton *)sender {
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    [_gcdTimer restartTimer];// 重新开始轮询
    
    sender.selected = !sender.isSelected;
    
    [RDSDemoApiHelper rds_setSleepPower:sender.isSelected control_number:_roomModel.control_number success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showCenterToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showCenterToast:@"连接服务器失败"];
    }];
    
}

// 定时
- (IBAction)onTimingAction:(UIButton *)sender {
    
    if(!_roomModel.power) {
        [RDSHudShower showCenterToast:@"请先开机再进行其他操作"];
        return;
    }
    
    if(!sender.isSelected){
        if(_selectTimer == nil || _selectTimer.floatValue == 0){
            _selectTimer = @0.5;
        }
        [self presentViewController:self.timerAlert animated:YES completion:nil];
    }else{
        if(_selectTimer == nil){
            _selectTimer = @0;
        }
        [self timerSelect];
    }
    
    
}

- (SPAlertController *)timerAlert{
    if (!_timerAlert){
        RDS_WEAKSELF(weakSelf)
        SPAlertController *alertController = [SPAlertController alertControllerWithTitle:@"定时关闭" message:@"" preferredStyle:SPAlertControllerStyleAlert animationType:SPAlertAnimationTypeDefault];
        
        UIPickerView *timerPick = [[UIPickerView alloc] init];
        timerPick.delegate = self;
        timerPick.dataSource = self;
        NSMutableArray *data = [NSMutableArray array];
        for (CGFloat i = 0.5; i<=24; i+=0.5) {
            [data addObject:@(i)];
        }
        self.timerData = data;
        _selectTimer = @(0.5);
        [timerPick selectRow:0 inComponent:0 animated:NO];
        
        UILabel *h = [[UILabel alloc] initWithFrame:CGRectMake(timerPick.rds_centerX+15, timerPick.rds_centerY-10, 20, 20)];
        h.text = @"h";
        h.textColor = RDSGreenColor;
        h.font = [UIFont systemFontOfSize:18];
        [timerPick addSubview:h];
        
        // 插入一个view
        [alertController insertComponentView:timerPick];
        
        SPAlertAction *action1 = [SPAlertAction actionWithTitle:@"取消" style:SPAlertActionStyleDefault handler:nil];
        SPAlertAction *action2 = [SPAlertAction actionWithTitle:@"确定" style:SPAlertActionStyleDefault handler:^(SPAlertAction * _Nonnull action) {
            [weakSelf timerSelect];
        }];
        
        [alertController addAction:action1];
        [alertController addAction:action2];
        _timerAlert = alertController;
    }
    return _timerAlert;
}

- (void)timerSelect{
    
    [_gcdTimer restartTimer];// 重新开始轮询
    
    _timingBtn.selected = !_timingBtn.isSelected;
    
    NSString *timingStr;
    NSString *selectTimer = [NSString stringWithFormat:@"%@h",_selectTimer];
    timingStr = _timingBtn.isSelected ? selectTimer : @"关";
    _timingLab.text = [NSString stringWithFormat:@"定时：%@",timingStr];
    
    
    [RDSDemoApiHelper rds_setTimer:_selectTimer onOff:_timingBtn.isSelected control_number:_roomModel.control_number success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showCenterToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showCenterToast:@"连接服务器失败"];
    }];
}

#pragma mark pickerView  delegate
//滚动选中的行
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    _selectTimer = _timerData[row];
}

//每行显示的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    CGFloat fHour = [_timerData[row] floatValue];
    NSString *str = [NSString stringWithFormat:@"%.1f",fHour];
    return str;
}

//列宽
//-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
//
//    return 100;
//}

#pragma mark pickerView  dataSource
// 多少组
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// 行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _timerData.count;
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//    
//    UILabel *lbl = (UILabel *)view;
//
//    if (lbl == nil) {
//        lbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)];
//        //在这里设置字体相关属性
//        lbl.font = [UIFont systemFontOfSize:22];
//        lbl.textColor = RDSGreenColor;
//        lbl.textAlignment = NSTextAlignmentCenter;
//        [lbl setBackgroundColor:[UIColor clearColor]];
//    }
//    //重新加载lbl的文字内容
//    lbl.text = [self pickerView:pickerView titleForRow:row forComponent:component];
//    
//    // 去掉选中行背景灰色
//    if(pickerView.subviews.count > 0){
//        pickerView.subviews[1].backgroundColor = UIColor.clearColor;
//    }
//
//    return lbl;
//
//}

#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_getRoomStatus{
    
    RDS_WEAKSELF(weakSelf)
    [self.roomModel rds_getRoomStatusFinished:^(NSError * error) {
        [weakSelf p_refreshUI];
    }];
}

- (void)p_refreshUI{
    
    RDS_WEAKSELF(weakSelf)
    dispatch_async(dispatch_get_main_queue(), ^{
        
        // 用户拖动的时候不刷新
        if(!weakSelf.cirSlider.isTouchInside){
            weakSelf.cirSlider.value = weakSelf.roomModel.set_temp;
            weakSelf.airTempLab.text = @(weakSelf.roomModel.set_temp).description;
        }
        if (!weakSelf.fanSlider.isTouchInside){
            [weakSelf.fanSlider setValue:weakSelf.roomModel.fan_speed animated:YES];
        }
        
        [weakSelf.modeView setMode:weakSelf.roomModel.mode];
        
        
        weakSelf.roomTempLab.text = [NSString stringWithFormat:@"%d℃", weakSelf.roomModel.temperature];
        weakSelf.roomHumidityLab.text = [NSString stringWithFormat:@"%d%%", weakSelf.roomModel.humidity];
        weakSelf.roomPm25Lab.text = [NSString stringWithFormat:@"%d", weakSelf.roomModel.air_quality];
        weakSelf.roomCo2Lab.text = [NSString stringWithFormat:@"%d", weakSelf.roomModel.co2];
        weakSelf.powerBtn.selected = weakSelf.roomModel.power;
        weakSelf.newairBtn.selected = weakSelf.roomModel.new_fan;
        weakSelf.timingBtn.selected = weakSelf.roomModel.timer_status;
        weakSelf.sleepBtn.selected = weakSelf.roomModel.sleep_mode;
        
        
        NSString *mode;
        switch (weakSelf.roomModel.mode) {
            case 0:
                mode = @"制冷";
                break;
            case 1:
                mode = @"制热";
                break;
            case 2:
                mode = @"除湿";
                break;
            case 3:
                mode = @"送风";
                break;
            case 4:
                mode = @"加湿";
                break;
            default:
                break;
        }
        NSString *speed;
        switch (weakSelf.roomModel.fan_speed) {
            case 1:
                speed = @"一档";
                break;
            case 2:
                speed = @"二档";
                break;
            case 3:
                speed = @"三档";
                break;
            case 4:
                speed = @"四档";
                break;
            case 5:
                speed = @"五档";
                break;
                
            default:
                break;
        }
        
        weakSelf.modeLab.text = [NSString stringWithFormat:@"%@ %@", mode, speed];
        
        
        NSString *selectTimer = [NSString stringWithFormat:@"%@h",weakSelf.roomModel.duration];
        if (!weakSelf.roomModel.timer_status) selectTimer = @"关";
        weakSelf.timingLab.text = [NSString stringWithFormat:@"定时：%@",selectTimer];
    });

    
}



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

@end
