//
//  PreListView.m
//  Gengmei
//
//  Created by Sean Lee on 4/7/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "GMPreviewListView.h"
#import <Masonry/Masonry.h>
#import <Constant.h>
@interface GMPreviewListView ()<GMPreviewCellDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView   *scrollView;
@property (nonatomic, strong) GMPreviewCell    *defaultCell;
@property (nonatomic, assign) BOOL           hasDelete;
@property (nonatomic, assign) BOOL           frontMove;
@property (nonatomic, assign) int            moveCount;

@end

@implementation GMPreviewListView

- (void)setup{
    [super setup];
    self.backgroundColor = UIColor.whiteColor;
    _previewList = [[NSMutableArray alloc] init];
    _hasDelete = NO;
    _moveCount = 0;
    
    _scrollView = [[UIScrollView alloc] init];
    _scrollView.delegate = self;
    _scrollView.backgroundColor = UIColor.whiteColor;
    _scrollView.scrollEnabled = YES;
    
    _scrollView.directionalLockEnabled = YES;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = YES;
//    _scrollView.alwaysBounceHorizontal = YES;
    _scrollView.contentSize = [self contentSizeForUIScrollView:0];
    [self addSubview:_scrollView];
    if (!_cellWH) {
        _cellWH = self.cellWH;
    }
    
    _defaultCell = [[GMPreviewCell alloc] initWithFrame:CGRectMake(0, 0,PREVIRE_CELL_HEIGHT, PREVIRE_CELL_HEIGHT) image:[UIImage imageNamed:@"camera"]];
    
    _defaultCell.tag = 1000;
    _defaultCell.delegate = self;
    [_scrollView addSubview:_defaultCell];
    [self scrollViewAbleScroll];
}

- (void)setDefaultCellImage:(UIImage *)defaultCellImage {
    _defaultCellImage = defaultCellImage;
    if (_defaultCellImage != nil) {
        _defaultCell.image = _defaultCellImage;
    }
}

- (NSInteger)cellWH {
    if (_cellWH > 0) {
        CGRect rect = _defaultCell.frame;
        rect.size.width = _cellWH;
        rect.size.height = _cellWH;
        _defaultCell.frame = rect;
    } else {
        _cellWH = PREVIRE_CELL_HEIGHT;
    }
    return _cellWH;
}

- (void)updateConstraints{
    
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(00);
        make.top.mas_equalTo(00);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [super updateConstraints];
}


/*
 *  @brief 根据index获取UIScrollView的ContentSize
 */
- (CGSize)contentSizeForUIScrollView:(NSInteger)index
{
    float width = (PREVIRE_CELL_SPACE + self.cellWH) * index;
    if (width < _scrollView.bounds.size.width)
        width = _scrollView.bounds.size.width;
    return CGSizeMake(width, PREVIRE_CELL_HEIGHT);
}


- (void)scrollViewAbleScroll
{
    _scrollView.contentSize = [self contentSizeForUIScrollView:(_previewList.count + 1)];
    [_scrollView scrollRectToVisible:CGRectMake(_scrollView.contentSize.width - self.cellWH, 0, self.cellWH, self.frame.size.height) animated:YES];
}

- (GMPreviewCell * ) addImage:(UIImage *)image{
    
    GMPreviewCell * newPreviewCell = nil;
    CGFloat x = (_previewList.count) * (PREVIRE_CELL_SPACE + self.cellWH);
    newPreviewCell = [[GMPreviewCell alloc] initWithFrame:CGRectMake(x, 0, self.cellWH, self.cellWH) image:image];
    
    newPreviewCell.alpha = 0.1;
    newPreviewCell.delegate = self;
    [_previewList addObject:newPreviewCell];
    [_scrollView addSubview:newPreviewCell];
    [self scrollViewAbleScroll];
    _defaultCell.alpha = 0.5;
    
    [UIView animateWithDuration:DURATION animations:^(){
        CGRect rect = _defaultCell.frame;
        rect.origin.x += (PREVIRE_CELL_SPACE + self.cellWH);
        _defaultCell.frame = rect;
        _defaultCell.alpha = 1.0;
        newPreviewCell.alpha = 0.8;
        
    } completion:^(BOOL finished){
        newPreviewCell.alpha = 1.0;
        
    }];
    return newPreviewCell;
}


#pragma -- mark  PreviewCellDelegate

- (void)prepareAddPreviewCell:(GMPreviewCell *)cell{
    
    if ([self.delegate respondsToSelector:@selector(addPreviewCell)]) {
        [self.delegate addPreviewCell];
    }
}

