//
//  HomeMemberViewController.m
//  kneet
//
//  Created by Jason Lee on 6/15/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "RequestHandler.h"
#import "LoginModel.h"

#import "CustomButton.h"
#import "CustomLabel.h"
#import "CustomLabelButton.h"
#import "CustomImageView.h"
#import "CustomCheckBox.h"
#import "CustomAlertView.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"

#import "HomeMemberViewController.h"
#import "JYPullToRefreshController.h"

#define kfMemberTableViewCellHeight 100.0f
#define kiCellInset 5
#define kiCellItem 2
#define kiCellRatio 74
#define kiCellDivision 3

#define MASTER_TRANSFER_REQUEST @"R"
#define MASTER_TRANSFER_CANCEL  @"C"

/**
 
 Head Text
 - 참여 , 대기 Text Color : kUITextColor01
 - Count Text Color     : kUITextColor03
 
 Member List
 - 멤버 닉네임 Text Color   : kUITextColor01
 - 멤버 ID   Text Color   : kUITextColor03
 - 멤버 상태  Text Color
 - 초대 수락된 멤버      : kUITextColor02
 - 초대 수락 안된 멤버    : kUITextColor01
 - 멤버 초대 Text Color     : kUITextColor01
 
 **/

@interface HomeMemberCollectionCell () {
    
}

@property (weak, nonatomic) NSIndexPath *indexPath;

@end


@implementation HomeMemberCollectionCell

- (void)awakeFromNib {
//    _chkSelect.hidden = YES;
    _lblMemID.hidden = YES;
    _btnProfile.layer.frame = CGRectMake(0, 0, _btnProfile.frame.size.width, _btnProfile.frame.size.width);
    _btnProfile.layer.masksToBounds = YES;
    _btnProfile.layer.cornerRadius = _btnProfile.frame.size.width/2;
}

@end

@implementation HomeMemberAddCollectionCell

@end


@interface HomeMemberViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
    NSArray<HomeMemberModel> *_memberList;
    HomeMemberListModel *_responseInfo;
    
    BOOL _isNotFirstLoading, _isDeleteMode, _isMasterTransferMode;
    NSInteger _deviceFlag;
    NSString *_masterNickname;
}

@property (strong, nonatomic) JYPullToRefreshController *refreshController;

@end


#pragma mark - Class Definition

@implementation HomeMemberViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    [self initProperties];
    [self initUI];
    
    //마스터 권한 양도 push
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kMasGradeNoti
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notichageGrade:)
                                                 name:kMasGradeNoti
                                               object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kMasGradeNoti
                                                  object:nil];
}

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

    [self prepareViewDidLoad];

}


- (void)initProperties {
    _deviceFlag = IS_IPHONE_6P ? 2 : 2;
}

- (void)initUI {

    //set tableview option
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.alwaysBounceVertical = YES;

    [_btnClose setHidden:YES];
    [_btnOption setHidden:NO];
    
//    [self setThingsPopoverOptions];
    [self setMoreBtnArray];
    [self initRefreshController];
    
}

- (void)initRefreshController {
    //set refresh controls
    __weak typeof(self) weakSelf = self;
    self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.collectionView];
    self.refreshController.pullToRefreshHandleAction = ^{
        [weakSelf requestHomeMemberList];
    };
}


- (void)setThingsPopoverOptions {
    //set Popover Contents
    __weak typeof(self) weakSelf = self;
    _popooverOptionArray = [[NSMutableArray alloc] init];

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil),
                                      @"iconName": @"img_bg_morepopup_icon_refresh",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(requestHomeMemberList)]}];

    if ([JDFacade facade].loginUser.level == 90) {
        
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"멤버 삭제", @"멤버 삭제"),
                                          @"iconName": @"img_bg_morepopup_icon_del",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
    } else {
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"멤버 탈퇴", @"멤버 탈퇴"),
                                          @"iconName": @"img_bg_morepopup_icon_del",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(leaveHomegroup)]}];
    }
}

