//
//  YHSingleLineInputCell.swift
//  galaxy
//
//  Created by edy on 2024/1/22.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHFormItemInputTextCell: UITableViewCell {

    static let cellReuseIdentifier = "YHFormItemInputTextCell"
    
    // 是否必填 如必填title会展示红色*
    var isMust = false
    var textChange:((String?)->Void)?
    
    var title:String? {
        didSet {
            
            if let title = title {
                let str = (isMust ? ("*"+title) : title)
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: UIFont.PFSC_R(ofSize: 14),
                    .foregroundColor: UIColor(hex:0x222222)
                ]
                let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                if isMust {
                    let starRange = NSRange(location: 0, length: 1)
                    questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(hex:0xFF3A3A), range: starRange)
                }
                titleLabel.attributedText = questionAttrStr
            }
        }
    }

    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString:"#333333")
        label.textAlignment = .left
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        return label
    }()
    
    lazy var textField:UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.placeholder = "请如实填写"
        textField.font = UIFont.PFSC_R(ofSize: 14)
        textField.tintColor = UIColor(hex: 0xC0C0C0)
        textField.textColor = UIColor(hex: 0x222222)
        textField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged)
        return textField
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        contentView.addSubview(titleLabel)
        contentView.addSubview(textField)
        
        isMust = true
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.width.equalTo(120)
            make.centerY.equalToSuperview()
        }
        
        textField.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(contentView.snp.right).offset(-16)
            make.left.equalTo(titleLabel.snp.right).offset(10)
        }
    }
    
    @objc func textFieldChanged(textField:UITextField) {
        if let textChange = textChange {
            textChange(textField.text)
        }
    }

}
