//
//  UICollectionView+Ext.swift
//  PQCreativeCommunity
//
//  Created by SanW on 2021/8/4.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import Foundation
import MJRefresh

extension UICollectionView{
    /// 获取当前cell
    /// - Returns: <#description#>
    func visibleCell() -> UICollectionViewCell? {
        let visibleRect = CGRect(origin: contentOffset, size: bounds.size)
        let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
        guard let visibleIndexPath = indexPathForItem(at: visiblePoint) else { return nil }
        return cellForItem(at: visibleIndexPath)
    }

    /// 添加刷新组件
    /// - Parameters:
    ///   - scroller: <#scroller description#>
    ///   - type: 1-头部跟尾部 2-头部 3-尾部
    public func addRefreshView(type: REFRESH_TYPE = .REFRESH_TYPE_ALL, refreshHandle: ((_ isHeader: Bool) -> Void)?) {
        if type == .REFRESH_TYPE_ALL || type == .REFRESH_TYPE_HEADER {
            let header = MJRefreshNormalHeader.init {
                if refreshHandle != nil {
                    refreshHandle!(true)
                }
            }
            header.setTitle("下拉刷新", for: .willRefresh)
            header.setTitle("正在刷新...", for: .refreshing)
            header.setTitle("松开刷新", for: .pulling)
            header.setTitle("下拉刷新", for: .idle)
            header.lastUpdatedTimeLabel?.isHidden = true
            mj_header = header
        }
        if type == .REFRESH_TYPE_ALL || type == .REFRESH_TYPE_FOOTER {
            // MJRefreshBackNormalFooter 不会附在上面
            // MJRefreshAutoFooter 不会便宜
            let footer = MJRefreshBackNormalFooter.init {
                if refreshHandle != nil {
                    refreshHandle!(false)
                }
            }
            footer.setTitle("暂时没有更多了", for: .noMoreData)
            footer.setTitle("精彩内容正在加载中...", for: .refreshing)
            mj_footer = footer
        }
        
        if type == .REFRESH_TYPE_AUTOFOOTER {
            let footer = MJRefreshAutoNormalFooter.init {
                if refreshHandle != nil {
                    refreshHandle!(false)
                }
            }
            footer.triggerAutomaticallyRefreshPercent = -70
            footer.setTitle("暂时没有更多了", for: .noMoreData)
            footer.setTitle("精彩内容正在加载中...", for: .refreshing)
            mj_footer = footer
        }
    }

    func indexPathsForElements(in rect: CGRect) -> [IndexPath] {
        let allLayoutAttributes = collectionViewLayout.layoutAttributesForElements(in: rect)!
        return allLayoutAttributes.map { $0.indexPath }
    }
}