- (void)setMoreBtnArray {
    _moreBtnArray = [NSMutableArray array];
    
    if (![[JDFacade facade].loginUser hasHomeHub]) {
        [_btnOption setHidden:YES];
    }
    
    NSLog(@"[JDFacade facade].loginUser.gradeCode : %@", [JDFacade facade].loginUser.gradeCode);
    
    if([[JDFacade facade].loginUser.gradeCode isEqualToString:KNEET_MEMBER_MASTER]) {
        for (int i = 0; i < 4; i++) {
            MoreBtnModel *btnModel;
            switch (i) {
                case 0:{
                    btnModel = [[MoreBtnModel alloc] initWithTyep:MasterTransfer isEnable:YES];
                    if (![[JDFacade facade].loginUser isHomehubOnline] || [self getNormalMemberCount] == 0) {
                        [btnModel setEnable:NO];
                    }
                }
                    break;
                case 1:
                    btnModel = [[MoreBtnModel alloc] initWithTyep:AddMember isEnable:YES];
                    break;
                case 2:
                    btnModel = [[MoreBtnModel alloc] initWithTyep:Del isEnable:YES];
                    break;
                case 3:
                    btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
                    break;
                    
                default:
                    break;
            }
            [_moreBtnArray addObject:btnModel];
        }
    }
    else {
        MoreBtnModel *btnModel = [[MoreBtnModel alloc] initWithTyep:Refresh isEnable:YES];
        [_moreBtnArray addObject:btnModel];
    }
}


- (void)prepareViewDidLoad {
    
    [self updateTitle];
    [self performSelector:@selector(requestHomeMemberList) withObject:nil afterDelay:0.0f];
}


- (void)updateTitle {
    
    NSInteger memberCount = _memberList ? [_memberList filteredArrayUsingPredicateFormat:@"memberTypeCode == %@", @"01"].count : 0;
    NSInteger invitationCount = _memberList ? [_memberList filteredArrayUsingPredicateFormat:@"memberTypeCode == %@", @"02"].count : 0;

    NSString *title = invitationCount > 0 ? [NSString stringWithFormat:@"참여 %zd / 대기 %zd", memberCount, invitationCount] : [NSString stringWithFormat:@"참여 %zd", memberCount];
    
    _lblTitle.text = title;
    
    if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
        
        [_mainView bringSubviewToFront:_addHubContainerView];
        _addHubContainerView.hidden = NO;
        _collectionView.hidden = YES;
        _btnOption.hidden = NO;
        _btnClose.hidden = YES;
        
        if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
            _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
            _imgvHubAlert.hidden = YES;
            
            _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
            
            _lblLeaveAccount.hidden = YES;
            _lblSimpleMemberInfo.hidden = YES;
            
        } else {//홈허브가 삭제됨.
            _lblTitle.text = @"홈허브 삭제됨";
            
            _imgvHubAlert.hidden = NO;
            _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
            
            _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
            
            if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
                _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
                _lblLeaveAccount.hidden = NO;
                _lblSimpleMemberInfo.hidden = NO;
                [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
                
                if (!_lblLeaveAccount.touchHandler) {
                    [_lblLeaveAccount addTouchEventHandler:^(id label) {
                        [self leaveHomegroup];
                    }];
                }
            }
        }
    } else {
        
        if (![JDFacade facade].loginUser.isHomehubOnline) {
            _imgvHubAlert.hidden = NO;
            _lblTitle.text = @"홈허브 오프라인";
            [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
            
        } else {
            _imgvHubAlert.hidden = YES;
        }
        
        [_mainView bringSubviewToFront:_collectionView];
        _addHubContainerView.hidden = YES;
        _collectionView.hidden = NO;
        _btnOption.hidden = NO;
    }
    
    if ([_lblTitle.text rangeOfString:@"참여"].location != NSNotFound) {
        [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"%zd", memberCount]];
        [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"대기 %zd", invitationCount]];
        [_lblTitle setColor:kUITextColor01 text:@"/ 대기"];
    }
    _btnClose.hidden = YES;
    _btnOption.hidden = NO;
    [self setMoreBtnArray];
}

