//
//  ALRankViewController.m
//  GMAlpha
//
//  Created by Mikasa on 2018/11/8.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALRankViewController.h"
#import "ALRankListContainerViewController.h"
#import "ALRankCardView.h"
#import "GMLoginManager.h"
#import "GMLoginManager.h"

#define kCardCount  3
@interface ALRankViewController ()< MDCSwipeToChooseDelegate>

@property (nonatomic, strong) NSMutableArray *userArrayM;
@property (nonatomic, assign) NSInteger rankIndex;
@property (nonatomic, strong) NSMutableArray *cardViewArray;

@property (nonatomic, strong) ALRankCardView *frontCardView;
@property (nonatomic, strong) ALRankCardView *backCardView;
@end

@implementation ALRankViewController

#pragma mark - lazy loading

#pragma mark - view lifeCycle
- (void)initController {
    
    [super initController];
    self.needLogPV = NO;
    self.viewModel = [ALPickListViewModel new];
    self.viewModel.refreshData = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (self.viewModel.refreshData) {

        [self reloadRefreshData];
        
    } else {
        if (self.viewModel.userListObject.users.count > 0) {
            [self addCard];
        } else {
            [self showEmptyView:GMEmptyViewTypeEmpty];
        }
    }
}

- (void)reloadRefreshData {
    self.viewModel.refreshData = NO;
    self.viewModel.page = 1;
    [GMHudModule showLoading:nil];
    [self getUserPickData];
}

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

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
    [self.navigationBar removeFromSuperview];
    self.cardViewArray = [NSMutableArray array];
    self.userArrayM = [NSMutableArray array];
}

// 添加卡片
- (void)addCard {

    // 废弃之前卡片
    [self disCard];
    
    // 需要展示叠层卡片
    NSInteger cardCount = kCardCount;
    if (self.viewModel.userListObject.users.count > 0) {
        cardCount = MIN(self.viewModel.userListObject.users.count, kCardCount);
    }
    CGFloat leftTop = 15 + 10*(cardCount-1);
    CGFloat minWidth = kRankCardViewW - 20*(cardCount-1);
    
    for (int i = 0; i < cardCount; i++) {
        __weak __typeof(self)weakSelf = self;
        MDCSwipeToChooseViewOptions *options = [MDCSwipeToChooseViewOptions new];
        options.delegate = self;
        options.threshold = 160.f;
        options.onPan = ^(MDCPanState *state){
            [weakSelf updateSubCardView:state];
        };
        ALRankCardView *cardView = nil;
        if (i == 0) {
            cardView = [[ALRankCardView alloc] initWithFrame:CGRectMake(leftTop, leftTop, minWidth, kRankCardViewH) options:options];
        } else {
            ALRankCardView *preCardView = self.cardViewArray[i-1];
            cardView = [[ALRankCardView alloc] initWithFrame:CGRectMake(preCardView.left-10, preCardView.top-10, preCardView.width+20, kRankCardViewH) options:options];
        }
        cardView.userInteractionEnabled = NO;
        if (i == cardCount-1) {
            cardView.userInteractionEnabled = YES;
        }
        cardView.userObject = self.viewModel.userListObject.users[(cardCount-1) - (i%cardCount)];
        cardView.pick_id = self.viewModel.pick_id;
        cardView.pickTab_name = self.pickTab_name;
        [self.cardViewArray addObject:cardView];
        [self.view addSubview:cardView];
    }
}

- (void)disCard {
    for (ALRankCardView *rankView in self.cardViewArray) {
        [rankView removeFromSuperview];
    }
    [self.cardViewArray removeAllObjects];
    
}

// 滑动过程中更新其他卡片的frame
- (void)updateSubCardView:(MDCPanState *)state {
    
    CGFloat thresholdRatio = state.thresholdRatio;
    
    // 滑动超出卡片一半多弹出登录
    if (thresholdRatio > 0.85 && [[GMLoginManager shareInstance] showLoginViewIfNeeded]) {
        return;
    }
    
    NSInteger cardCount = self.cardViewArray.count;
    for (int i = 0; i < cardCount; i++) {
        
        ALRankCardView *subCardView = (ALRankCardView *)self.cardViewArray[i];
        
        if (subCardView != state.view) {
            
            CGFloat offset = (cardCount - i - 1)*10;
            CGRect frame = CGRectMake(15+offset, 15+offset, kRankCardViewW-offset*2, kRankCardViewH);
            
            subCardView.frame = CGRectMake(frame.origin.x - (thresholdRatio * 10.f), frame.origin.y- (state.thresholdRatio * 10.f), frame.size.width + thresholdRatio*20, kRankCardViewH);
        }
    }
}

