//
//  SelectMonthViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/12/20.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SelectMonthViewController.h"

#import "UIView+frameAdjust.h"
#import "Constants.h"
#import "SelectMonthCollectionViewCell.h"
#import "JHCollectionViewFlowLayout.h"
#import "SelectMonthReusableView.h"
#import "UIView+frameAdjust.h"

typedef NS_ENUM(NSUInteger,SELECTState) {
    SELECTStateZero,
    SELECTStateStart,
    SELECTStateEnd
};

@interface SelectMonthViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,JHCollectionViewDelegateFlowLayout,CAAnimationDelegate>
{
    int startYear;
    int startMonth;
    int nums;
    
    NSIndexPath* selectedIndexPath;
    NSIndexPath* selectedIndexPath2;
    
    
    SELECTState currentState;
    
    UILabel *startLabel;
    UILabel *endLabel;
    UILabel *startDateLabel;
    UILabel *endDateLabel;
    UIView *selectLine;
}

@property (nonatomic, strong)UICollectionView* collectionView;
@property (nonatomic, strong)NSMutableArray* dataArray;

@end

@implementation SelectMonthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSString*startDate = self.startDate;
    int num = 1;
    nums = num;
    int startNum = [startDate substringToIndex:4].intValue;
    
    startYear = startNum;
    startMonth = [startDate substringFromIndex:5].intValue;
    
    self.dataArray = [NSMutableArray array];
    
    for (int i = startNum; i < (startNum + 3); i++) {
        [self.dataArray addObject:@(i)];
    }
    
    currentState = SELECTStateZero;
    [self creatUI];
}
- (void)creatUI
{
     [self.view addSubview:self.collectionView];
    [self creatTopView];
   
}
- (void)creatTopView
{
    UIView* topView = [[UIView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 100)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    
    UIView* subTopView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 45)];
    
    subTopView.backgroundColor = RGBCOLOR(250, 247, 231);
    [topView addSubview:subTopView];
    
    UIView* subMiddleView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, ScreenWidth, 55)];
    
    subMiddleView.backgroundColor = [UIColor whiteColor];
    [topView addSubview:subMiddleView];
    
    
    UIView *dView = [[UIView alloc]init];
    dView.backgroundColor = RGBCOLOR(211, 118, 50);
    dView.layer.cornerRadius = 2;
    dView.layer.masksToBounds = YES;
    [subTopView addSubview:dView];
    
    UILabel *lb_message = [[UILabel alloc]init];
    lb_message.text = @"开始时间仅支持近半年内的月份，最多可购买12个月";
    lb_message.textColor = RGBCOLOR(211, 118, 50);
    lb_message.numberOfLines = 0;
    lb_message.font = [UIFont systemFontOfSize:12];
    
    [subTopView addSubview:lb_message];
    
     
    
    [dView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(subTopView);
        make.left.offset(20);
        make.width.height.offset(4);
    }];
    
    
    [lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(dView.mas_centerY);
        make.left.equalTo(dView.mas_right).offset(10);
        make.right.offset(-20);
    }];
    
    UILabel *lb_startMonth = [[UILabel alloc]init];
    lb_startMonth.text = @"开始月份";
    lb_startMonth.textAlignment = NSTextAlignmentCenter;
    lb_startMonth.textColor = K_MainColor;
    lb_startMonth.font = [UIFont systemFontOfSize:15];
    [subMiddleView addSubview:lb_startMonth];
    
    startLabel = lb_startMonth;
    
    
    
    
    UILabel *lb_endMonth = [[UILabel alloc]init];
    lb_endMonth.text = @"结束月份";
    lb_endMonth.textAlignment = NSTextAlignmentCenter;
    lb_endMonth.textColor = [UIColor colorWithHex:0x808080];
    lb_endMonth.font = [UIFont systemFontOfSize:15];
    [subMiddleView addSubview:lb_endMonth];
    
    endLabel = lb_endMonth;
    
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = K_MainColor;
    [subMiddleView addSubview:line];
    
    selectLine = line;
    
    [lb_startMonth mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(subMiddleView);
        make.left.offset(60);
    }];
    
    
    [lb_endMonth mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(subMiddleView);
        make.right.offset(-60);
    }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(lb_startMonth);
        make.bottom.equalTo(subMiddleView);
        make.height.offset(2);
        make.width.offset(80);
    }];
    
    
    
   
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 12;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     SelectMonthCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
     cell.backgroundColor = [UIColor whiteColor];
    if (currentState == SELECTStateZero) {
        if ((startMonth + 6) <= 12) {
                          if (indexPath.section == 0) {
                              if (indexPath.item < (startMonth - 1)) {
                                  
                                  cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                                  cell.lb_month.backgroundColor = [UIColor clearColor];
                                  cell.isSelected = NO;
                              }else{
                                  
                                  if (selectedIndexPath == indexPath) {
                                      cell.lb_month.textColor = [UIColor whiteColor];
                                      cell.lb_month.backgroundColor = K_MainColor;
                                  }else{
                                      cell.lb_month.textColor = [UIColor colorWithHex:0x4d4d4d];
                                      cell.lb_month.backgroundColor = [UIColor clearColor];
                                      
                                  }
                                  
                                  cell.isSelected = YES;
                                  
                              }
                          }else{
                              cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                              cell.lb_month.backgroundColor = [UIColor clearColor];
                              cell.isSelected = NO;
                          }
                      }else{
                          int remainderNum = (startMonth + 6) - 12;
                          if (indexPath.section == 0){
                             if (indexPath.item < (startMonth - 1)) {
                                  cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                                  cell.lb_month.backgroundColor = [UIColor clearColor];
                                 cell.isSelected = NO;
                              }else{
                                  if (selectedIndexPath == indexPath) {
                                      cell.lb_month.textColor = [UIColor whiteColor];
                                      cell.lb_month.backgroundColor = K_MainColor;
                                  }else{
                                      cell.lb_month.textColor = [UIColor colorWithHex:0x4d4d4d];
                                      cell.lb_month.backgroundColor = [UIColor clearColor];
                                  }
                                  cell.isSelected = YES;
                              }
                          }else if (indexPath.section == 1){
                              if (indexPath.item < (remainderNum - 1)) {
                                  if (selectedIndexPath == indexPath) {
                                      cell.lb_month.textColor = [UIColor whiteColor];
                                      cell.lb_month.backgroundColor = K_MainColor;
                                  }else{
                                      cell.lb_month.textColor = [UIColor colorWithHex:0x4d4d4d];
                                      cell.lb_month.backgroundColor = [UIColor clearColor];
                                  }
                                  cell.isSelected = YES;
                              }else{
                                  cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                                  cell.lb_month.backgroundColor = [UIColor clearColor];
                                  cell.isSelected = NO;
                              }
                          }else{
                              cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                              cell.lb_month.backgroundColor = [UIColor clearColor];
                              cell.isSelected = NO;
                          }
                      }
    }else if (currentState == SELECTStateStart || currentState == SELECTStateEnd){
        
        NSInteger currrentIndex = indexPath.section * 12 + (indexPath.item + 1);
        NSInteger selectedIndex = selectedIndexPath.section * 12 + (selectedIndexPath.item + 1);
        
        if ((selectedIndex + 11) < currrentIndex) {
            cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
            cell.lb_month.backgroundColor = [UIColor clearColor];
            cell.isSelected = NO;
        }else{
            if (startMonth > currrentIndex) {
                cell.lb_month.textColor = [UIColor colorWithHex:0xd9d9d9];
                cell.lb_month.backgroundColor = [UIColor clearColor];
                cell.isSelected = NO;
            }else{
                if (selectedIndexPath == indexPath || selectedIndexPath2 == indexPath) {
                    cell.lb_month.textColor = [UIColor whiteColor];
                    cell.lb_month.backgroundColor = K_MainColor;
                }else{
                    cell.lb_month.textColor = [UIColor colorWithHex:0x4d4d4d];
                    cell.lb_month.backgroundColor = [UIColor clearColor];
                    
                }
                
                cell.isSelected = YES;
            }
        }
        
       
        
        
    }
  
       
           
           cell.lb_month.text = [NSString stringWithFormat:@"%ld月",indexPath.item + 1];
           
           NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:cell.lb_month.text];
           [content addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, cell.lb_month.text.length - 1)];
           [content addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(cell.lb_month.text.length - 1, 1)];
           cell.lb_month.attributedText = content;
   
       
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
   return  CGSizeMake((ScreenWidth- 100)/5, (ScreenWidth- 100)/5);
}