- (void)updateHomeHubStatusToMembers {
    [self updateTitle];
}


- (IBAction)btnOptionTouched:(id)sender
{
    [self toggleOptionsWithArray:sender btnArray:_moreBtnArray];
}

- (IBAction)btnCloseTouched:(id)sender {
    if (_isDeleteMode) {
        [self toggleEditMode];
    }
    if (_isMasterTransferMode) {
        [self toggleMasterTransferMode:YES];
    }
}

- (NSInteger)getNormalMemberCount
{
    NSInteger result = 0;
    
    if (_memberList) {
        NSArray *_tmpFirst = [_memberList filteredArrayUsingPredicateFormat:@"memberTypeCode == %@", KNEET_MEMBER_TYPE_HOME];
        result = [_tmpFirst filteredArrayUsingPredicateFormat:@"gradeCode == %@", KNEET_MEMBER_SIMPLE].count;
    }
    return result;
}




- (void)returnMoreId:(id)moreButtonId{
    NSLog(@"moreButtonId : %@",moreButtonId);
}



- (IBAction)btnCloseEditModeTouched:(id)sender {
}

- (void)addNewMember {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeMemberAddViewController" storyboardName:@"HomeMember"];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)toggleMasterTransferMode:(BOOL)reload{
    
    _isMasterTransferMode = !_isMasterTransferMode;


    if(!_isMasterTransferMode) {

        [self updateTitle];
        
    } else {
        
        BOOL isToggle = YES;
        HomeMemberModel *requestMember;
        for (HomeMemberModel *memberInfo in _memberList) {
            if ([memberInfo.permissionTransferFlag isEqualToIgnoreCase:MASTER_TRANSFER_REQUEST]) {
                requestMember = memberInfo;
                isToggle = NO;
            }
        }
        
        if (isToggle) {
            _lblTitle.text = @"마스터 권한을 양도할 멤버 선택";
            _imgvHubAlert.hidden = YES;
            _btnClose.hidden = NO;
            _btnOption.hidden = YES;
        }
        else {
            NSString *name = requestMember.nickname;
            if ([requestMember.nickname isEmptyString]) {
                name = requestMember.memberId;
            }
            
            NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"%@멤버에게 신청된\n마스터 권한 양도를\n취소하시겠습니까?", @""), name];
            
            [[JDFacade facade] confirmTitle:NSLocalizedString(@"마스터 권한 양도 취소", @"마스터 권한 양도 취소") message:msg completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 0) {
                    [self requestMasterTransfer:requestMember.memberId isRequest:NO];
                }
            }];
        }
            
        
    }
    
    if (reload)
        [_collectionView reloadData];
        
}

- (void)toggleEditMode {
    
    _isDeleteMode = !_isDeleteMode;
    
    if (!_isDeleteMode) {
        for (HomeMemberModel *member in _memberList) {
            [[JDFacade facade] setCheckBoxStatus:@(NO) object:member];
        }
        [self updateTitle];
        
    } else {
        _lblTitle.text = @"멤버 삭제";
        _imgvHubAlert.hidden = YES;
        _btnClose.hidden = NO;
        _btnOption.hidden = YES;
    }
    
    [_collectionView reloadData];

//    _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width;
//    
//    [UIView animateWithDuration:kfAnimationDur animations:^{
//        [self.view layoutIfNeeded];
//    }];
}

