//
//  PQCollectionViewFlowlayout.swift
//  PQSpeed
//
//  Created by SanW on 2020/5/26.
//  Copyright © 2020 BytesFlow. All rights reserved.
//


import Photos
import UIKit

class PQCollectionViewFlowlayout: UICollectionViewFlowLayout {
    // 总列数
    var columnCount: Int = 0
    // 数据数组
    var findList = [Any]()
    // 整个高度
    private var maxH: Int?
    // 头部高度
    var headerH: CGFloat = 100
    // 所有item的属性
    fileprivate var layoutAttributesArray = [UICollectionViewLayoutAttributes]()

    override func prepare() {
        let contentWidth: CGFloat = (collectionView?.bounds.size.width)! - sectionInset.left - sectionInset.right
        let marginX = minimumInteritemSpacing
        let itemWidth = (contentWidth - marginX * CGFloat(columnCount - 1)) / CGFloat(columnCount)
        computeAttributesWithItemWidth(CGFloat(itemWidth))
    }

    /// 根据itemWidth计算布局属性
    func computeAttributesWithItemWidth(_ itemWidth: CGFloat) {
        // 定义一个列高数组 记录每一列的总高度
        var columnHeight = [Int](repeating: Int(sectionInset.top + headerH), count: columnCount)
        // 定义一个记录每一列的总item个数的数组
        var columnItemCount = [Int](repeating: 0, count: columnCount)
        var attributesArray = [UICollectionViewLayoutAttributes]()

        // 添加头部属性
        let headerAttr: UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(item: 0, section: 0))
        headerAttr.frame = CGRect(x: 0, y: CGFloat(0), width: collectionView!.bounds.size.width, height: headerH)
        attributesArray.append(headerAttr)
        // 给属性数组设置数值
        // self.layoutAttributesArray = attributesArray

        // 遍历数据计算每个item的属性并布局
        var index = 0
        for data in findList {
            var scale: CGFloat = 0
            if data is PQVideoListModel {
                scale = (data as! PQVideoListModel).height / (data as! PQVideoListModel).width
            } else if data is PQEditVisionTrackMaterialsModel {
                scale = CGFloat((data as! PQEditVisionTrackMaterialsModel).itemHeight / (data as! PQEditVisionTrackMaterialsModel).itemWidth)
            } else {
                scale = 0
            }
            let indexPath = IndexPath(item: index, section: 0)
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            // 找出最短列号
            let minHeight: Int = columnHeight.sorted().first!
            let column = columnHeight.firstIndex(of: minHeight)
            // 数据追加在最短列
            columnItemCount[column!] += 1
            let itemX = (itemWidth + minimumInteritemSpacing) * CGFloat(column!) + sectionInset.left
            let itemY = minHeight
            // 等比例缩放 计算item的高度
            let itemH = Int(itemWidth * scale)
            // 设置frame
            attributes.frame = CGRect(x: itemX, y: CGFloat(itemY), width: itemWidth, height: CGFloat(itemH))

            attributesArray.append(attributes)
            // 累加列高
            columnHeight[column!] += itemH + Int(minimumLineSpacing)
            index += 1
        }

        // 找出最高列列号
        let maxHeight: Int = columnHeight.sorted().last!
        let column = columnHeight.firstIndex(of: maxHeight)
        // 根据最高列设置itemSize 使用总高度的平均值
        var itemH = 0

        if findList.count > 0 {
            itemH = (maxHeight - Int(minimumLineSpacing) * (columnItemCount[column!] + 1)) / columnItemCount[column!]
        }
        itemSize = CGSize(width: itemWidth, height: CGFloat(itemH))
        // 给属性数组设置数值
        layoutAttributesArray = attributesArray
        maxH = maxHeight + 30
    }

    override func layoutAttributesForElements(in _: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return layoutAttributesArray
    }

    /// 重写设置contentSize
    override var collectionViewContentSize: CGSize {
        get {
            return CGSize(width: (collectionView?.bounds.width)!, height: CGFloat(maxH!))
        }
        set {
            self.collectionViewContentSize = newValue
        }
    }
}
