//
//  ALGroupInviteController.m
//  GMAlpha
//
//  Created by zhb on 2018/11/13.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALGroupInviteController.h"
#import "ALGroupVerbStyle1Cell.h"
#import "ALGroupVerbStyle2Cell.h"
#import "ALGroupEditVerbController.h"
#import "ALGroupConfigModel.h"
#import "ALGroupInviteShareView.h"
#import "ALPersonViewController.h"
#import "ALRankContainerViewController.h"

#import "GMTabBarController.h"
#import "GMShareSDK.h"

@interface ALGroupInviteController ()<ALGroupVerbStyle1CellDelegate, ALGroupEditVerbControllerDelegate, ALGroupInviteShareViewDelegate>
@property (nonatomic, strong) UIButton *bottomButton;
@property (nonatomic, strong) ALGroupInviteShareView *shareView;
@property (nonatomic, strong) NSMutableArray<NSNumber *> *heightArray;
@property (nonatomic, strong) NSArray<NSString *> *titleArray;
@property (nonatomic, assign) NSInteger groupId;
@property (nonatomic, assign) NSInteger creatorId;
@end

@implementation ALGroupInviteController
@synthesize viewModel;

#pragma mark - life cycle
- (instancetype)initWithGroupId:(NSInteger)groupId creatorId:(NSInteger)creatorId {
    self = [super init];
    if (self) {
        self.groupId = groupId;
        self.creatorId = creatorId;
        self.viewModel.groupId = groupId;
        self.viewModel.isCreator = [self isGroupCreator];
    }
    return self;
}

- (void)initController{
    [super initController];
    self.viewModel = [[ALGroupInviteViewModel alloc] init];
    
    self.immediateLoad = YES;
    _needFooterRefresh = NO;
    _needHeaderRefresh = NO;
    self.pageName = @"group_invite";
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
    self.navigationBar.hidden = NO;
    self.navigationBar.title = @"小组";
    self.businessId =[NSString stringWithFormat:@"%zd", self.groupId];
    [self setupSubViews];
}

- (void)setupSubViews {
    self.table.tableHeaderView = self.shareView;
    [self.table registerClass:[ALGroupVerbStyle1Cell class] forCellReuseIdentifier:NSStringFromClass([ALGroupVerbStyle1Cell class])];
    [self.table registerClass:[ALGroupVerbStyle2Cell class] forCellReuseIdentifier:NSStringFromClass([ALGroupVerbStyle2Cell class])];
    [self.table mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-70);
    }];
    
    [self.view addSubview:self.bottomButton];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.equalTo(self.view.mas_safeBottom).offset(-20);
        make.height.mas_equalTo(40);
    }];
    if ([self isGroupCreator]) {
        self.bottomButton.hidden = YES;
    }
    [self.table reloadData];
}

- (void)updateOtherUIData {
    
    [super updateOtherUIData];
    // 传递分享数据
    self.shareView.shareData = self.viewModel.contentObject.shareData;
}

#pragma mark - tableview 数据源/代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.configArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = [self cellReusableIdAtIndexPath:indexPath];
    GMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.indexPath = indexPath;
    [self configNormalDataForCell:cell atIndexPath:indexPath];
    [self configDataForCell:cell atIndexPath:indexPath];
    [self configActionForCell:cell atIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.viewModel.configArray.count == self.viewModel.dataArray.count) {
        ALGroupConfigModel *normalObj = self.viewModel.dataArray[indexPath.row];
        return normalObj.cellHeight;
    }else {
        ALGroupConfigModel *normalObj = self.viewModel.configArray[indexPath.row];
        return normalObj.cellHeight;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    switch (row) {
        case 0:
        {
            NSInteger userId = self.creatorId;
            ALPersonViewController *toVc = [[ALPersonViewController alloc] initWithUserId:userId];
            toVc.referer = self.pageName;
            [self pushViewController:toVc];
        }
            break;
        case 1:
        {
            [self pushScheme:self.viewModel.contentObject.url];
            NSDictionary *phDict = @{
                                   @"page_name": SafeString(self.pageName),
                                   @"business_id": SafeNumber(@(self.groupId)),
                                   };
            [Phobos track:@"group_invite_click_follower_list" attributes:phDict];
        }
            break;
        case 2:
        {
            //1.只有操作者是组长 才跳转
            NSInteger groupId = self.viewModel.contentObject. id;
            if (![self isGroupCreator]) return;
            ALGroupEditVerbController*toVc = [[ALGroupEditVerbController alloc] initWithGroupId:groupId];
            toVc.delegate = self;
            [self pushViewController:toVc];
            //埋点:简介
            NSDictionary *phDict = @{
                                     @"page_name": SafeString(self.pageName),
                                     @"business_id": SafeNumber(@(self.groupId)),
                                     };
            [Phobos track:@"group_invite_click_group_intro" attributes:phDict];
        }
            break;
        default:
            break;
    }
}


#pragma mark - style1Cell 代理
- (void)style1Cell:(ALGroupVerbStyle1Cell *)cell clickedArrowButton:(UIButton *)arrowButton {

}