/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(30, 30, 30, 30);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{

    return 10.0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10.0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    SelectMonthReusableView *sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                         UICollectionElementKindSectionHeader withReuseIdentifier:@"SelectMonthReusableView" forIndexPath:indexPath];
   
    sectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    
    sectionView.lb_year.text = [NSString stringWithFormat:@"%@年",self.dataArray[indexPath.section]];
    
    return sectionView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
        return CGSizeMake(self.view.frame.size.width, 45);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    SelectMonthCollectionViewCell *cell = (SelectMonthCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
   
    
    if (cell.selected) {
        
        if (currentState == SELECTStateZero) {
            currentState = SELECTStateStart;
            selectedIndexPath = indexPath;
            [collectionView reloadData];
            [self selectAnimation:cell indexPath:indexPath];
        }else if (currentState == SELECTStateStart){
            if ((indexPath.section * 12 + (indexPath.item + 1)) < (selectedIndexPath.section * 12 + (selectedIndexPath.item + 1))) {
                currentState = SELECTStateStart;
                selectedIndexPath = indexPath;
                [self selectAnimation:cell indexPath:indexPath];
                [collectionView reloadData];
            }else{
                currentState = SELECTStateEnd;
                selectedIndexPath2 = indexPath;
                [self startEndAnimation:cell indexPath:indexPath];
                [collectionView reloadData];
                
            }
        }
       
    }
    
   
}

