//
//  RDSHomeVC.m
//  Temperature
//
//  Created by RD on 2022/10/24.
//

#import "RDSHomeVC.h"
#import "RDSHomeTopView.h"
#import "RDSHomeSceneView.h"
#import "RDSHomeRoomView.h"
#import "RDSRoomCell.h"
#import "RDSAddRoomView.h"
#import "RDSSelectDeviceMainVC.h"
#import "RDSAirControlVC.h"
#import "RDSSubControlVC.h"
#import <MJRefresh/MJRefresh.h>
#import "RDSMyInfoVC.h"
#import "RDSSetPwdVC.h"
#import "RDSMapHelper.h"
#import "UIImageView+webImage.h"
#import "WeatherModel.h"
#import "RDSMemberModel.h"
#import "RDSRoomModel.h"
#import "GCDTimer.h"// 轮询定时器
#import "RDSControlWebVC.h"

static NSString * const RDSRoomCellID = @"RDSRoomCellID";
@interface RDSHomeVC ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionReusableView *footerView;
@property (nonatomic, strong) UICollectionReusableView *headerView;

@property (nonatomic, strong) RDSHomeTopView *topView;
@property (nonatomic, strong) RDSHomeSceneView *sceneView;
@property (nonatomic, strong) RDSAddRoomView *addView;
@property (nonatomic, strong) GCDTimer *gcdTimer;// 定时轮询
@end

@implementation RDSHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 隐藏导航栏
    self.fd_prefersNavigationBarHidden = YES;
    
    
    [self p_getCurrentUserInfo];
//    [self p_getHomeList];
    [self p_setUpTimer];// 初始化轮询
    [self p_setupCollectionView];
    
    
    [kNotificationCenter addObserver:self selector:@selector(p_refreshUserInfo)name:RDSUpdateUserInfoNotice object:nil];
    
    if(TheDataManager.isFirstLogin){
        RDSSetPwdVC *vc = [[RDSSetPwdVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self pushViewController:vc animated:YES];
    }
}

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

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

- (void)p_getCurrentUserInfo{
    RDS_WEAKSELF(weakSelf)
    [RDSUserInfoModel rds_getCurrentUserInfoFinished:^(NSError *error) {
        if (!error) {
            [weakSelf p_refreshUserInfo];
            [weakSelf p_getHomeDetail];
            [weakSelf p_getWeather];
            [weakSelf p_getWelcomeMessage];
        }
    }];
}

//- (void)p_getHomeList {
//    [RDSHomeModel rds_getHomeListIsAdmin:NO finished:nil];
//}

- (void)p_getWeather{
    RDS_WEAKSELF(weakSelf)
    [WeatherModel rds_getWeatherFinished:^(WeatherModel * _Nonnull weather, NSError * _Nonnull error) {
        weakSelf.topView.model = weather;
    }];
}

- (void)p_getWelcomeMessage {
    RDS_WEAKSELF(weakSelf)
    [RDSSystemParameterModel rds_getWelcomeMessageFinished:^(RDSSystemParameterModel * _Nullable systemParameter, NSError * _Nullable error) {
        weakSelf.topView.systemParameter = systemParameter;
    }];
}

// 弃用
- (void)p_getRoomList{
    RDS_WEAKSELF(weakSelf)
    [RDSRoomModel rds_getRoomListFinished:^(NSError * _Nonnull error) {
        
        weakSelf.addView.hidden = (BOOL)TheDataManager.rooms.count;
        
        [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(kNULLString(home.city)){
            [weakSelf p_userLocation];
        }
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView reloadData];
    }];
}

- (void)p_userLocation{
    RDS_WEAKSELF(weakSelf)
    [TheMapHelper rds_startLocationSevice:^(RDSUserLocation *userLocation) {
        [weakSelf p_updateLocation];
    }];
}

- (void)p_updateLocation{
    RDS_WEAKSELF(weakSelf)
    if(kNULLString(TheMapHelper.userLocation.cityString)){
        return;
    }
    
    [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(@"更新城市成功");
            
            [weakSelf p_getWeather];
        } else{
            DDLog(@"更新城市失败:%@",responseObject[@"message"]);
        }
    } failure:^(NSError *error) {
        
    }];
}


- (void)p_refreshUserInfo{
    
    RDS_WEAKSELF(weakSelf)
    
    weakSelf.topView.title = [NSString stringWithFormat:@"欢迎回来，%@！",TheDataManager.currentUser.user_name];
    
    if (!TheDataManager.currentUser.headImg) {
        [TheDataManager.currentUser rds_getHeadImgFinished:^(NSError *error) {
            [weakSelf.topView.headBtn setImage:TheDataManager.currentUser.headImg forState:UIControlStateNormal];
        }];
    }else{
        [weakSelf.topView.headBtn setImage:TheDataManager.currentUser.headImg forState:UIControlStateNormal];
    }
    

}

