//
//  UIView+TileSubviews.m
//  Gengmei
//
//  Created by wangyang on 2016/10/26.
//  Copyright © 2016年 更美互动信息科技有限公司. All rights reserved.
//

#import "UIView+TileSubviews.h"
#import "UIView+Layout.h"
@implementation UIView (TileSubviews)
- (CGFloat)layoutSubviews:(NSArray<UIView *> *)views
                  padding:(UIEdgeInsets)padding
                  spacing:(CGPoint)spacing
                 maxWidth:(CGFloat)maxWidth
              subviewSize:(CGSize (^)(NSUInteger idx))caculater {
    __block CGFloat allHeight = 0;
    __block UIView *preView;
    [views enumerateObjectsUsingBlock:^(UIView * obj, NSUInteger idx, BOOL *stop) {
        UIView *item = views[idx];
        CGSize size = item.intrinsicContentSize;
        if (caculater) {
            size = caculater(idx);
        }
        views[idx].size = size;

        if (idx == 0) {
            item.left = padding.left;
            item.top = padding.top;
            preView = item;
        } else {
            //如果当前button超出了屏幕，则换行
            NSInteger totleW = preView.right + spacing.x + size.width + padding.right;
            if (totleW > maxWidth) {
                item.left = padding.left;
                item.top = preView.bottom + spacing.y;
            }else{
                item.left = preView.right + spacing.x;
                item.top = preView.top;
            }
        }
        preView = item;
    }];

    allHeight = preView.bottom + padding.bottom;
    return allHeight;
}

- (CGFloat)layoutSubviews:(NSArray<UIView *> *)views
                  padding:(UIEdgeInsets)padding
                  spacing:(CGPoint)spacing
                 maxWidth:(CGFloat)maxWidth
               singleLine:(BOOL)singleLine
              subviewSize:(CGSize (^)(NSUInteger idx))caculater {
    __block CGFloat allHeight = 0;
    __block UIView *preView;
    [views enumerateObjectsUsingBlock:^(UIView * obj, NSUInteger idx, BOOL *stop) {
        UIView *item = views[idx];
        CGSize size = item.intrinsicContentSize;
        if (caculater) {
            size = caculater(idx);
        }
        views[idx].size = size;
        
        if (idx == 0) {
            item.left = padding.left;
            item.top = padding.top;
            preView = item;
        } else {
            //如果当前button超出了屏幕，则换行
            NSInteger totleW = preView.right + spacing.x + size.width + padding.right;
            
            if (totleW > maxWidth) {
                if (singleLine) {
                    [item removeFromSuperview];
                } else {
                    item.left = padding.left;
                    item.top = preView.bottom + spacing.y;
                    preView = item;
                }
            }else{
                item.left = preView.right + spacing.x;
                item.top = preView.top;
                preView = item;
            }
        }
    }];
    
    allHeight = preView.bottom + padding.bottom;
    return allHeight;
}

@end
