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

import UIKit

class HomeTabbarView:UIView {
    
    private var tabbarItems:[HomeTabbarItem] = []
    
    var indexCallBack:callBack<Any> = {index in }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        getData()
        
        setupUI()
        
        addButton()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = .white
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.setShadow(cornerRadius: 40, sColor: UIColor.colorWithHex(hexStr: "#0082FF"), offset: CGSize(width: 0, height:-2),opacity: 0.1)
    }
    
    private func addButton() {
        
        let cW:CGFloat = (self.width - 32) / Double(tabbarItems.count)
        let cH:CGFloat = 56
        
        for (index,item) in tabbarItems.enumerated() {
            
            let btn:UIButton = UIButton()
            
            btn.setImage(UIImage(named: item.normalImage), for: .normal)
            btn.setTitleColor(UIColor.colorWithHex(hexStr: black6Color), for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 10, weight: .bold)
            btn.setTitle(item.text, for: .normal)
            btn.addTarget(self, action: #selector(tabbarClick(_:)), for: .touchUpInside)
            btn.width = cW
            btn.tag = 10 + index
            btn.height = cH
            btn.y = 6//safeHeight == 0 ? 6 : 12
            btn.x = 16 + Double(index) * cW
            btn.changBtnWithStytl(btnStyle: .imageTop, margin: 2)
            self.addSubview(btn)
        }
    }
    
    private func getData() {
        
        tabbarItems = loadTabbarImtesSONFromBundle() ?? []
        
    }
    
    @objc func tabbarClick(_ btn:UIButton) {
        let tm = tabbarItems[btn.tag % 10]
        indexCallBack(tm.text)
//        let  btnText = btn.titleLabel?.text
//        
//        for (index, item) in tabbarItems.enumerated() {
//            if item.text == btnText {
//                indexCallBack(index)
//            }
//        }
        
    }
    
}
