//
//  PQSelectedMaterialListView.swift
//  PQSpeed
//
//  Created by SanW on 2021/5/16.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import UIKit
import BFMaterialKit

class PQSelectedMaterialListView: UIView {
    var photoData: [PQEditVisionTrackMaterialsModel] = Array<PQEditVisionTrackMaterialsModel>.init() // 相册数据
    var deletedMaterialHandle: ((_ materialData: PQEditVisionTrackMaterialsModel?, _ isDissmiss: Bool) -> Void)? // 删除已选素材回调
    var detailMaterialHandle: ((_ indexPath: IndexPath, _ currentMaterialData: PQEditVisionTrackMaterialsModel?) -> Void)? // 点击详情
    lazy var photoCollectionView: UICollectionView = {
        let photoFlowLayout = UICollectionViewFlowLayout()
        photoFlowLayout.itemSize = CGSize(width: 74, height: 74)
        photoFlowLayout.minimumLineSpacing = cDefaultMargin
        photoFlowLayout.minimumInteritemSpacing = 0
        photoFlowLayout.scrollDirection = .horizontal
        let photoCollectionView = UICollectionView(frame: bounds, collectionViewLayout: photoFlowLayout)
        photoCollectionView.register(BFChoseMaterialCell.self, forCellWithReuseIdentifier: String(describing: BFChoseMaterialCell.self))
        photoCollectionView.showsVerticalScrollIndicator = false
        photoCollectionView.showsHorizontalScrollIndicator = false
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        photoCollectionView.backgroundColor = UIColor.clear
        if #available(iOS 11.0, *) {
            photoCollectionView.contentInsetAdjustmentBehavior = .never
        } else {}
        return photoCollectionView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = PQBFConfig.shared.styleBackGroundColor
        addSubview(photoCollectionView)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        BFLog(1, message: "meterialview release")
    }

    /// 添加新素材
    /// - Parameter itemData: <#itemData description#>
    /// - Returns: <#description#>
    func addMaterialData(materialData: PQEditVisionTrackMaterialsModel) {
        let temp = photoData.firstIndex { item in
            item.asset == materialData.asset
        }
        if temp == nil, materialData.isSelected {
            photoData.append(materialData)
            photoCollectionView.reloadData()
            photoCollectionView.scrollToItem(at: IndexPath(item: photoData.count - 1, section: 0), at: .right, animated: true)
        } else if temp != nil, !materialData.isSelected {
            photoData.remove(at: temp ?? 0)
            photoCollectionView.reloadData()
        }
    }
}

extension PQSelectedMaterialListView: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return photoData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = BFChoseMaterialCell.choseMaterialCell(collectionView: collectionView, indexPath: indexPath)
        cell.isShowMediaTag = false
        cell.isAdded = true
        cell.materialData = photoData[indexPath.item].asset
        cell.materialClicHandle = { [weak self] _, _ in
            if self?.deletedMaterialHandle != nil {
                self?.deletedMaterialHandle!(self?.photoData[indexPath.item], (self?.photoData.count ?? 0) <= 1)
            }
            self?.photoData[indexPath.item].isSelected = false
            self?.photoData.remove(at: indexPath.item)
            collectionView.reloadData()
        }
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if detailMaterialHandle != nil {
            detailMaterialHandle!(indexPath, photoData[indexPath.item])
        }
    }
}