#pragma mark - JHCollectionViewDelegateFlowLayout
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section
{
    if (section == 0) {
        return [UIColor whiteColor];
    }else if (section == 1){
        return [UIColor whiteColor];
    }
    return [UIColor whiteColor];
}

#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
     CGPoint center = self->selectLine.center;
            center.x = self->endLabel.centerX;
            [UIView animateWithDuration:0.25 animations:^{
                self->selectLine.center = center;
                self->endLabel.textColor = K_MainColor;
    
            }];
}


#pragma mark - 动画
//StartShow

- (void)selectAnimation:(UIView *)view indexPath:(NSIndexPath *)indexPath
{
    
//    SelectMonthCollectionViewCell*cell = (SelectMonthCollectionViewCell*)view;
    

    
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];

    CGPoint startPoint = [view convertPoint:CGPointMake(0, 0) toView:window];
    
  
     
    
    startLabel.transform = CGAffineTransformScale(endLabel.transform, 1.0, 1.0);
    [startLabel sizeToFit];

    
    
   __block UILabel *lb_startDate = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 15)];
    lb_startDate.text = @"";
    lb_startDate.textAlignment = NSTextAlignmentCenter;
    lb_startDate.textColor = K_MainColor;
    lb_startDate.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:lb_startDate];
    
    
    lb_startDate.frame = CGRectMake(startPoint.x, startPoint.y, lb_startDate.bounds.size.width, lb_startDate.bounds.size.height);
    lb_startDate.text = [NSString stringWithFormat:@"%@年%ld月",self.dataArray[indexPath.section],(indexPath.item + 1)];
    
    if (self->startDateLabel) {
        self->startLabel.transform = CGAffineTransformScale(self->endLabel.transform, 0.85, 0.85);
        self->startLabel.center = CGPointMake(self->startLabel.center.x,  15);
    }
    
    [UIView animateWithDuration:0.5 animations:^{
         if (self->startDateLabel == nil) {
            self->startLabel.transform = CGAffineTransformScale(self->endLabel.transform, 0.85, 0.85);
            self->startLabel.center = CGPointMake(self->startLabel.center.x,  15);
        }
        
        CGRect endRact = [self->startLabel convertRect:self->startLabel.bounds toView:window];
        
       lb_startDate.frame= CGRectMake(endRact.origin.x - (lb_startDate.width - self->startLabel.width)/2,CGRectGetMaxY(endRact) + 5, lb_startDate.width, lb_startDate.height);
        
    } completion:^(BOOL finished) {
        if (self->startDateLabel) {
            [self->startDateLabel removeFromSuperview];
        }
        
        
        
        //if (self->startDateLabel == nil) {
            CGPoint center = self->selectLine.center;
                  center.x = self->endLabel.centerX;
                  self->startDateLabel = lb_startDate;
                  [UIView animateWithDuration:0.5 animations:^{
                      self->selectLine.center = center;
                      self->endLabel.textColor = K_MainColor;

                  }];
        //}
        
    }];;
    
  
   
    
    

}