- (void)leaveHomegroup {
    
    if (!_masterNickname) {
        
        NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_HOMEGROUP_MEMBERS aditional:nil];
//        NSString *path = [NSString stringWithFormat:API_GET_HOMEGROUP_MEMBERS, [[JDFacade facade].loginUser custId], [[JDFacade facade].loginUser ctrtGrpId]];
        
        [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[HomeMemberListModel class] completion:^(id responseObject) {
            if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
                return;
            }

            HomeMemberListModel *fetchedMemberList = (HomeMemberListModel *)responseObject;
            NSArray<HomeMemberModel> *homegrpMemberList = fetchedMemberList.ctrtGrpMemberList;
            
            if (homegrpMemberList && homegrpMemberList.count) {
                HomeMemberModel *master = [homegrpMemberList objectKey:@"gradeCode" eqaulToString:KNEET_MEMBER_MASTER];
                _masterNickname = master && master.nickname ? master.nickname : ksEmptyString;
                
                [self leaveHomegroup];
            }
            
        } failure:^(id errorObject) {
            
            JDErrorModel *error = (JDErrorModel *)errorObject;
            [[JDFacade facade] alert:error.errorMessage];
        }];

        return;
    }
    
    NSString *message = [NSString stringWithFormat:@"[%@]님의 홈그룹에서 탈퇴하시겠습니까?", _masterNickname];
    [[JDFacade facade] confirmTitle:@"멤버 탈퇴" message:message completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [self requestLeaveHomegroup];
        }
    }];
}





#pragma mark - UICollectionView Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger auth = [JDFacade facade].loginUser.level == 90 && !_isDeleteMode && _responseInfo.isRemainInvite; //마스터 권한이면서, 멤버초대 최대수를 넘지 않으며, 삭제모드가 아닐경우,
    //    NSInteger count = _memberList.count % _deviceFlag == 0 ? _memberList.count : _memberList.count + auth; //홀수일 경우, 멤버 초대 버튼을 추가해줌.
    NSInteger count = _memberList.count + auth; //항상 추가되도록 수정
    
    
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *rcell = nil;
    
    if (indexPath.row < _memberList.count) {
        HomeMemberCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCellIdentifier" forIndexPath:indexPath];
        
        HomeMemberModel *member = _memberList[indexPath.row];
        cell.indexPath = indexPath;
        
        [cell.btnProfile sd_setBackgroundImageWithURL:[NSURL URLWithString:[JDFacade facade].loginUser.profileImage] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
        
        cell.lblNickname.text = member.nickname;
        
        NSString *name = member.nickname;
        
        if ([name isEmptyString]) {
            cell.lblNickname.text = member.memberId;
        }
        //        cell.lblMemID.text = member.memberId;
        
        if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_HOME]) {
            cell.lblNickname.text = [NSString stringWithFormat:@"%@", cell.lblNickname.text];
            cell.lblNickname.textColor = kUITextColor01;
            
            NSString *strGradeName = NSLocalizedString(@"멤버",@"멤버");
            if ([member.gradeCode isEqualToIgnoreCase:KNEET_MEMBER_MASTER]) {
                strGradeName = NSLocalizedString(@"마스터",@"마스터");
            }
            
            cell.lblStatus.text = strGradeName;
            
            [cell.lblStatus setColor:kUITextColor02 text:cell.lblStatus.text];
            
        } else {
            
            if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_INV]) {//초대 대기중
                cell.lblStatus.text = @"초대 대기중";
            } else if ([member.memberTypeCode isEqualToString:@"21"]) {//초대 유효기간 종료
                cell.lblStatus.text = @"초대 무효";
            } else if ([member.memberTypeCode isEqualToString:@"22"]) {//답변 오류 제한 초과
                cell.lblStatus.text = @"답변 오류 제한 초과";
            } else if ([member.memberTypeCode isEqualToString:@"23"]) {//초대 거절
                cell.lblStatus.text = @"초대 거절";
            }
            
            [cell.lblStatus setColor:kUITextColor01 text:cell.lblStatus.text];
        }
        
        cell.btnCheck.value = member;
        cell.btnDelete.value = member;
        
        cell.btnCheck.hidden = !(_isMasterTransferMode && [member.gradeCode isEqualToString:KNEET_MEMBER_SIMPLE] && _memberList.count > 1);
        cell.btnCheck.value = member;
        //        cell.btnCheck.checked = [cell.btnCheck getCheckStatusFromValue];
        
        cell.btnDelete.hidden = !(_isDeleteMode && ![member.gradeCode isEqualToString:KNEET_MEMBER_MASTER] && _memberList.count > 1);
        cell.btnDelete.value = member;
        
        [cell.btnCheck addTarget:self action:@selector(btnTransferMaster:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnDelete addTarget:self action:@selector(btnDeleteMember:) forControlEvents:UIControlEventTouchUpInside];
        
        rcell = cell;
        
    } else {
        
        HomeMemberAddCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddCollectionCellIdentifier" forIndexPath:indexPath];
        
        if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [cell.btnAdd addTarget:self action:@selector(addNewMember) forControlEvents:UIControlEventTouchUpInside];
        }
        
        rcell = cell;
    }
    
    return rcell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(ViewWidth(_collectionView), (((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem) / kiCellDivision+(kiCellItem*kiCellItem));
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake((ViewWidth(_collectionView)-kiCellInset) / kiCellItem, ((ViewWidth(_collectionView)-kiCellInset)+kiCellRatio) / kiCellItem);
}

// Cell 사이 최소 간격
- (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return kiCellInset;
}

// Line 별 최소 간격
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return kiCellInset;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < _memberList.count) {
        HomeMemberCollectionCell *cell = (HomeMemberCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCellIdentifier" forIndexPath:indexPath];
        
        HomeMemberModel *member = _memberList[indexPath.row];
        
        cell.btnCheck.value = member;
        //        [cell.btnCheck checkBoxClicked];
    }
    
}

