//
//  SWMultiButtonView.swift
//  SWScrollPageViewController
//
//  Created by Alan on 2019/9/7.
//  Copyright © 2019 liuhongli. All rights reserved.
//

import UIKit

// 按钮点击事件的代理
protocol SWMultiButtonActionDelegate {
    func multiButtonAction(sender: UIButton)
}

/// 多个按钮： 两个或两个以上的按钮视图
class SWMultiButtonView: UIView {
    open var delegate: SWMultiButtonActionDelegate?
    /// 标题数组
    open var titles = [String]()
    /// 标题 font size
    open var itemFont: UIFont = UIFont.systemFont(ofSize: 15)
    /// 选中标题的 font size
    open var selectedItemFont: UIFont = UIFont.systemFont(ofSize: 15)
    /// 未选中状态下标题颜色
    open var normalTitleColor: UIColor = UIColor(red:51/255, green:51/255, blue:51/255, alpha:1.00)
    /// 选中状态下标题颜色
    open var selectedTitleColor: UIColor = UIColor(red:254/255, green:172/255, blue:44/255, alpha:1.00)
    /// tipView颜色
    open var tipColor: UIColor = UIColor(red:254/255, green:172/255, blue:44/255, alpha:1.00)
    /// tipView 高度
    open var tipViewHeight: CGFloat = 3
    /// 选中button的索引
    //    open var selectedIndex: Int = 0
    /// 选中button的索引
    open var selectedIndex: Int = 0 {
        didSet{
            if buttonList.count > selectedIndex {
                self.selected_button_action(sender: buttonList[selectedIndex])
            }
        }
    }
    
    /// 是否显示 tipView
    open var isTipViewHidden: Bool = false {
        didSet {
            if self.tipView != nil {
                if isTipViewHidden == true {
                    self.tipView.isHidden = true
                }
                else {
                    self.tipView.isHidden = false
                }
            }
        }
    }
    /// tipView宽度的缩小倍率, tipViewScale>=1, 当为0时 tipView的宽度(btnWidth - 20); 其它值 (btnWidth / tipViewScale)
    open var tipViewScale: CGFloat = 0
    /// tipView的圆角,设置时应 <=tipViewHeight/2
    open var tipViewCornerRadius: CGFloat = 0
    /// tipView是否显示动画
    open var isTipViewAnimate: Bool = true
    /// tipView的动画速率
    open var velocity: CGFloat = 1000
    
    /// 底部分割线
    open var seperateLine: UIView!
    open var isSeperateLineHidden: Bool = true {
        didSet {
            if self.seperateLine != nil {
                self.seperateLine.isHidden = isSeperateLineHidden
            }
        }
    }
    
    /// 滚动在x轴的增量
    open var delta_x: CGFloat = 0 {
        didSet {
            if self.tipView != nil {
                self.tipView.frame =  CGRect(x: self.tipview_offset_x + delta_x, y: btnHeight - tipViewHeight, width: tipViewWidth, height: tipViewHeight)
            }
        }
    }
    
    ///////////如果type == 1 可选择性设置以下属性
    /// 按钮的类型，0普通, 1具有子标题
    open var type: Int = 0
    /// 按钮标题的缩进
    open var titleEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    /// 子标题
    open var subtitles = [String]()
    /// 子标题的 font size
    open var subFont: UIFont = UIFont.systemFont(ofSize: 12)
    /// 字表题的偏移（一般设置为负数，向上偏移）
    open var subtitleOffsetY:CGFloat = -5
    ///////////如果type == 1 可选择性设置以上属性
    
    //    private var tipView: UIView!
    private var buttonList = [UIButton]()
    private var tipViewList = [UIView]()
    private var tipView: UIView!
    private var tipViewWidth: CGFloat = 0
    private var btnWidth: CGFloat = 0
    private var btnHeight: CGFloat = 0
    private var tipview_offset_x: CGFloat = 0
    /// 点击前 tipview 的横坐标
    private var tipview_pre_location_x: CGFloat = 0
    /// 点击后 tipview 的横坐标
    private var tipview_crt_location_x: CGFloat = 0
    
