//
//  PQCustomSwitchView.swift
//  PQSpeed
//
//  Created by SanW on 2021/5/12.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import UIKit

class PQCustomSwitchView: UIView {
    /// 当前选中的item
    var currentItemBtn: UIButton?
    /// 按钮点击的回调
    var switchChangeHandle: ((_ sender: UIButton) -> Void)?
 
    override private init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    init(frame: CGRect, titles: [String], defaultIndex: Int = 1) {
        super.init(frame: frame)
        let itemWidth: CGFloat = frame.width / CGFloat(titles.count)
        for (index, itemTitle) in titles.enumerated() {
            let itemBtn = UIButton(type: .custom)
            //8 是每一个btn 的间隔
            itemBtn.frame = CGRect(x: CGFloat(index) * itemWidth + CGFloat(index) * 8, y: 0, width: itemWidth, height: frame.height)
            itemBtn.tag = index + 1
            itemBtn.setTitle(itemTitle, for: .normal)
            itemBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#959595"), for: .normal)
            itemBtn.setTitleColor(UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue), for: .selected)
            itemBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
  
            itemBtn.isSelected = index == (defaultIndex - 1)
            if index == (defaultIndex - 1) {
                itemBtn.isSelected = true
              
                currentItemBtn = itemBtn
                itemBtn.backgroundColor = UIColor(red: 0.239, green: 0.757, blue: 0.757, alpha: 0.15)
            }else{
                itemBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#F9F9F9")
            }
            itemBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
            itemBtn.addCorner(corner:5)
            addSubview(itemBtn)
        }
    }
 
    /// 按钮点击事件
    /// - Parameter sender: <#sender description#>
    /// - Returns: <#description#>
    @objc func btnClick(sender: UIButton) {
        currentItemBtn?.isSelected = false
        currentItemBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        currentItemBtn?.backgroundColor = UIColor.hexColor(hexadecimal: "#F9F9F9")
        sender.isSelected = true
        sender.backgroundColor = UIColor(red: 0.239, green: 0.757, blue: 0.757, alpha: 0.15)
//        sender.backgroundColor = .red
        currentItemBtn = sender
        if switchChangeHandle != nil {
            switchChangeHandle!(sender)
        }
 
    }
}
