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

import UIKit

// 输入框UI显示配置
struct YHSmsCodeViewConfig {
    
    var textColor : UIColor? = UIColor.mainTextColor
    var bgColor : UIColor? = UIColor.clear
    var cursorColor : UIColor? = UIColor.brandMainColor
    var font: UIFont? = UIFont(name: "DINAlternate-Bold", size: 18)
    // 展示输入框个数
    var count : Int = 6
    var width : Double = 46.0
    var height : Double = 46.0
    // 输入框之间间距
    var gap:Double = 12
}

let codeViewBaseTag = 9527

class YHSmsCodeInputView: UIView {
    
    var complete: ((String) ->Void)?
    var config: YHSmsCodeViewConfig = YHSmsCodeViewConfig()

    // 此输入框并不显示，只是接收输入
    lazy var textField: YHTextField = {
        let textField = YHTextField()
        textField.backgroundColor = .clear
        textField.tintColor = .clear
        textField.textColor = .clear
        textField.delegate = self
        textField.keyboardType = .phonePad
        textField.addTarget(self, action: #selector(smsCodeInputChanged), for: .editingChanged)
        return textField
    }()
    
    convenience init(config: YHSmsCodeViewConfig) {
        self.init(frame: .zero)
        self.config = config
        self.setupUI()
        
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func setupUI() {
        self.addSubview(textField)
        textField.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        // 输入框数量
        let count = config.count
        // 输入框之间间距
        let gap = config.gap
        // 输入框宽度
        let inputWidth = config.width
        // 输入框高度
        let inputHeight = config.height
        // 输入框个数是否为偶数
        let isEven = (config.count % 2 == 0)
        for index in 1...count {
            
            let inputView = YHSmsCodeView(frame: CGRectZero)
            inputView.backgroundColor = config.bgColor
            inputView.label.font = config.font
            inputView.label.textColor = config.textColor
            inputView.cursor.backgroundColor = config.cursorColor
            
            if (index == 1) {
                inputView.showCursor = true
            }
           inputView.tag = codeViewBaseTag + index
           self.addSubview(inputView)
            
           // 此处布局为轴对称布局
            
           // 小组件右边距离父视图中轴线间距
            var rightMargin = 0.0;
            if (isEven) { // 输入框个数为偶数
                let middle = count/2
                if (index <= middle) {
                    rightMargin = -(Double(middle-index)*(gap+inputWidth) + gap/2.0)
                } else {
                    rightMargin = Double(index-middle-1)*(gap+inputWidth) + gap/2.0+inputWidth
                }
                print(rightMargin)
                inputView.snp.makeConstraints { make in
                    make.size.equalTo(CGSize(width: inputWidth, height: inputHeight))
                    make.centerY.equalTo(self)
                    make.right.equalTo(self.snp.centerX).offset(rightMargin)
                }
                
            } else { // // 输入框个数为奇数
                let middle:Int = count/2 + 1
                if (index < middle) {
                    rightMargin = -(Double(middle-index-1)*(gap+inputWidth) + inputWidth/2.0+gap)
                } else if (index > middle)  {
                    rightMargin = (Double(index-middle-1)*(gap+inputWidth) + inputWidth*3/2.0+gap)
                }
                print(rightMargin)
                inputView.snp.makeConstraints { make in
                    make.size.equalTo(CGSize(width: inputWidth, height: inputHeight))
                    make.centerY.equalTo(self)
                    if (index == middle) {
                        make.centerX.equalTo(self)
                    } else {
                        make.right.equalTo(self.snp.centerX).offset(rightMargin)
                    }
                }
            }
        }
    }
    
    @objc func smsCodeInputChanged(input:UITextField) {
        
        guard let text = input.text else  {
            let codeView = self.viewWithTag(codeViewBaseTag+1) as? YHSmsCodeView
            codeView?.showCursor = true
            return
        }
        
        if (text.count > config.count) { return }
        
        for index in 0..<config.count {
            let codeView = self.viewWithTag(codeViewBaseTag+index+1) as! YHSmsCodeView
            
            codeView.text = (index < text.count ? String(text[index]) : "")
            codeView.showCursor = (index == text.count)
        }
        
        for (index, char) in input.text!.enumerated() {
            if (index < config.count) {
                let codeView = self.viewWithTag(codeViewBaseTag+index+1) as? YHSmsCodeView
                codeView?.text = String(char)
            }
        }
        
        if (text.count == config.count) {
            textField.resignFirstResponder()
            if let complete = self.complete {
                complete(text)
            }
        }
    }
}

extension YHSmsCodeInputView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard let text = textField.text else {
            return true
        }
        
        if (string.count <= 0) { // 删除字符操作
            return true
        }
        
        if !string.isDigits { // 必须是数字
            return false
        }
        // 限制字数
        let textLength = text.charactersArray.count + string.charactersArray.count - range.length
        return textLength <= config.count
    }

}

class YHTextField: UITextField {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
    
//    open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
//        if let ges = gestureRecognizer as? UITapGestureRecognizer {
//            return true
//        } else {
//            return false
//        }
//    }
}
