//
//  BadgeView.swift
//  LegendTeam
//
//  Created by 梁博 on 16/12/21.
//

import UIKit

class BadgeView: UIView {
    /// 是否显示为小红点，默认false
    public var onlyShowPoint = false
    /// 是否超过99 只显示... 默认false
    public var showMax99 = false
    /// 显示红点数值，设置为0会自动隐藏
    public var badgeValue = 0 {
        didSet {
            reloadBadge()
        }
    }

    /// 显示为红点的时候的宽高 默认 8
    public var pointWidth: CGFloat = 8
    /// 字体大小 默认
    public var badgeFont: UIFont = .t.tnmxs

    private var leftPadding: CGFloat = 4
    private var rightPadding: CGFloat = 4
    private let defaultBgColor = UIColor.c.cin
    private let defaultTextColor = UIColor.white
    private let contentLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }

    private func setupUI() {
        isUserInteractionEnabled = false
        backgroundColor = defaultBgColor
        layer.masksToBounds = true
        
        snp.makeConstraints { make in
            make.width.greaterThanOrEqualTo(snp.height)
        }

        addSubview(contentLabel)
        contentLabel.textColor = defaultTextColor
        contentLabel.font = badgeFont
        contentLabel.textAlignment = .center
        contentLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    private func reloadBadge() {
        isHidden = false
        contentLabel.isHidden = false

        if badgeValue == 0 {
            isHidden = true
            return
        }

        if onlyShowPoint {
            contentLabel.isHidden = true
            contentLabel.snp.remakeConstraints { make in
                make.edges.equalToSuperview()
                make.size.equalTo(CGSize(width: pointWidth, height: pointWidth))
            }
            return
        }

        if showMax99 && badgeValue > 99 {
            contentLabel.text = "···"
        } else {
            contentLabel.text = String(badgeValue)
        }
        contentLabel.snp.remakeConstraints { make in
            make.leading.equalTo(self).offset(leftPadding)
            make.trailing.equalTo(self).offset(-rightPadding)
            make.width.greaterThanOrEqualTo(6)
            make.top.bottom.equalTo(self)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if bounds.size.width > 0 {
            layer.cornerRadius = bounds.size.height * 0.5
        }
    }

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