//
//  RDSRoomVC.m
//  Temperature
//
//  Created by RD on 2022/11/2.
//

#import "RDSRoomVC.h"
#import "RDSRoomCell.h"
#import "RDSAirControlVC.h"
#import "RDSSubControlVC.h"
#import "RDSAddRoomView.h"
#import "RDSResetDeviceVC.h"
#import <MJRefresh/MJRefresh.h>
#import "GCDTimer.h"// 轮询定时器
#import "RDSSelectDeviceMainVC.h"

static NSString * const RDSRoomCellID = @"RDSRoomCellID";
@interface RDSRoomVC ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) RDSAddRoomView *addView;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) UIBarButtonItem *addBtn;
@property (nonatomic, strong) UIBarButtonItem *editBtn;
@property (nonatomic, strong) UIBarButtonItem *finishBtn;
@property (nonatomic, assign) BOOL isEdit;// 是否在编辑房间
@property (nonatomic, strong) GCDTimer *gcdTimer;
@end

@implementation RDSRoomVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"我的房间";
    
    [self p_navAddRoomItem];
    [self p_navEditItem];
    [self p_setupCollectionView];
    [self p_setUpTimer];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [_gcdTimer resumeTimer];// 开始轮询
}

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

- (void)p_navAddRoomItem{
    [self.navigationItem setLeftBarButtonItem:self.addBtn];
}

- (void)p_navEditItem{
    [self.navigationItem setRightBarButtonItem:self.editBtn];
}

- (void)p_navFinishItem{
    [self.navigationItem setRightBarButtonItem:self.finishBtn];
}

- (UIBarButtonItem *)addBtn{
    if(_addBtn == nil){
        UIBarButtonItem *item = [RDSBarButtonItem barButtonItemWithTitle:@"添加" color:kTextColor target:self action:@selector(p_onAddRoomBtn)];
        _addBtn = item;
    }
    return _addBtn;
}

- (UIBarButtonItem *)editBtn{
    if(_editBtn == nil){
        UIBarButtonItem *item = [RDSBarButtonItem barButtonItemWithTitle:@"编辑" color:kTextColor target:self action:@selector(p_onEitdBtn)];
        _editBtn = item;
    }
    return _editBtn;
}

- (UIBarButtonItem *)finishBtn{
    if(_finishBtn == nil){
        UIBarButtonItem *item = [RDSBarButtonItem barButtonItemWithTitle:@"完成" color:RDSGreenColor target:self action:@selector(p_onEitdFinishBtn)];
        _finishBtn = item;
    }
    return _finishBtn;
}

- (void)p_onEitdBtn{
    
    [_gcdTimer pauseTimer];// 暂停轮询
    
    _isEdit = YES;
    [self p_navFinishItem];
    self.tabBarController.tabBar.hidden = YES;
    [self.collectionView reloadData];
}

- (void)p_onEitdFinishBtn{
    
    [_gcdTimer resumeTimer];// 开始轮询
    
    _isEdit = NO;
    [self p_navEditItem];
    self.tabBarController.tabBar.hidden = NO;
    [self.collectionView reloadData];
}

- (void)p_onAddRoomBtn{
    RDSSelectDeviceMainVC *selectDeviceMainVC = [[RDSSelectDeviceMainVC alloc] init];
    selectDeviceMainVC.hidesBottomBarWhenPushed = YES;
    [self pushViewController:selectDeviceMainVC animated:YES];
//    RDSResetDeviceVC *vc = [[RDSResetDeviceVC alloc] init];
//    vc.hidesBottomBarWhenPushed = YES;
//    [self pushViewController:vc animated:YES];
}

- (void)p_setupCollectionView {
        
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat viewW = SCREEN_WIDTH - 16 * 2;
    layout.itemSize = CGSizeMake(viewW, 80);
    layout.minimumLineSpacing = 8;
    layout.sectionInset = UIEdgeInsetsMake(16, 16, 16, 16);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionHeadersPinToVisibleBounds = YES;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.backgroundColor = UIColor.clearColor;
    [collectionView registerClass:[RDSRoomCell class] forCellWithReuseIdentifier:RDSRoomCellID];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = NO;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
        
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
//            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.equalTo(self.view);
            
        }
    }];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(p_getHomeDetail)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.collectionView.mj_header = header;
}