#pragma mark - UI Events

- (IBAction)btnDeleteOnEditModeTouched:(id)sender {
    if (!_isDeleteMode)
        return;
    
    NSMutableString *memberIds = [[NSMutableString alloc] init];
    NSMutableString *invitationHistIds = [[NSMutableString alloc] init];
    
    for (HomeMemberModel *member in _memberList) {
        if ([[[JDFacade facade] getCheckBoxStatus:member] boolValue]) {
            
            if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_HOME]) {//홈멤버일 경우,
                NSString *prefix = [memberIds isEmptyString] ? ksEmptyString : @",";
                [memberIds appendFormat:@"%@%@", prefix, member.memberId];
                
            } else if ([member.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_INV]) {//초대중일 경우,
                NSString *prefix = [invitationHistIds isEmptyString] ? ksEmptyString : @",";
                //                [invitationHistIds appendFormat:@"%@%@", prefix, member.invitationHistId];
                // TODO : 초대중일 경우에 처리하기
            }
        }
    }
    
    if ([memberIds isEmptyString] && [invitationHistIds isEmptyString]) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 멤버가 없습니다", @"선택된 멤버가 없습니다")];
        return;
    }
    
    CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:@"멤버를 삭제하시겠습니까?\n\n삭제된 멤버는 홈의 모든 기능을\n이용할 수 없게되며,\n참여 대기중인 사람은 초대가\n취소됩니다." delegate:nil OKButtonTitle:@"멤버삭제" cancelButtonTitle:@"취소"];
    [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [self requestDeleteMembers:memberIds invitations:invitationHistIds];
        }
    }];
}

- (IBAction)btnCloseOnEditModeTouched:(id)sender {
    [self toggleEditMode];
}

//- (IBAction)btnCoverIconTouched:(id)sender {
//
//    if (_selectedCoverIcon) {
//        [_selectedCoverIcon faceOffImage];
//    }
//
//    CustomButton *btn = (CustomButton *)sender;
//    _selectedCoverIcon = btn;
//    [_selectedCoverIcon faceOffImage];
//}

- (void)btnTransferMaster:(id)sender {
    HomeMemberModel *memberInfo = (HomeMemberModel *) ((CustomButton *)sender).value;
    NSLog(@"Member Info : %@", memberInfo);
    
    NSString *name = memberInfo.nickname;
    if ([name isEmptyString]) {
        name = memberInfo.memberId;
    }
    
    NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"%@멤버에게\n마스터 권한을\n양도하시겠습니까?", @""), name];
    
    [[JDFacade facade] confirmTitle:NSLocalizedString(@"마스터 권한 양도", @"마스터 권한 양도") message:msg completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self requestMasterTransfer:memberInfo.memberId isRequest:YES];
        }
    }];
}

