//
//  YHSearchInfoHistoryView.swift
//  galaxy
//
//  Created by edy on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSearchInfoHistoryView: UIView {
    
    var historyItems: [String] = []
//    var historyItems:[String] = ["几天2345", "阿", "萨法", "阿德"]
    
    var selectBlock: ((String) -> Void)?
    var deleteBlock: (() -> Void)?
    let interItemSpacing: CGFloat = 12.0 // 相邻单元格之间的水平间距
    let gap: CGFloat = 12.0
    let cellHeight: CGFloat = 30.0 // 单元格的固定高度

    lazy var titleLabel: UILabel =  {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 14)
        label.textColor = UIColor.yhGreyColor
        label.text = "历史搜索"
        return label
    }()
    
    lazy var deleteAllBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "home_history_delete"), for: .normal)
        btn.addTarget(self, action: #selector(didDeleteAllBtnClicked), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var collectionView: UICollectionView = {
        // 创建集合视图布局
        let layout = YHSearchItemLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = interItemSpacing
        
        // 创建集合视图
        let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .white
        // 注册自定义单元格
        collectView.register(YHSearchInfoHistoryCell.self, forCellWithReuseIdentifier: YHSearchInfoHistoryCell.cellReuseIdentifier)
        return collectView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        self.addSubview(titleLabel)
        self.addSubview(deleteAllBtn)
        self.addSubview(collectionView)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(20.0)
        }
        
        deleteAllBtn.snp.makeConstraints { make in
            make.width.height.equalTo(16)
            make.right.equalTo(-20)
            make.centerY.equalTo(titleLabel)
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(15.0)
            make.left.right.equalTo(titleLabel)
            make.bottom.equalToSuperview()
        }
    }
    
    func updateDataSource(_ arr: [String]) {
        historyItems.removeAll()
        historyItems.append(contentsOf: arr)
        self.collectionView.reloadData()
        titleLabel.isHidden = arr.count <= 0
        deleteAllBtn.isHidden = arr.count <= 0
    }
    
    @objc func didDeleteAllBtnClicked() {
        deleteBlock?()
    }
    
    // 计算文字宽度大小
    func getwith(font: UIFont, height: CGFloat, string: String) -> CGSize {
        let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        var strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: ceil(strSize.width), height: strSize.height)
    }
}

extension YHSearchInfoHistoryView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            
            return historyItems.count
        }
        
        // 返回每个单元格的大小
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            let size = self.getwith(font: UIFont.systemFont(ofSize: 12), height: 24, string: historyItems[indexPath.item])
            var width = size.width + gap*2.0
            if width > 226.0 {
                width = 226.0
            }
            return CGSize(width: width, height: cellHeight)
        }
        
        // 返回自定义单元格
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHSearchInfoHistoryCell.cellReuseIdentifier, for: indexPath) as? YHSearchInfoHistoryCell else { return UICollectionViewCell() }
            if 0 <= indexPath.item && indexPath.item < historyItems.count {
                cell.titleLabel.text = historyItems[indexPath.item]
            }
            return cell
        }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < historyItems.count {
            let text = historyItems[indexPath.item]
            selectBlock?(text)
        }
    }
}