// 更新卡片数据
- (void)updateCardViewData {
    NSInteger cardCount = self.cardViewArray.count;
    for (int i = 0; i < cardCount; i++) {
        
        ALRankCardView *subCardView = (ALRankCardView *)self.cardViewArray[i];
        subCardView.userObject = self.viewModel.userListObject.users[(cardCount-1) - (i%cardCount)];
        subCardView.pick_id = self.viewModel.pick_id;
    }
}

#pragma mark - Network Data
// 获取用户数据
- (void)getUserPickData {
    
    [self hideEmptyView];
    [self.viewModel excuteUserPickList:^(id responseObject) {
        
        if (self.viewModel.userListObject.users.count > 0) {
            if (self.viewModel.page == 1) {
                [self addCard];
            }
        } else {
            [self disCard];
            [self showEmptyView:GMEmptyViewTypeEmpty];
        }
        
    } failBlock:^(NSString *message) {
        
        if (self.viewModel.userListObject.users.count == 0) {
            [self disCard];
            [self showEmptyView:GMEmptyViewTypeException];
        }
    }];
}

// 获取下一页用户数据
- (void)getNextPageUserData {
    
    if (self.viewModel.userListObject.users.count <= 5 && self.viewModel.moreData) {
        
        self.viewModel.page++;
        [self getUserPickData];
    }
    
}

// 重新加载数据
- (void)emptyViewDidClickReload {
    [GMHudModule showLoading:nil];
    [self getUserPickData];
}

#pragma mark - MDCSwipeToChooseDelegate Protocol Methods
// This is called when a user didn't fully swipe left or right.
- (void)viewDidCancelSwipe:(UIView *)view {
//    NSLog(@"You couldn't decide on %@.", view);
}

// This is called then a user swipes the view fully left or right.
- (void)view:(UIView *)view wasChosenWithDirection:(MDCSwipeDirection)direction {
        
    ALRankCardView *cardView = (ALRankCardView *)view;
    ALUserObject *userObject = cardView.userObject;
    self.viewModel.pick_type = userObject.pick_type;
    
    if (direction == MDCSwipeDirectionLeft) {
        self.viewModel.is_pick = NO;
    } else {
        self.viewModel.is_pick = YES;
    }

    [Phobos track:@"pick_home_swipe_card" attributes:@{@"tab_name":SafeString(self.pickTab_name),
                                                       @"business_id":SafeString(userObject.pick_user_id),
                                                       @"favor":self.viewModel.is_pick?@"right":@"left"
                                                       }];
    [self.viewModel excuteUserDoPick:userObject.pick_user_id
                        successBlock:^(id responseObject) {
    } failBlock:^(NSString *message) {  
    }];
    
    // 动画完成
    [UIView animateWithDuration:0.5
                                   delay:0.0
                                 options:UIViewAnimationOptionCurveEaseInOut
                              animations:^{
                                  cardView.alpha = 1.0f;
                              } completion:^(BOOL finished) {
                                  
                                  [self updateNextCard:cardView];
                              }];
}

- (void)updateNextCard:(ALRankCardView *)cardView {
    
    cardView.userInteractionEnabled = NO;
    [self.viewModel.userListObject.users removeObject:cardView.userObject];
    [self.cardViewArray removeObject:cardView];
    
    if (self.cardViewArray.count == 0) {
        [GMHudModule toast:@"暂时没有更多卡片咯～"];
        return;
    }
    ALRankCardView *lastView = (ALRankCardView *)[self.cardViewArray lastObject];
    lastView.userInteractionEnabled = YES;
    ALUserObject *userObject = [[self.cardViewArray firstObject] userObject];
    
    if ([self.viewModel.userListObject.users containsObject:userObject]) {
        NSInteger index = [self.viewModel.userListObject.users indexOfObject:userObject];
        
        if (index+1 < self.viewModel.userListObject.users.count-1) {
            cardView.userObject = self.viewModel.userListObject.users[index+1];
            cardView.pick_id = self.viewModel.pick_id;
            cardView.transform = CGAffineTransformIdentity;
            cardView.frame = CGRectMake(35, 35, (kRankCardViewW - 60), kRankCardViewH);
            cardView.likedView.alpha = 0;
            cardView.nopeView.alpha = 0;
            [self.view insertSubview:cardView atIndex:0];
            [self.cardViewArray insertObject:cardView atIndex:0];
            [self getNextPageUserData];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
