//
//  YNSmsCodeView.swift
//  galaxy
//
//  Created by edy on 2023/12/29.
//

import UIKit

class YHSmsCodeView: UIView {

    // 是否显示光标
    var showCursor: Bool = false {
        didSet {
            if showCursor {
                self.cursor.layer .removeAllAnimations()
                self.animaitonShow(true)
                self.bottomLine.backgroundColor =  UIColor.mainTextColor
                
            } else {
                self.cursor.layer .removeAllAnimations()
                self.cursor.isHidden = true
                self.bottomLine.backgroundColor =  UIColor.init(hex: 0xF0F3F7)
            }
        }
    }
    var text: String? {
        didSet {
            label.text = text
        }
    }
    lazy var label: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont(name: "DINAlternate-Bold", size: 18)
        return label
    }()
    
    lazy var cursor: UIView = {
        let cursor = UIView()
        cursor.backgroundColor = UIColor.brandMainColor
        cursor.isHidden = true
        return cursor
    }()
    
    lazy var bottomLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hex: 0xF0F3F7)
        return view
    }()
        
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.config()
    }
    
    func config() {
        self.isUserInteractionEnabled = false
        self.layer.cornerRadius = kCornerRadius3
        self.clipsToBounds = true
        self.backgroundColor = .clear

        self.addSubview(label)
        self.addSubview(cursor)
        self.addSubview(bottomLine)
    }
    
    @objc func animaitonShow(_ show: Bool) {
        
        if !self.showCursor { return }
        
        UIView.animate(withDuration: 0.8, animations: {
            self.cursor.isHidden = !show
            
        }, completion: { (_) in
            if self.showCursor {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                    self.animaitonShow(!show)
                }
            }
        })
    }
    
    override func layoutSubviews() {
        self.label.frame = self.bounds
        self.cursor.bounds = CGRect(x: 0, y: 0, width: 1, height: 17)
        self.cursor.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
        self.bottomLine.frame = CGRect(x: 0, y: self.frame.size.height-1, width: self.frame.size.width, height: 1)
    }
}
