//
//  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.layer.borderWidth = 1
                self.layer.borderColor = UIColor(hex: 0x2f7ef6).cgColor
            } else {
                self.cursor.layer .removeAllAnimations()
                self.cursor.isHidden = true
                self.layer.borderWidth = 0
            }
        }
    }
    var text : String? {
        didSet {
            label.text = text
        }
    }
    lazy var label : UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 20)
        return label
    }()
    
    var cursor : UIView = {
        let cursor = UIView()
        cursor.backgroundColor = UIColor(hex: 0x2f7ef6)
        cursor.isHidden = true
        return cursor
    }()
        
    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 = 6;
        self.clipsToBounds = true;
        self.backgroundColor = UIColor(white: 1, alpha: 0.3)

        self.addSubview(label)
        self.addSubview(cursor)
    }
    
    @objc func animaitonShow(_ show: Bool) {
        
        if !self.showCursor { return }
        
        UIView.animate(withDuration: 0.8, animations:  {
            self.cursor.isHidden = !show
            
        }, completion:  { (finishd) 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 = CGRectMake(0, 0, 1.5, self.frame.size.height - 20);
        self.cursor.center = CGPoint(x:CGRectGetMidX(self.bounds) , y: CGRectGetMidY(self.bounds))
    }
}
