//
//  MPCustomTabBarView.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/3/27.
//

import UIKit
///自定义tabBarView
class MPSideA_CustomTabBarView: UIView, instanceFromNibDelegate {
    @IBOutlet weak var bgImageView: UIImageView!{
        didSet{
            bgImageView.layer.masksToBounds = true
            bgImageView.layer.cornerRadius = 24*width
            bgImageView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
        }
    }
    @IBOutlet var tabBarItems: [MPSideA_CustomTabBarItem]!{
        didSet{
            //添加点击事件
            tabBarItems.forEach { item in
                item.isUserInteractionEnabled = true
                item.title = titles[item.tag]
                item.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(switchActionClick(_ :))))
            }
        }
    }
    private lazy var titles:[String] = ["Home","Center"]
    //当前选中item(默认为首位)
    private lazy var selectedItem:Int = 0
    override func awakeFromNib() {
        super.awakeFromNib()
        setUpLayout()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpLayout()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    deinit {
    }
    //布局
    private func setUpLayout() {
        backgroundColor = .clear
        //超出部分不切除
        layer.masksToBounds = false
        //默认首位item处于选中状态
        tabBarItems[0].isSelected = true
    }
    //点击事件
    @objc private func switchActionClick(_ sender:UITapGestureRecognizer) {
        endEditing(true)
        let tag = sender.view?.tag ?? 0
        //根据tag值传送
        guard selectedItem != tag else {
            //无效点击
            return
        }
        tabBarItems.forEach { item in
            item.isSelected = item.tag == tag
        }
        selectedItem = tag
        //发送页面切换通知
        NotificationCenter.notificationKey.post(notificationName: .switch_tabBarItem, object: tag)
    }
}