// 弃用
//- (void)reloadData{
//
//    RDS_WEAKSELF(weakSelf)
//    [RDSRoomModel rds_getRoomListFinished:^(NSError * _Nonnull error) {
//
//        weakSelf.addView.hidden = (BOOL)TheDataManager.rooms.count;
//        if(TheDataManager.rooms.count == 0){
//            [weakSelf p_onEitdFinishBtn];
//        }
//
//        [weakSelf.collectionView.mj_header endRefreshing];
//        [weakSelf.collectionView reloadData];
//    }];
//}

- (void)p_getHomeDetail{
    
    RDS_WEAKSELF(weakSelf)
    [RDSHomeModel rds_getHomeDetailWithHomeId:TheDataManager.current_home_id finished:^(RDSHomeModel *home, NSError *error) {
        weakSelf.addView.hidden = (BOOL)TheDataManager.rooms.count;
        if(TheDataManager.rooms.count == 0){
            [weakSelf p_onEitdFinishBtn];
        }
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView reloadData];
    }];
}

#pragma mark - 轮询 开始-暂停要一一对应
// 定时轮询 3秒一次
- (void)p_setUpTimer{
    
    self.gcdTimer = [[GCDTimer alloc] init];
    RDS_WEAKSELF(weakSelf)
    [_gcdTimer scheduledTimerWithTimeInterval:3 afterTime:0 repeats:YES block:^{
        [weakSelf p_getHomeDetail];
    }];
}

- (void)p_restartTimer{
    [_gcdTimer restartTimer];
}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    if (_isEdit) return;

    RDSRoomModel *roomModel = TheDataManager.rooms[indexPath.row];
    if(roomModel.is_master){
        RDSAirControlVC *vc = [[RDSAirControlVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.roomModel = roomModel;
        [self pushViewController:vc animated:YES];
    }
    else{
        RDSSubControlVC *vc = [[RDSSubControlVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.roomModel = roomModel;
        [self pushViewController:vc animated:YES];
    }
    
    

}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return TheDataManager.rooms.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RDSRoomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:RDSRoomCellID forIndexPath:indexPath];
    
    RDSRoomModel *model = TheDataManager.rooms[indexPath.row];
    cell.model = model;
    cell.isEdit = _isEdit;
    
    RDS_WEAKSELF(weakSelf)
    cell.onPowerClick = ^(BOOL onOff) {
        // 开关
        if(model.is_master){
            [RDSDemoApiHelper rds_setPower:onOff control_number:model.control_number success:^(id responseObject) {
                if ([responseObject[@"code"] intValue] != 0) {
                    [RDSHudShower showBottomToast:responseObject[@"message"]];
                }
            } failure:^(NSError *error) {
                [RDSHudShower showBottomToast:@"连接服务器失败"];
            }];
        }
        else{
            [RDSDemoApiHelper rds_setSubDevPower:onOff control_number:model.control_number success:^(id responseObject) {
                if ([responseObject[@"code"] intValue] != 0) {
                    [RDSHudShower showBottomToast:responseObject[@"message"]];
                }
            } failure:^(NSError *error) {
                [RDSHudShower showBottomToast:@"连接服务器失败"];
            }];
        }
    };
    cell.onDelClick = ^{
        [weakSelf p_onDelAction:model.record_id];
    };
    
    return cell;
}

- (void)p_onDelAction:(NSString *)roomId{
    
    RDS_WEAKSELF(weakSelf)
    [self rds_alertMessage:@"确定删除所选房间吗？" doneAction:^{
        [RDSRoomModel rds_delRoomId:roomId finished:^(NSError * _Nonnull error) {
            [weakSelf p_getHomeDetail];
        }];
    }];
}

// 不允许高亮
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    
    RDSRoomCell *cell = (RDSRoomCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.highlighted = NO;
}


- (RDSAddRoomView *)addView{
    if(_addView == nil){
        _addView = [RDSAddRoomView rds_loadViewFromNib];
        _addView.hidden = YES;
        [self.collectionView addSubview:_addView];
        [_addView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);//.offset(20);
            make.right.equalTo(self.view);//.offset(-20);
            make.height.equalTo(@300);
            make.top.equalTo(@(SCREEN_HEIGHT*0.2));
        }];
        
        RDS_WEAKSELF(weakSelf)
        _addView.onAddClick = ^{
            [weakSelf p_onAddRoomBtn];
        };
    }
    return _addView;
}


- (void)dealloc{
    
    // 取消轮询
    [_gcdTimer stopTimer];
    
    DDLog(@"dealloc~~");
    
}
@end
