//
//  MPPositive_CenterListSearchView.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/6/25.
//

import UIKit
///曲库搜索View
class MPPositive_CenterListSearchView: UIView, UITextFieldDelegate {
    ///搜索文本框
    lazy var textField:UITextField = {
        let textField = UITextField()
        textField.delegate = self
        textField.textColor = .init(hex: "#80F988")
        textField.tintColor = .init(hex: "#80F988")
        textField.font = .systemFont(ofSize: 12*width, weight: .regular)
        let attributed = NSAttributedString(string: "Search songs in this list", attributes: [.font:UIFont.systemFont(ofSize: 12*width, weight: .regular), .foregroundColor:UIColor(hex: "#FFFFFF", alpha: 0.6)])
        textField.attributedPlaceholder = attributed
        return textField
    }()
    ///取消按钮
    private lazy var cancelBtn:UIButton = {
        let btn:UIButton = .init()
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(.init(hex: "#80F988"), for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14*width, weight: .regular)
        btn.addTarget(self, action: #selector(cancelClick(_ :)), for: .touchUpInside)
        return btn
    }()
    //搜索限定计时器
    private var debounceTimer: Timer?
    var cancelBlock:(() -> Void)?
    var textBlock:((String) -> Void)?
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .init(hex: "#151718")
        configure()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    deinit {
        debounceTimer?.invalidate()
        debounceTimer = nil
    }
    private func configure() {
        //生成一个容器View
        let containerView = UIView()
        containerView.backgroundColor = .init(hex: "#FFFFFF", alpha: 0.1)
        containerView.layer.masksToBounds = true
        containerView.layer.cornerRadius = 12*width
        containerView.addSubview(textField)
        textField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12*width)
            make.right.equalToSuperview().offset(-12*width)
            make.centerY.equalToSuperview()
        }
        addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.width.equalTo(275*width)
            make.height.equalTo(24*width)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(18*width)
        }
        addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-18*width)
            make.centerY.equalToSuperview()
        }
    }
    //取消
    @objc private func cancelClick(_ sender:UIButton) {
        endEditing(true)
        textField.text = ""
        if let block = cancelBlock {
            block()
        }
    }
    //MARK: - textField
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        guard text.count <= 30, text.contains("\n") == false else {
            return false
        }
        loadSearchs(text)
        return true
    }
    //避免重复请求
    private func cancelDebounceTimer() {
        debounceTimer?.invalidate()
        debounceTimer = nil
    }
    //当用户输入文本通过后进行检索
    private func loadSearchs(_ text:String) {
        cancelDebounceTimer()
        //停止输入0.5秒后调用
        debounceTimer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { [weak self] _ in
            //文本回调
            if let block = self?.textBlock {
                block(text)
            }
        }
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 用户点击了键盘上的 return 键
        // 可以在这里让键盘消失或执行其他动作
        textField.resignFirstResponder() // 让键盘消失
        return true
    }
}