- (void)prepareDeletePreviewCell:(GMPreviewCell *)cell{
    
    NSInteger index = [_previewList indexOfObject:cell];
    //设置相关Cell的透明度
    cell.alpha = 0.8;
    // 判断其余cell的移动方向（从前向后移动/从后向前移动）
    _frontMove = NO;
    if (_previewList.count - 1 > DEFAULT_VISIBLE_COUNT
        && (_previewList.count - index - 1) <= DEFAULT_VISIBLE_COUNT) {
        _frontMove = YES;
    }
    if (index == _previewList.count - 1 && !_frontMove)
        _defaultCell.alpha = 0.5;
    
    [UIView animateWithDuration:DURATION animations:^(){
        
        //其余defautlCell依次移动
        if (_frontMove)
        {
            //前面的向后移动
            for (int i = 0; i < index; i++) {
                GMPreviewCell *cell = _previewList[i];
                CGRect rect = cell.frame;
                rect.origin.x += (PREVIRE_CELL_SPACE + self.cellWH);
                cell.frame = rect;
            }
            _moveCount++;
        }
        else
        {
            //后面的向前移动
            for (NSInteger i = index + 1; i < _previewList.count; i++) {
                GMPreviewCell *cell = _previewList[i];
                CGRect rect = cell.frame;
                rect.origin.x -= (PREVIRE_CELL_SPACE + self.cellWH);
                cell.frame = rect;
            }
            
            //defautlCell向前移动
            CGRect rect = _defaultCell.frame;
            rect.origin.x -= (PREVIRE_CELL_SPACE + self.cellWH);
            _defaultCell.frame = rect;
            _defaultCell.alpha = 1.0;
            
        }
        cell.alpha = 0.0;
        
    } completion:^(BOOL finished){
        
        if ([self.delegate respondsToSelector:@selector(deletePreviewCell:)]) {
            [self.delegate deletePreviewCell:index];
        }
        //删除被点击的cell
        [cell removeFromSuperview];
        [_previewList removeObject:cell];
        
        if (_previewList.count <= DEFAULT_VISIBLE_COUNT){
            [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
            _scrollView.contentSize = [self contentSizeForUIScrollView:0];
        }
        
        if (_frontMove) {
            [self isNeedResetFrame];
        }
    }];
    _hasDelete = YES;
}

/**大图模式*/
- (void)didSelectedPreviewCell:(GMPreviewCell *)cell{
    
    if ([self.delegate respondsToSelector:@selector(fullScreenImage:)]) {
        [self.delegate fullScreenImage:cell];
    }
    
}


- (void)prepareRetryUploadPreviewCell:(GMPreviewCell *)cell{
    
    if ([self.delegate respondsToSelector:@selector(retryUploadPreviewCell:)]) {
        [self.delegate retryUploadPreviewCell:cell];
    }
    
}

/**
 *  @brief 当删除操作是前面的unitCell向后移动时
 *  做滚动操作或者添加操作需要重新设置每个unitCell的frame
 */
- (void)isNeedResetFrame
{
    if (_frontMove && _moveCount > 0) {
        for (int i = 0; i < _previewList.count; i++) {
            GMPreviewCell *cell = [_previewList objectAtIndex:(NSUInteger) i];
            CGRect rect = cell.frame;
            rect.origin.x -= (PREVIRE_CELL_SPACE + self.cellWH) * _moveCount;
            cell.frame = rect;
        }
        
        CGRect rect = _defaultCell.frame;
        rect.origin.x -= (PREVIRE_CELL_SPACE + self.cellWH) * _moveCount;
        _defaultCell.frame = rect;
        
        _frontMove = NO;
        _moveCount = 0;
    }
    
    if (_hasDelete)
    {
        _scrollView.contentSize = [self contentSizeForUIScrollView:(_previewList.count + 1)];
        _hasDelete = !_hasDelete;
    }
}

/***  @brief  开始上传，显示loading */
- (void)showLoadingAtIndex:(NSInteger)index{
    GMPreviewCell * cell = _previewList[index];
    [cell.retryButton setHidden:YES];
    [cell.deleteButton setHidden:YES];
    [cell.indicatorView setHidden:NO];
    [cell.indicatorView startAnimating];
}

/***  @brief  上传成功，隐藏loading */
- (void)hideLoadingAtIndex:(NSInteger)index{
    
    GMPreviewCell * cell = _previewList[index];
    [cell.retryButton setHidden:YES];
    [cell.deleteButton setHidden:NO];
    [cell.indicatorView setHidden:YES];
    [cell.indicatorView stopAnimating];
}

/***  @brief 重新上传loading */
- (void)retryLoadingAtIndex:(NSInteger)index{
    if (index > _previewList.count - 1){
        return;
    }
    GMPreviewCell * cell = _previewList[index];
    [cell.retryButton setHidden:NO];
    [cell.deleteButton setHidden:NO];
    [cell.indicatorView setHidden:YES];
    [cell.indicatorView stopAnimating];
}

@end