- (void)btnDeleteMember:(id)sender {
    HomeMemberModel *memberInfo = (HomeMemberModel *) ((CustomButton *)sender).value;
    NSLog(@"Member Info : %@", memberInfo);
    NSString *memberId = @"";
    NSString *invitationId = @"";
    
    if ([memberInfo.memberTypeCode isEqualToString:KNEET_MEMBER_TYPE_INV]) {
        invitationId = memberInfo.nickname;
    } else {
        memberId = memberInfo.memberId;
    }
    NSString *name = memberInfo.nickname;
    if ([memberInfo.nickname isEmptyString]) {
        name = memberInfo.memberId;
    }
    
    NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"%@멤버를\n삭제하시겠습니까?", @""), name];
    
    CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:msg delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:@"취소"];
    [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [self requestDeleteMembers:memberId invitations:invitationId];
        }
    }];
    
}

#pragma mark - MoreButtonDelegate
-(void)moreBtnAction:(id)sender
{
    NSInteger tag = [(UIButton *)sender tag];
    NSLog(@"MoreBtn Action : %li", (long)tag);
    switch (tag) {
        case MasterTransfer:
        {
            // TODO : 마스터 권한 양도 모드로 진입
            [self toggleMasterTransferMode:YES];
        }
            break;
        case AddMember:
        {
            // TODO : 멤버초대 화면 띄우기
            [self addNewMember];
        }
            break;
        case Del:
        {
            // TODO : 멤버 삭제 모드로 진입
            [self toggleEditMode];
        }
            break;
        case Refresh:
        {
            [self requestHomeMemberList];
        }
            break;
            
        default:
            break;
    }
}



#pragma mark - noti
-(void)notichageGrade:(NSNotification *)notification {
    
    NSLog(@"notichageGrade : %@\n%@\n\n", self.navigationController.viewControllers, notification);
    
    if (notification.object == nil) {
        //보낸 마스터 양도 완료
        [self requestAutoLogin];
    }
    else {
        //마스터 양도 받음
        [self precessMasterTransfer:notification.object];
    }
}

- (void)precessMasterTransfer:(NSString*)message {
    
    [[JDFacade facade] confirmTitle:@"알림"
                            message:[NSString stringWithFormat:@"%@ 수락하시겠습니까?",message]
                         btnOKLabel:@"예"
                     btnCancelLabel:@"아니요"
                         completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                             
                             [self requestGradeAccept:buttonIndex == 0];
                         }];
}



#pragma mark - Main Logic api
//홈그룹 멤버 권한 양도 수락 거절
- (void)requestGradeAccept:(BOOL)accept{
    
    NSDictionary *parameter = @{@"status":accept ? @"T" : @"C"};
    
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_PUT_HOMEGROUP_GRADE];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path
                                              parameters:parameter
                                              modelClass:[JDJSONModel class] completion:^(id responseObject) {
                                                  
                                                  [self requestAutoLogin];
                                                 
                                                  
                                              } failure:^(id errorObject) {
                                                  
                                                  JDErrorModel *error = (JDErrorModel *)errorObject;
                                                  [[JDFacade facade] alert:error.errorMessage];
                                                  
                                              }];
}

//자동로그인 요청
- (void)requestAutoLogin {;
    
    LoginModel *tmpInfo = [[LoginModel alloc] init];
    tmpInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
    tmpInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
    
    SocketRequestModel *request = [[SocketRequestModel alloc] initWithMsgType:MSG_TYPE_AUTO_LOGIN];
    NSDictionary *param = @{@"Authorization": tmpInfo.authorization,
                            @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
                            @"os_type": MOBILE_DEVICE_TYPE};
    
    [request setRequestMsg:param];
    [self sendDataToSocket:request modelClass:[LoginModel class] isLoading:YES];
}

