//
//  RDSHomeInfoVC.m
//  Temperature
//
//  Created by RD on 2023/2/1.
//

#import "RDSHomeInfoVC.h"
#import "RDSHomeInfoCell.h"
#import "RDSAddMemberVC.h"

static NSString * const RDSHomeInfoCellID = @"RDSHomeInfoCell";
@interface RDSHomeInfoVC ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *homeNameLab;
@property (weak, nonatomic) IBOutlet UIImageView *homeNameIcon;
@property (weak, nonatomic) IBOutlet UILabel *localLab;
@property (weak, nonatomic) IBOutlet UILabel *gatewayLab;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *delHomeBtn;
@property (nonatomic, strong) UIBarButtonItem *editBtn;
@property (nonatomic, strong) UIBarButtonItem *finishBtn;
@property (nonatomic, assign) BOOL isEdit;// 是否在编辑


@end

@implementation RDSHomeInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"家庭信息维护";
    
    [self p_navEditItem];
    [self p_setupCollectionView];
    
    [self p_refreshUI];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self refreshHomeInfo];
}

- (void)p_refreshUI{
    _homeNameLab.text = _home.name;
    _localLab.text = _home.city;
    _gatewayLab.text = _home.gateway;
    [_collectionView reloadData];
}

- (void)refreshHomeInfo{
    RDS_WEAKSELF(weakSelf)
    [RDSHomeModel rds_getHomeDetailWithHomeId:_home.record_id finished:^(RDSHomeModel * home, NSError * error) {
        
        if(error == nil){
            weakSelf.home = home;
            [weakSelf p_refreshUI];
        }
        
    }];
}

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

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

- (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{
    
    _isEdit = YES;
    [self p_navFinishItem];
    
    _delHomeBtn.hidden = NO;
    _homeNameIcon.hidden = NO;
    _homeNameLab.highlighted = YES;
    
    [_collectionView reloadData];
}

// 完成
- (void)p_onEitdFinishBtn{
    
    _isEdit = NO;
    [self p_navEditItem];
    
    _delHomeBtn.hidden = YES;
    _homeNameIcon.hidden = YES;
    _homeNameLab.highlighted = NO;
    
    [_collectionView reloadData];
}

- (IBAction)onRenameClick:(id)sender {
    
    if(!_isEdit) return;
    
    RDS_WEAKSELF(weakSelf)
    [self rds_alertInputTitle:@"修改家庭名称" msg:nil placeholder:_home.name doneAction:^(NSString *name) {
        [weakSelf p_updateHomeName:name];
        TheDataManager.currentUser.user_name = name;
    }];
}

- (void)p_updateHomeName:(NSString *)name{
    
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_updateHomeInfoWithHomeId:_home.record_id name:name city:nil success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 0) {
            [weakSelf refreshHomeInfo];
        } else{
            [RDSHudShower showErrorWithStatus:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}

// 删除家庭
- (IBAction)delHomeClick:(id)sender {
    
    RDS_WEAKSELF(weakSelf)
    [TheAlertCtrl rds_alertWithTitle:@"提示" message:@"删除家庭将清空该家庭下的所有数据，确认删除？" cancel:@"取消" sure:@"删除家庭" cancelColor:nil sureColor:RDSRedColor cancelAction:nil sureAction:^{
        [weakSelf p_delHome];
    }];
}

- (void)p_delHome{
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_delHomeWithHomeId:_home.record_id success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 0) {
            [RDSHudShower showBottomToast:@"删除成功"];
            [weakSelf popViewControllerAnimated:YES];
        } else{
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}


#pragma mark - UICollectionView
- (void)p_setupCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(44, 44);
    layout.minimumLineSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerNib:[UINib nibWithNibName:RDSHomeInfoCellID bundle:nil] forCellWithReuseIdentifier:RDSHomeInfoCellID];
    
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    
    if(indexPath.row == _home.member.count){
        RDSAddMemberVC *vc = [[RDSAddMemberVC alloc] init];
        vc.homeId = self.home.record_id;
        [self pushViewController:vc animated:YES];
    }
    else{
        if(_isEdit && indexPath.row != 0){
            // 编辑时删除成员
            [self p_delMemberAlertWithUserId:_home.member[indexPath.row].user_id];
        }
    }
    
}

// 删除成员弹窗
- (void)p_delMemberAlertWithUserId:(NSString *)user_id{
    
    RDS_WEAKSELF(weakSelf)
    [TheAlertCtrl rds_alertWithTitle:@"删除权限" message:@"确认删除此用户控制权限吗？" cancel:@"取消" sure:@"删除" cancelColor:nil sureColor:RDSRedColor cancelAction:nil sureAction:^{
        [weakSelf p_delMemberWithUserId:user_id];
    }];
    
}

// 删除成员
- (void)p_delMemberWithUserId:(NSString *)user_id{
    
    RDS_WEAKSELF(weakSelf)
    [RDSHudShower showWithStatus:@"加载中" autoDismiss:NO];
    [RDSDemoApiHelper rds_delMemberWithHomeId:_home.record_id user_id:user_id success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 0) {
            [RDSHudShower showCenterToast:@"删除成功"];
            [weakSelf refreshHomeInfo];
        } else{
            [RDSHudShower showErrorWithStatus:responseObject[@"message"]];
        }
        
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _home.member.count+1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    RDSHomeInfoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:RDSHomeInfoCellID forIndexPath:indexPath];
    
    
    if(indexPath.row == _home.member.count){
        cell.isAddBtn = YES;
    }else{
        cell.isAddBtn = NO;
        cell.photo = _home.member[indexPath.row].photo;
    }
    cell.isFirstCell = indexPath.row == 0 ? YES : NO;
    cell.isEditing = _isEdit;
    return cell;
}

@end