// 定时轮询
- (void)p_setUpTimer{
    
    self.gcdTimer = [[GCDTimer alloc] init];
    RDS_WEAKSELF(weakSelf)
    [_gcdTimer scheduledTimerWithTimeInterval:3 afterTime:3 repeats:YES block:^{
        [weakSelf p_getHomeDetail];
    }];
}


#pragma mark - UI

// 顶部视图
- (void)p_setupTopView{
    
    // 375 217.5
    CGFloat viewH = 206;//kSCALE_WIDTH_6*222;

    RDSHomeTopView *view = [RDSHomeTopView rds_loadViewFromNib];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, viewH);
    [self.footerView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.footerView);
        make.height.equalTo(@(viewH));
        make.left.equalTo(self.footerView);
        make.right.equalTo(self.footerView);
    }];
    self.topView = view;
    RDS_WEAKSELF(weakSelf)
    view.onHeadClick = ^{
        RDSMyInfoVC *vc = [[RDSMyInfoVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [weakSelf pushViewController:vc animated:YES];
    };
    
    
    
}





// 场景先不做
- (void)p_setupSceneView{
    
    RDSHomeSceneView *scenesView = [[RDSHomeSceneView alloc] init];
    [self.footerView addSubview:scenesView];
    self.sceneView = scenesView;
    //scenesView.delegate = self;
    [scenesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom).offset(10);
        make.height.equalTo(@90);
        make.left.equalTo(self.footerView);//.offset(10);
        make.right.equalTo(self.footerView);//.offset(-10);
    }];
    
    NSArray *scenes = @[@1,@2,@3,@4,@5,@6];
    scenesView.scenes = scenes;
}

- (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.4));
        }];
        
        RDS_WEAKSELF(weakSelf)
        _addView.onAddClick = ^{
            RDSSelectDeviceMainVC *vc = [[RDSSelectDeviceMainVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [weakSelf pushViewController:vc animated:YES];
            
        };
    }
    return _addView;
}


- (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(0, 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 = RDSViewBgColor;
    [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);//.offset(20);
        make.right.equalTo(self.view);//.offset(-20);
        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);
        }
    }];
    
    
    //注册行头
//    [self.collectView registerNib:[UINib nibWithNibName:@"NibName" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReuseIdentifier"];
    //或者
       [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer"];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(p_getCurrentUserInfo)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.collectionView.mj_header = header;
    
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(p_longPressMethod:)];
//    longPress.minimumPressDuration = 0.3f;
//    [collectionView addGestureRecognizer:longPress];
}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    RDSRoomModel *roomModel = TheDataManager.rooms[indexPath.row];
    switch (roomModel.deviceType) {
        case RDSDeviceType_MasterController: {
            RDSAirControlVC *vc = [[RDSAirControlVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.roomModel = roomModel;
            [self pushViewController:vc animated:YES];
            break;
        }
        case RDSDeviceType_SubController: {
            RDSSubControlVC *vc = [[RDSSubControlVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.roomModel = roomModel;
            [self pushViewController:vc animated:YES];
            break;
        }
        default:{
            RDSControlWebVC *vc = [[RDSControlWebVC alloc] initWithRecordId:roomModel.record_id code:roomModel.code];
            [self pushViewController:vc animated:YES];
        }
    }
    
    
}

#pragma mark - UICollectionViewDataSource

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if(section == 0){// 第一组用来做悬停顶部视图
        return 0;
    }
    return TheDataManager.rooms.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    RDSRoomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:RDSRoomCellID forIndexPath:indexPath];
    
    RDSRoomModel *model;
    if(TheDataManager.rooms.count > indexPath.row){
        model = TheDataManager.rooms[indexPath.row];
    }
    cell.model = model;
    
    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:@"连接服务器失败"];
            }];
        }
    };
    
    return cell;
}

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





// 设置header尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if(section == 0){
        return CGSizeZero;
    }
    
    return CGSizeMake(SCREEN_WIDTH, 50);
}

// 设置footer尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    if(section == 0){
        return CGSizeMake(SCREEN_WIDTH, 306-60-30);// -60是场景的高度，场景先不做
    }
    
    return CGSizeZero;
}



//sectionheader
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"Footer" forIndexPath:indexPath];
        footerView.backgroundColor = UIColor.clearColor;
        if(self.topView == nil){
            self.footerView = footerView;
            [self p_setupTopView];
            //[self p_setupSceneView]; //先不做场景功能
        }
        return footerView;
    }
    
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header" forIndexPath:indexPath];
    headView.backgroundColor = RDSViewBgColor;
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 20)];
    title.text = @"我的房间";
    title.font = [UIFont boldSystemFontOfSize:18];
    [headView addSubview:title];
    
    return headView;
}



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





@end
