//
//  NewUtilityView.m
//  zhuxun
//
//  Created by winsoft on 17/4/1.
//
//

#import "CSFileTypeClassView.h"
#import "CustomButton.h"

#define UtilisIconWidth 50
#define UtilisIconHeight 72

#define OnePageUtilityCellWidth self.frame.size.width
#define OnePageUtilityCellHeight CSFileTypeClassViewH

#define MaxUtilisCountOnePage 8
#define LineNum 4
#define RowNum 2

#define OnePageUtilityCellIdentifier @"OnePageUtilityCellIdentifier"
@interface CSFileTypeClassView()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic , weak) UICollectionView *mainCollectionView;
@property (nonatomic , strong) NSMutableArray *utilityIconPagesArray;//总的utiilitys
@property (nonatomic , strong) NSMutableArray *utilityTitlePagesArray;
@property (nonatomic , strong) NSArray *fileTypeArray;
@property (nonatomic , assign) NSInteger utilityPagesCount;//总的utiility count
@property (nonatomic, assign)NSInteger currentPageIndex;
@end
@implementation CSFileTypeClassView

- (NSMutableArray *)utilityIconPagesArray
{
    if (!_utilityIconPagesArray) {
        _utilityIconPagesArray = [NSMutableArray array];
    }
    
    return _utilityIconPagesArray;
    
}

- (NSMutableArray *)utilityTitlePagesArray
{
    if (!_utilityTitlePagesArray) {
        _utilityTitlePagesArray = [NSMutableArray array];
    }
    
    return _utilityTitlePagesArray;
    
}

- (instancetype)init
{
    if (self = [super init]) {
                
        [self.layer setBorderWidth:0.5];
        
        [self.layer setBorderColor:RGB(188, 188, 188).CGColor];
        
        self.backgroundColor = [UIColor whiteColor];
        
        NSArray *iconArray = @[@"file_all_normal",@"file_images_normal",@"file_text_normal",@"file_viedo_normal",@"file_music_normal",@"file_unknown_normal"];
        NSArray *titleArray = @[@"全部",@"照片",@"文档",@"视频",@"音频",@"其他"];
        self.fileTypeArray = @[@(CSFileTypeAll),@(CSFileTypePic),@(CSFileTypeDoc),@(CSFileTypeVideo),@(CSFileTypeAudio),@(CSFileTypeAudioOther)];
        
        //实际多少页
        NSInteger pageCount = (iconArray.count / (LineNum * RowNum));
        if (iconArray.count % (LineNum * RowNum) != 0) {
            pageCount += 1;
        }
        self.utilityPagesCount = pageCount;
        
        for (int i = 0; i< self.utilityPagesCount; i ++) {
            
            NSInteger loc = i * (LineNum * RowNum );
            
            NSInteger len = 0;
            //最大值.
            if (i  < self.utilityPagesCount - 1) {
                len = (LineNum * RowNum);
            }else len = iconArray.count - i*(LineNum * RowNum);
            
            NSArray *onePageIconUtitlityArray = [iconArray subarrayWithRange:NSMakeRange(loc, len)];
            NSArray *onePageTitleUtitlityArray = [titleArray subarrayWithRange:NSMakeRange(loc, len)];
            [self.utilityIconPagesArray addObject:onePageIconUtitlityArray];
            [self.utilityTitlePagesArray addObject:onePageTitleUtitlityArray];
            
            
        }
        
        CGFloat itemsW = OnePageUtilityCellWidth;
        //(deviceWidth - (collectionViewItmesInRow + 1)*mainViewMargin)/3.0f;
        CGFloat itemsH = OnePageUtilityCellHeight;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake(itemsW, itemsH);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        UICollectionView *collectionView  = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:flowLayout];
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.pagingEnabled = YES;
        //能否和tableview一样设置headerview的效果..
        
//        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        [collectionView registerClass:[CSFileOnePageUtilityCell class] forCellWithReuseIdentifier:OnePageUtilityCellIdentifier];
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [self addSubview:collectionView];
        
        self.mainCollectionView = collectionView;

        
    }
    
    return self;
}

- (void)reloadData
{
    [self.mainCollectionView reloadData];
}
#pragma mark --
#pragma mrak -- collectionviewdatasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.utilityIconPagesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CSFileOnePageUtilityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:OnePageUtilityCellIdentifier forIndexPath:indexPath];
    //    cell.backgroundColor = [UIColor redColor];
    if (cell == nil) {
        
        NSLog(@"生成cell失败");
        
    }
    
    __weak typeof(self)weakself = self;
    
    cell.utilityOperateBlock = ^(CSFileType type)
    {
        if (weakself.utilityOperateBlock) {
            
            NSNumber *typeNum = weakself.fileTypeArray[weakself.currentPageIndex * (LineNum * RowNum - 1) + type];
            
            weakself.utilityOperateBlock((CSFileType)typeNum.integerValue);
        }
    };
    
    [cell setUitilityIconsArray:self.utilityIconPagesArray[indexPath.row] titlesArray:self.utilityTitlePagesArray[indexPath.row]];
    
    return cell;
    
}