- (void)requestHomeMemberList {

    if (![JDFacade facade].loginUser.hasHomeHub) {
        return;
    }
    
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_HOMEGROUP_MEMBERS arguments:nil];
//    NSString *path = [NSString stringWithFormat:API_GET_HOMEGROUP_MEMBERS, [[JDFacade facade].loginUser custId], [[JDFacade facade].loginUser ctrtGrpId]];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[HomeMemberListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        _responseInfo = (HomeMemberListModel *)responseObject;
        
        NSArray<HomeMemberModel> *homegrpMemberList = _responseInfo.ctrtGrpMemberList;
        _memberList = homegrpMemberList;
        
        [self setContents];
        
        [_collectionView reloadData];
        
        
        //refresh controller
        if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
            [self.refreshController stopRefreshWithAnimated:YES completion:nil];
        }

    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setContents {
    
    
    HomeMemberModel *master = [_memberList objectKey:@"gradeCode" eqaulToString:KNEET_MEMBER_MASTER];
    
    _masterNickname = master && master.nickname ? master.nickname : ksEmptyString;

    [self updateTitle];

}

- (void)requestMasterTransfer:(NSString *)memberId isRequest:(BOOL)isRequst{
    NSDictionary *parameter = @{@"after_member_id" : ![memberId isEmptyString] ? memberId : ksEmptyString,
                                @"status": isRequst ? MASTER_TRANSFER_REQUEST : MASTER_TRANSFER_CANCEL};

    
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_PUT_HOMEGROUP_MASTER_TRANSFER];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {

        [self toggleMasterTransferMode:NO];

        [self requestHomeMemberList];

    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
    
}

- (void)requestDeleteMembers:(NSString *)memberIds invitations:(NSString *)invitations {
    
    //parameters
    NSDictionary *parameter = @{@"member_ids" : ![memberIds isEmptyString] ? memberIds : ksEmptyString,
                                @"receive_phones": ![invitations isEmptyString] ? invitations : ksEmptyString};
    
//    NSString *path = [NSString stringWithFormat:API_DELETE_HOMEGROUP_MEMBERS];
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_DELETE_HOMEGROUP_MEMBER arguments:nil];
    
    
    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:parameter modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {

        [self toggleEditMode];
        [self requestHomeMemberList];
        //[[JDFacade facade] toast:NSLocalizedString(@"멤버를 삭제했습니다", @"멤버를 삭제했습니다")];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)requestLeaveHomegroup {
    
    //api path
    NSString *path = [NSString stringWithFormat:API_DELETE_HOMEGROUP_MEMBER, [JDFacade facade].loginUser.memberId];

    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {
        
        [[JDFacade facade] alertTitle:@"멤버 탈퇴" message:@"탈퇴를 완료했습니다" completionHander:^{
            [[JDFacade facade] gotoWishMenu:KNMenuIdDashboard];
        }];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

#pragma mark - SocketService
- (void) socketDidReceiveMessage:(id)message result:(SocketModel *)result
{
    SWITCH(result.messageType)
    {
        CASE(MSG_TYPE_AUTO_LOGIN)
        {
            if (result.isSuccess) {
                
                LoginModel *loginInfo = (LoginModel *)message;
                loginInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
                loginInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
                
                [self actionForLoginSucceed:loginInfo];
                [self requestHomeMemberList];
            }
            else {
                
                [[JDFacade facade] alertTitle:@"알림" message:result.resultMsg];
            }
            
            break;
        }
        DEFAULT
        {
            break;
        }
    }
}

//로그인 이후 처리.
- (void)actionForLoginSucceed:(LoginModel *)loginInfo {
    
    if (loginInfo) {//API 성공함
        
        [JDFacade facade].loginUser = loginInfo;
        
        NSLog(@"loginUser : %@", [JDFacade facade].loginUser);
        
        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].tmpEmailId]) {
            [JDFacade facade].tmpEmailId = ksEmptyString;
        }
        
        if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].loginUser.newEmailId]) {//이메일 변경 요청 중
            [JDFacade facade].loginUser.newEmailId = ksEmptyString;
        }
        
        [RequestHandler handler].authorization = loginInfo.authorization;
    }
}






@end
