//
//  HomeTitleCollectionCell.swift
//  PhoneManager
//
//  Created by edy on 2025/3/21.
//

import UIKit
import SnapKit

class HomeTitleCollectionCell:UICollectionViewCell {
    
    static let identifiers = "HomeTitleCollectionCellID"
    
    private var titleLabel: UILabel!
    
    public var fileLabel:UILabel?
    
    public var collectionView: UICollectionView?
    
    private var nextImage:UIImageView?
    
    private var assetsModels:[ImageCollectionModel] = []
    
    var homeTititlAction:((_ idx:Int)->Void) = { idx in}
    
    var firstID:String?
    
    var hadLoadFirst:((Bool) ->Void)?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        addSubview1()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        self.backgroundColor = .white
        self.layer.cornerRadius = 12
        self.layer.masksToBounds = true
        
        titleLabel = UILabel()
        titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        titleLabel.textColor = UIColor.colorWithHex(hexStr: black3Color)
        
        fileLabel = UILabel()
        fileLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        fileLabel?.textColor = UIColor.colorWithHex(hexStr: mColor)
        
        let flowlayout:UICollectionViewFlowLayout =  UICollectionViewFlowLayout()
        flowlayout.scrollDirection = .horizontal
        flowlayout.minimumLineSpacing = 4
        
        collectionView = UICollectionView.init(frame: CGRectMake(0, 0 , ScreenW , ScreenH), collectionViewLayout: flowlayout)
        collectionView?.backgroundColor = .clear
        
        collectionView?.decelerationRate = UIScrollView.DecelerationRate.fast;
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
        collectionView?.register(ImageCollectionCell.self, forCellWithReuseIdentifier: ImageCollectionCell.identifiers)
        collectionView?.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: marginLR)
        
        collectionView?.dataSource = self
        collectionView?.delegate = self
        collectionView?.isUserInteractionEnabled = true
        self.contentView.isUserInteractionEnabled = true
        self.isUserInteractionEnabled = true
        nextImage = UIImageView(image: UIImage(named: "icon_left_setting"))
        
    }
    
    func addSubview1() {
        
        addSubview(titleLabel!)
        addSubview(fileLabel!)
        addSubview(collectionView!)
        addSubview(nextImage!)
    }
    
    var model:HomePhotosModel? {
        didSet {
            guard let model = model else{
                return
            }
            
            titleLabel.text = model.folderName
            titleLabel.sizeToFit()
            
            var count = 0
            
            for array in model.assets {
                count += array.count
            }
            
            fileLabel?.text = "\(count)" + " Photos " + (model.allFileSize > 0 ? "(\(formatFileSize(model.allFileSize)))" : "(Calculating...)")
            fileLabel?.sizeToFit()
        
        }
    }
    
    
    func reloadUIWithModel(model:HomePhotosModel?){
        guard let model = model else { return }
        self.model = model
        
    }
    
    func reloadCoverData(_ assets:[AssetModel]){
        assetsModels.removeAll()
        assetsModels = assets.compactMap({ model in
            return ImageCollectionModel.init(asset: model)
        })
        Print("刷新头部封面\(self)",assets.count)
        collectionView?.reloadData()
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        titleLabel.snp.makeConstraints({ make in
            
            make.top.left.equalTo(8)
        })
        
//        titleLabel.sizeToFit()
        
        fileLabel?.snp.makeConstraints({ make in
            
            make.top.equalTo(titleLabel!)
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.right.equalToSuperview().offset(-34)
        })
        
//        fileLabel?.sizeToFit()
        
        collectionView?.snp.makeConstraints({ make in
            make.left.equalTo(8)
            make.bottom.equalTo(0)
            make.right.equalTo(-8)
            make.top.equalTo(titleLabel.snp.bottom).offset(0)
        })
        
        nextImage?.snp.makeConstraints({ make in
            
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.right.equalToSuperview().inset(12)
            make.width.height.equalTo(20)
        })
    }
    
}

extension HomeTitleCollectionCell:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return assetsModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCollectionCell.identifiers, for: indexPath) as! ImageCollectionCell
        
        cell.model = assetsModels[indexPath.row]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         // 计算 cell 宽度
        let width = max(0, collectionView.height - 16) // 使用实际的宽度计算方法
        let height = max(0, collectionView.height - 16) // 使用实际的高度计算方法
        return CGSize(width:width, height: height)  // 宽高相等，形成网格
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 4  // 设置列间距
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        homeTititlAction(1)
    }
    

   
    
}
