//
//  YHCountryHotView.swift
//  galaxy
//
//  Created by EDY on 2024/3/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHCountryHotView: UIView {
    typealias HotBlock = (_ index: String) -> ()
    var hotBlock: HotBlock?
    var dataSource: [String]?{
        didSet {
            updateView()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpView() {
       
    }
    
    func updateView() {
        guard let dataSource = dataSource else { return }
        var x = 0
        var y = 0
        for i in 0..<dataSource.count {
            let string = dataSource[i]
            let font = UIFont.systemFont(ofSize: 13) // 设置字体样式及大小
            let maxWidth = KScreenWidth - 42 // label最大宽度限制
            // 创建NSAttributedString对象并指定字体属性
            let attributedText = NSMutableAttributedString(string: string)
            attributedText.addAttribute(.font, value: font, range: NSRange(location: 0, length: string.count))
             
            // 获取文本所需的高度和宽度
            var boundingBox = CGRect()
            boundingBox = NSString(string: string).boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin], attributes: [.font : font], context: nil)
            let width = boundingBox.size.width

            if CGFloat(x) + width + 24  > maxWidth {
                x = 0
                y = y + 1
            }
            
            let button = UIButton(type: .custom)
            button.setTitle(dataSource[i], for: .normal)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.setBackgroundColor(color: UIColor.contentBkgColor, forState: .normal)
            button.setBackgroundColor(color: UIColor.tipsColor.withAlphaComponent(0.08), forState: .highlighted)
            button.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
            button.layer.cornerRadius = 16
            button.tag = 3000 + i
            button.addTarget(self, action: #selector(exampleClick(sender:)), for: .touchUpInside)
            addSubview(button)
            button.snp.makeConstraints { make in
                make.left.equalTo(21 + x)
                make.top.equalTo(y * 44)
                make.height.equalTo(32)
                make.width.equalTo(width + 24)
            }
            x = x + Int(width) + 36
        }
    }
    
    @objc func exampleClick(sender: UIButton) {
        let tag = sender.tag - 3000
        if let block = hotBlock {
            block(dataSource?[tag] ?? "")
        }
    }
}
