//
//  DateCalibrationViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2017/3/15.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "DateCalibrationViewController.h"
#import "CalibrationCollectionViewCell.h"
#import "CalibrationDetailCollectionCell.h"
#import "TriangleIndicatorView.h"
#import "CustomTOForumtypeEntity.h"

@interface DateCalibrationViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong) TriangleIndicatorView *triangleView;

/**
 时间轴数据
 */
@property (nonatomic,strong) TimeLineTypeResponse *timeLineResponse;

/**
 当前年下标
 */
@property (nonatomic,assign) NSInteger yearNumber;

/**
 当前月下标
 */
@property (nonatomic,assign) NSInteger monthNumber;

@end

@implementation DateCalibrationViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getTimeLineDatas];
}

#pragma mark -获取数据
- (void)getTimeLineDatas
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefaultWithView:self.view];
    [HTTP networkWithDictionaryRequestWithURL:SERVERREQUESTURL(GETTIMELINE) withRequestType:GET withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefaultWithView:weakSelf.view];
        if (RESULT(returnValue)) {
             TimeLineTypeResponse *response = [[TimeLineTypeResponse alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf disposeData:response];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -处理数据
- (void)disposeData:(TimeLineTypeResponse *)response
{
    for (TimeLineType *entity in response.list) {
        for (CustomTOForumtypeEntity *timeEntity in entity.list) {
            timeEntity.type = [self disposeTimeLine:timeEntity];
        }
    }
    self.timeLineResponse = response;
    [self.calibrationCollectionView reloadData];
    [self.calibrationCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.timeLineResponse.list.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    //等待0.3s秒(刷新主界面)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.yearNumber = self.timeLineResponse.list.count-1;
        [self checkAnimationTriangleView:self.yearNumber returnMonthBlock:^(NSInteger monthNumber) {
            [self refreshForumTypeList:self.yearNumber monthNumber:monthNumber];
        }];
    });
}

#pragma mark -判断时间轴是否有效
- (TIMELINE_STATE)disposeTimeLine:(CustomTOForumtypeEntity *)entity
{
    NSInteger month = [[NSDate date] month];
    NSInteger year = [[NSDate date] year];
    if ([entity.year integerValue] == year) {
        if ([entity.month integerValue] > month) {
            return NotChoose;
        }else if ([entity.month integerValue] == month) {
            return Selected;
        }else {
            return Default;
        }
    }else if ([entity.year integerValue] > year) {
        if ([entity.month integerValue] == month) {
            return Selected;
        }
        return Default;
    }else if ([entity.year integerValue] < year) {
        if ([entity.month integerValue] == month) {
            return Selected;
        }
        return Default;
    }
    return NotChoose;
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.calibrationFlowLayout.itemSize = CGSizeMake(ScreenWidth-40, 60);
    self.calibrationFlowLayout.minimumInteritemSpacing = 0;
    self.calibrationFlowLayout.minimumLineSpacing = 0;
    [Notification addObserver:self selector:@selector(animationTriangleView:) name:ANIMATION object:nil];
    [self.view addSubview:self.triangleView];
}

#pragma mark -<UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.timeLineResponse.list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CalibrationCollectionViewCell *calibrationCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalibrationCollectionViewCell" forIndexPath:indexPath];
    calibrationCell.timeLineEntity = self.timeLineResponse.list[indexPath.item];
    return calibrationCell;
}

#pragma mark -滑动结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    NSInteger index = offset.x/self.view.frame.size.width;
    self.yearNumber = index;
    TimeLineType *entity = self.timeLineResponse.list[self.yearNumber];
    self.triangleView.yearString = entity.year;
    [self checkAnimationTriangleView:index returnMonthBlock:nil];
    [self refreshForumTypeList:index monthNumber:self.monthNumber];
}