#pragma mark - ALGroupInviteShareViewDelegate
- (void)shareView:(ALGroupInviteShareView *)view selectedPlatform:(GMSharePlatform)platform {
    //埋点:分享
    NSString *inviteWay = @"";
    switch (platform) {
        case GMSharePlatformWechatSession:
            inviteWay = @"微信";
            break;
        case GMSharePlatformWechatTimeline:
            inviteWay = @"朋友圈";
            break;
        case GMSharePlatformSinaWeibo:
            inviteWay = @"微博";
            break;
        case GMSharePlatformQQFriend:
            inviteWay = @"QQ";
            break;
        default:
            return;
    }
    NSDictionary *phDict = @{
                             @"page_name": SafeString(self.pageName),
                             @"business_id": SafeNumber(@(self.groupId)),
                             @"invite_way": inviteWay,
                             };
    [Phobos track:@"group_invite_click_invite" attributes:phDict];

}

#pragma mark - ALGroupEditVerbControllerDelegate
/** 将要出栈 */
- (void)groupEditVerbControllerWillPopping {
    [self.viewModel fetchRemoteData];
}

#pragma mark - 私有方法
- (NSString *)cellReusableIdAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 3) {
        return NSStringFromClass([ALGroupVerbStyle2Cell class]);
    }else {
        return NSStringFromClass([ALGroupVerbStyle1Cell class]);
    }
}

- (void)configNormalDataForCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    ALGroupConfigModel *normalObj = self.viewModel.configArray[indexPath.row];
    if (row == 3){
        ALGroupVerbStyle2Cell *tCell = (ALGroupVerbStyle2Cell *)cell;
        [tCell showNormalDataWithViewModel:normalObj atIndexPath:indexPath];
    }
    else {
        ALGroupVerbStyle1Cell *tCell = (ALGroupVerbStyle1Cell *)cell;
        [tCell showNormalDataWithViewModel:normalObj atIndexPath:indexPath];
    }
}

- (void)configDataForCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 3){
        ALGroupVerbStyle2Cell *tCell = (ALGroupVerbStyle2Cell *)cell;
        [tCell showData:self.viewModel.contentObject atIndexPath:indexPath];
    }
    else {
        ALGroupVerbStyle1Cell *tCell = (ALGroupVerbStyle1Cell *)cell;
        [tCell showData:self.viewModel.contentObject atIndexPath:indexPath];
    }
}

- (void)configActionForCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 3){
    }
    else {
        ALGroupVerbStyle1Cell *tCell = (ALGroupVerbStyle1Cell *)cell;
        tCell.delegate = self;
    }
}


#pragma mark - 事件
-(void)clickedBottomButtonButton:(UIButton *)sender {
    if ([self isGroupCreator]) {
        [self toast:@"您是组长,不能退出小组!"];
        return;
    }
    [self requestCancelFollowGroup];
    NSDictionary *phDict = @{
                             @"page_name": SafeString(self.pageName),
                             @"business_id": SafeNumber(@(self.groupId)),
                             };
    [Phobos track:@"group_invite_click_quit_group" attributes:phDict];
}

#pragma mark - 网络
- (void)requestCancelFollowGroup {
    NSString *groupId = [NSString stringWithFormat:@"%ld", (long)self.viewModel.contentObject.id];
    if (groupId == nil || groupId.length == 0) {
        return;
    }
    NSDictionary *params = @{
                             @"type": @"0",
                             @"id": groupId
                             };
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:API_V1_CANCEL_FOLLOW method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        if (response.isSuccess == NO) return;
        //更改view状态
        [weakSelf toast:@"您已经退出小组"];
        if ([weakSelf.delegate respondsToSelector:@selector(groupInviteControllerWillPopping)]) {
            [weakSelf.delegate groupInviteControllerWillPopping];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}


#pragma mark - getters and setters

- (ALGroupInviteShareView *)shareView
{
    if (!_shareView) {
        _shareView = [[ALGroupInviteShareView alloc] init];
        _shareView.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, 173);
        _shareView.delegate = self;
    }
    return _shareView;
}

- (UIButton *)bottomButton
{
    if (_bottomButton == nil) {
        _bottomButton = [[UIButton alloc] init];
        _bottomButton.backgroundColor = UIColor.whiteColor;
        [_bottomButton setTitleColor:UIColor.auxiliaryTextLight forState:UIControlStateNormal];
        _bottomButton.titleLabel.font = [UIFont gmFont:16];
        [_bottomButton setTitle:@"退出小组" forState:UIControlStateNormal];
        _bottomButton.contentMode = UIViewContentModeCenter;
        _bottomButton.layer.cornerRadius = 20;
        _bottomButton.layer.masksToBounds = YES;
        [_bottomButton addTarget:self action:@selector(clickedBottomButtonButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomButton;
}

- (BOOL)isGroupCreator {
    NSInteger userId = [GMLoginManager shareInstance].user.userId;
    return (userId == self.creatorId);
}


- (NSString *)getNowTimeTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
}


@end