    // MARK: - 初始化UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override func layoutSubviews() {    //传递数据后重新布局子视图
        getMultiButton(titles: titles)
    }
}
extension SWMultiButtonView {
    private func getMultiButton(titles: [String]) {
        let count: Int = titles.count
        self.btnWidth = self.bounds.size.width / CGFloat(count)
        self.btnHeight = self.bounds.size.height
        for i in 0..<count {
            let button = UIButton.init(type: .custom)
            self.addSubview(button)
            button.setTitle(titles[i], for: .normal)
            button.titleLabel?.font = itemFont
            button.tag = i
            buttonList.append(button)
            button.frame = CGRect(x: 0 + CGFloat(i) * btnWidth, y: 0, width: btnWidth, height: btnHeight)
            if i == selectedIndex {
                button.setTitleColor(selectedTitleColor, for: .normal)
                button.titleLabel?.font = selectedItemFont
            }
            else {
                button.setTitleColor(normalTitleColor, for: .normal)
                button.titleLabel?.font = itemFont
            }
            if type == 1 {
                button.titleEdgeInsets = titleEdgeInsets
                let subtitleLabel = UILabel.init()
                subtitleLabel.textColor = button.titleLabel?.textColor
                subtitleLabel.text = subtitles[i]
                subtitleLabel.font = subFont
                subtitleLabel.textAlignment = .center
                subtitleLabel.isUserInteractionEnabled = false
                button.addSubview(subtitleLabel)
                subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
                NSLayoutConstraint.activate([
                    subtitleLabel.centerXAnchor.constraint(equalTo: button.centerXAnchor, constant: 0),
                    subtitleLabel.leftAnchor.constraint(equalTo: button.leftAnchor, constant: 0),
                    subtitleLabel.rightAnchor.constraint(equalTo: button.rightAnchor,constant: 0),
                    subtitleLabel.bottomAnchor.constraint(equalTo: button.bottomAnchor,constant: -tipViewHeight + subtitleOffsetY)
                    ])
            }
            button.addTarget(self, action: #selector(evt_btn_action(sender:)), for: .touchUpInside)
        }
        
        var tipViewWidth: CGFloat = btnWidth - 20
        if tipViewScale == 0 {
            tipViewWidth = btnWidth - 20
        }
        else {
            tipViewWidth = btnWidth / CGFloat(tipViewScale)
        }
        self.tipview_offset_x = (btnWidth - tipViewWidth) / 2
        let tipView = UIView.init(frame: CGRect(x: self.tipview_offset_x, y: btnHeight - tipViewHeight, width: tipViewWidth, height: tipViewHeight))
        tipView.isHidden = false
        self.addSubview(tipView)
        tipView.backgroundColor = tipColor
        tipView.clipsToBounds = true
        tipView.layer.cornerRadius = tipViewCornerRadius
        if isTipViewHidden == true {
            tipView.isHidden = true
            self.velocity = 10000000 /// 让速率无限大,则tipView的动画时间无限小
        }
        else {
            tipView.isHidden = false
        }
        let seperateLine = UIView.init()
        self.addSubview(seperateLine)
        seperateLine.backgroundColor = UIColor.init(red: 244.0/255.0, green: 244.0/255.0, blue: 244.0/255.0, alpha: 1.0)
        seperateLine.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            seperateLine.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0),
            seperateLine.rightAnchor.constraint(equalTo: self.rightAnchor,constant: 0),
            seperateLine.bottomAnchor.constraint(equalTo: self.bottomAnchor,constant: 0),
            seperateLine.heightAnchor.constraint(equalToConstant: 0.5)
            ])
        self.tipView = tipView
        self.tipViewWidth = tipViewWidth
        self.seperateLine = seperateLine
        /// 初始化时确保调用到选中状态的方法
        if buttonList.count > selectedIndex {
            self.selected_button_action(sender: buttonList[selectedIndex])
        }
    }
    
    @objc func evt_btn_action(sender: UIButton) {
        self.selected_button_action(sender: sender)
        self.btnTitleColorWithoutAction(sender: sender)
        self.action(sender: sender)
    }
}


extension SWMultiButtonView {
    /// 只改变选中状态,不执行代理事件
    func selected_button_action(sender: UIButton) {
        self.tipview_pre_location_x = self.tipview_offset_x
        self.tipview_offset_x = btnWidth * CGFloat(sender.tag) + (btnWidth - tipViewWidth) / 2
        self.tipview_crt_location_x = self.tipview_offset_x
        let delt_x = abs(self.tipview_crt_location_x - self.tipview_pre_location_x)
        let duration = delt_x / velocity
        
        if isTipViewAnimate == true {
            UIView.animate(withDuration: TimeInterval(duration), animations: {
                self.tipView.frame = CGRect(x: self.tipview_offset_x, y: self.btnHeight - self.tipViewHeight, width: self.tipViewWidth, height: self.tipViewHeight)
            }) { (isFinished) in
                self.btnTitleColorWithoutAction(sender: sender)
            }
        }
        else {
            self.tipView.frame = CGRect(x: self.tipview_offset_x, y: self.btnHeight - self.tipViewHeight, width: self.tipViewWidth, height: self.tipViewHeight)
            self.btnTitleColorWithoutAction(sender: sender)
        }
        print("selectedIndex====>===== \(self.selectedIndex)")
    }
    func btnTitleColorWithoutAction(sender: UIButton) {
        for item in self.buttonList {
            if item.tag == sender.tag {
                self.buttonList[item.tag].setTitleColor(self.selectedTitleColor, for: .normal)
                self.buttonList[item.tag].titleLabel?.font = selectedItemFont
            }
            else {
                self.buttonList[item.tag].setTitleColor(self.normalTitleColor, for: .normal)
                self.buttonList[item.tag].titleLabel?.font = itemFont
            }
        }
    }
    /// 执行代理事件
    func action(sender: UIButton) {
        self.delegate?.multiButtonAction(sender: sender)
    }
}