#pragma mark -监听子控制器点击通知
- (void)animationTriangleView:(NSNotification *)object
{
    CalibrationDetailCollectionCell *cell = object.object;
    self.monthNumber = cell.indexPath.item;
    for (TimeLineType *timeLineType in self.timeLineResponse.list) {
        BOOL isSelected = NO;
        for (int i=0; i<timeLineType.list.count; i++) {
            CustomTOForumtypeEntity *entity = timeLineType.list[i];
            if (i == cell.indexPath.item) {
                if (entity.type) {
                    entity.type = Selected;
                    isSelected = YES;
                }
            }else {
                if (entity.type == Selected) {
                    entity.type = Default;
                }
            }
            //本次循环结束判断是否有选中时间轴
            if (i == timeLineType.list.count - 1) {
                if (!isSelected) {
                    [self checkTimeLineSelected:timeLineType];
                }
            }
        }
    }
    [self.calibrationCollectionView reloadData];
    [self mobileTriangleView:cell];
    [self refreshForumTypeList:self.yearNumber monthNumber:self.monthNumber];
}

#pragma mark -时间轴选中后通知
- (void)checkAnimationTriangleView:(NSInteger)yearNumber returnMonthBlock:(void(^)(NSInteger month))monthNumber
{
    TimeLineType *timeLineType = self.timeLineResponse.list[yearNumber];
    NSInteger selected = 0;
    for (int i=0; i<timeLineType.list.count; i++) {
        CustomTOForumtypeEntity *entity = timeLineType.list[i];
        if (entity.type == Selected) {
            if (monthNumber) {
                monthNumber(selected);
            }
            selected = i;break;
        }
    }
    CalibrationCollectionViewCell *calibrationCell = (CalibrationCollectionViewCell *)[self.calibrationCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:yearNumber inSection:0]];
    CalibrationDetailCollectionCell *calibrationDetailCell = (CalibrationDetailCollectionCell *)[calibrationCell.detailsVc.calibrationDetailCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:selected inSection:0]];
    [self mobileTriangleView:calibrationDetailCell];
}

#pragma mark -校验是否选中
- (void)checkTimeLineSelected:(TimeLineType *)timeLineType
{
    NSInteger number = timeLineType.list.count-1;
    for (NSInteger i=number; i>=0; i--) {
        CustomTOForumtypeEntity *entity = timeLineType.list[i];
        if (entity.type) {
            entity.type = Selected;break;
        }
    }
}

#pragma mark -刷新帖子分类列表
- (void)refreshForumTypeList:(NSInteger)yearNumber monthNumber:(NSInteger)monthNumber
{
    TimeLineType *timeLineType = self.timeLineResponse.list[yearNumber];
    CustomTOForumtypeEntity *entity = timeLineType.list[monthNumber];
    NSString *fidString = entity.fid;
    //判断滑动结束后指向的时间轴是否有效.
    if (entity.type != Selected) {
        for (int i=0; i<timeLineType.list.count; i++) {
            CustomTOForumtypeEntity *newEntity = timeLineType.list[i];
            if (newEntity.type == Selected) {
                fidString = newEntity.fid;break;
            }
        }
    }
    //判断是否在当前年、当前月
    BOOL boolValue = YES;
    if ([timeLineType.year isEqualToString: [NSString stringWithFormat:@"%ld",(unsigned long)[[NSDate date] year]]]) {
        if ([entity.month isEqualToString: [NSString stringWithFormat:@"%ld",(unsigned long)[[NSDate date] month]]]) {
            boolValue = NO;
        }
    }
    
    [Notification postNotificationName:REFRESH_FROUMLIST object:@(boolValue)];
    [Notification postNotificationName:REFRESH_FROUMLIST object:fidString];
}

#pragma mark -移动指示三角
- (void)mobileTriangleView:(CalibrationDetailCollectionCell *)cell
{
    CGRect toWindowFrame = [self.view convertRect:cell.monthLabel.frame fromView:cell.contentView];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        CGRect frame = self.triangleView.frame;
        frame.origin.x = toWindowFrame.origin.x + toWindowFrame.size.width/2.0 - self.triangleView.width/2.0;
        self.triangleView.frame = frame;
    } completion:nil];
}

#pragma mark -lazy
- (TriangleIndicatorView *)triangleView
{
    if (!_triangleView) {
        _triangleView = [[TriangleIndicatorView alloc] initializeView:CGRectMake(-100, 45, 25, 15) contentLabel:[NSString stringWithFormat:@"%ld",[[NSDate date] year]]];
    }
    return _triangleView;
}
@end