#pragma mark -
#pragma mark - UIActivityItemSource


#pragma mark -
#pragma mark - uicollectionviewlayoutdatasource
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(OnePageUtilityCellWidth ,OnePageUtilityCellHeight);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0, 0, 0 ,0);
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

{
    return  0;
}


- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.currentPageIndex = collectionView.contentOffset.x / collectionView.self.width;
}



#pragma mrak --

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.mainCollectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
    
}



@end

@interface CSFileOnePageUtilityCell()
@property (nonatomic , weak)CSFileOnePageUtilityView *pageUtilityView;
@end
@implementation CSFileOnePageUtilityCell
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        CSFileOnePageUtilityView *pageUtilityView = [[CSFileOnePageUtilityView alloc]init];
        
        
        __weak typeof(self)weakself = self;
        
        pageUtilityView.utilityOperateBlock = ^(CSFileType csFileType){
        
            if (weakself.utilityOperateBlock) {
                
                weakself.utilityOperateBlock(csFileType);
            }
            
        };
        [self.contentView addSubview:pageUtilityView];
        self.pageUtilityView = pageUtilityView;
        
    }
    
    return self;
}

- (void)setUitilityIconsArray:(NSArray *)iconArray titlesArray:(NSArray *)titleArray
{
    [self.pageUtilityView setUitilityIconsArray:iconArray titlesArray:titleArray];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.pageUtilityView.frame = self.bounds;
}
@end


@interface CSFileOnePageUtilityView()


@end


@implementation CSFileOnePageUtilityView
- (instancetype)init
{
    if(self = [super init])
    {
        

        for (int i = 0 ; i < RowNum; i ++) {
            for (int j = 0 ; j < LineNum; j++) {
                
                
                CustomButton *customBtn = [[CustomButton  alloc]initCustomBtnWithImageDirection:ImagePostionTop imageViewSize:CGSizeMake(UtilisIconWidth, UtilisIconWidth) imageLabelMargin:5 titleLabelFont:[UIFont systemFontOfSize:14] imageIcon:@"utility_image" selectIcon:nil title:@"更多" btnWidth:UtilisIconWidth];
                [customBtn setTitleColor:RGB(165, 165, 165) forState:UIControlStateNormal];
              
                customBtn.tag = i * LineNum + j;
                
                [self addSubview:customBtn];
                

                [customBtn addTarget:self action:@selector(utilityAction:) forControlEvents:UIControlEventTouchUpInside];

                

                
            }
        }
        

    }
    
    return self;

}

- (void)utilityAction:(CustomButton *)btn
{
    if (self.utilityOperateBlock) {
        self.utilityOperateBlock((CSFileType)btn.tag);
    }
}

- (void)setUitilityIconsArray:(NSArray *)iconArray titlesArray:(NSArray *)titleArray
{
   for (CustomButton *customBtn in self.subviews) {
    
      if ([customBtn isKindOfClass:[CustomButton class]]) {
          
          if (customBtn.tag > iconArray.count - 1 || customBtn.tag > titleArray.count - 1) {
              
            [customBtn setImage:nil forState:UIControlStateNormal];;
            [customBtn setTitle:nil forState:UIControlStateNormal];
          }else{
              [customBtn setImage:[UIImage imageNamed:iconArray[customBtn.tag]] forState:UIControlStateNormal];
              
              [customBtn setTitle:titleArray[customBtn.tag] forState:UIControlStateNormal];
          }
      }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    

    for (CustomButton *customBtn in self.subviews) {
        
        if ([customBtn isKindOfClass:[CustomButton class]]) {
            
            CGFloat btnMarginX = (self.size.width - (LineNum * UtilisIconWidth)) / (LineNum + 1);
            
            CGFloat btnMarginY =  10;
            
            CGFloat btnX = (customBtn.tag % LineNum) * (UtilisIconWidth + btnMarginX) + btnMarginX;
            
            CGFloat btnY = (customBtn.tag / LineNum) * (customBtn.customBtnHeight + btnMarginY) + btnMarginY;
            
            CGFloat btnW = UtilisIconWidth;
            
            CGFloat btnH = customBtn.customBtnHeight;
            
            customBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
            
            
        }
        
    }
    

    
    
}
@end