- (void)startEndAnimation:(UIView *)view indexPath:(NSIndexPath *)indexPath
{
    
       

       
       UIWindow * window=[[[UIApplication sharedApplication] delegate] window];

       CGPoint startPoint = [view convertPoint:CGPointMake(0, 0) toView:window];
       
     
        
       
       endLabel.transform = CGAffineTransformScale(endLabel.transform, 1.0, 1.0);
       [endLabel sizeToFit];

       
       
      __block UILabel *lb_endDate = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 15)];
       lb_endDate.text = @"";
       lb_endDate.textAlignment = NSTextAlignmentCenter;
       lb_endDate.textColor = K_MainColor;
       lb_endDate.font = [UIFont systemFontOfSize:15];
       [self.view addSubview:lb_endDate];
       
       
       lb_endDate.frame = CGRectMake(startPoint.x, startPoint.y, lb_endDate.bounds.size.width, lb_endDate.bounds.size.height);
       lb_endDate.text = [NSString stringWithFormat:@"%@年%ld月",self.dataArray[indexPath.section],(indexPath.item + 1)];
       
       if (self->endDateLabel) {
           self->endLabel.transform = CGAffineTransformScale(self->endLabel.transform, 0.85, 0.85);
           self->endLabel.center = CGPointMake(self->endLabel.center.x,  15);
       }
       
       [UIView animateWithDuration:0.5 animations:^{
            if (self->endDateLabel == nil) {
               self->endLabel.transform = CGAffineTransformScale(self->endLabel.transform, 0.85, 0.85);
               self->endLabel.center = CGPointMake(self->endLabel.center.x,  15);
           }
           
           CGRect endRact = [self->endLabel convertRect:self->endLabel.bounds toView:window];
           
          lb_endDate.frame= CGRectMake(endRact.origin.x - (lb_endDate.width - self->endLabel.width)/2,CGRectGetMaxY(endRact) + 5, lb_endDate.width, lb_endDate.height);
           
       } completion:^(BOOL finished) {
           if (self->endDateLabel) {
               [self->endDateLabel removeFromSuperview];
           }
           
           self->endDateLabel = lb_endDate;
           
           if (self.block) {
               
               NSInteger startIndex =  self->selectedIndexPath.section * 12 + (self->selectedIndexPath.item + 1);
               NSInteger endIndex = self->selectedIndexPath2.section * 12 + (self->selectedIndexPath2.item + 1);
               
               NSString* m = nil;
    
               if ((self->selectedIndexPath.item + 1) > 9 ) {
                   m = [NSString stringWithFormat:@"%@%ld",self.dataArray[self->selectedIndexPath.section],self->selectedIndexPath.item + 1];
               }else{
                   m = [NSString stringWithFormat:@"%@0%ld",self.dataArray[self->selectedIndexPath.section],self->selectedIndexPath.item + 1];
               }
               self.block(YES, self->startDateLabel.text, self->endDateLabel.text,(m.integerValue), endIndex - startIndex + 1);
           }
           
           
           
           [self.navigationController popViewControllerAnimated:YES];
           
       }];;
    
}





#pragma mark - getters and setters
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        JHCollectionViewFlowLayout *fl = [[JHCollectionViewFlowLayout alloc]init];
        fl.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        fl.scrollDirection = UICollectionViewScrollDirectionVertical;
        fl.minimumInteritemSpacing = 0;
        fl.minimumLineSpacing = 0;
        fl.sectionHeadersPinToVisibleBounds = NO;
        //fl.sectionFootersPinToVisibleBounds = YES;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight +100, ScreenWidth, ScreenHeight- cl_kNavigationBarHeight - 100) collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
         [_collectionView registerNib:[UINib nibWithNibName:@"SelectMonthCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"SelectMonthReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SelectMonthReusableView"];
    }
    return _collectionView;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
