//
//  YHSingleOptionalItemsView.swift
//  galaxy
//
//  Created by davidhuangA on 2024/11/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSingleOptionalItemsView: UIView {
    
    // 输入名称
    private lazy var languageTextField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.attributedPlaceholder = NSAttributedString(string: "请输入语言".local, attributes: [NSAttributedString.Key.foregroundColor: UIColor(hex: 0xB9C1CC)])
        textField.font = UIFont.PFSC_R(ofSize: 14)
        textField.tintColor = UIColor.brandMainColor
        textField.textColor = UIColor.mainTextColor
        textField.clearButtonMode = .whileEditing
        textField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged)
        textField.delegate = self
        return textField
    }()
    
    var textFieldHoldView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.clipsToBounds = true
        view.layer.cornerRadius = kCornerRadius3
        return view
    }()
    
    var optionsHoldView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.clipsToBounds = true
        view.layer.cornerRadius = kCornerRadius3
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var needCheckFlag: Bool = false
    // 提示lable
    private lazy var noTextTipsLable: UILabel = {
        let label = UILabel()
        label.textColor = .failColor
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "请输入"
        label.isHidden = true
        return label
    }()
    // 提示lable
    private lazy var noTextTipsLable2: UILabel = {
        let label = UILabel()
        label.textColor = .failColor
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "请选择"
        label.isHidden = true
        return label
    }()
    
    // 数据结构
    var dataModel: LanguageDetailModel? {
        didSet {
            updateUI()
        }
    }
    
    var arrCompare: [LanguageDetailModel] = []
    
    private var arrHoldView: [YHOtherSingleChoiceItemView] = []
    
    typealias Block = (LanguageDetailModel?) -> Void
    var block: Block?

}

private extension YHSingleOptionalItemsView {
    func setupUI() {
        
        addSubview(noTextTipsLable)
        addSubview(noTextTipsLable2)
        
        addSubview(textFieldHoldView)
        textFieldHoldView.isHidden = true
        textFieldHoldView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(52)
        }
        
        textFieldHoldView.addSubview(languageTextField)
        languageTextField.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
        }
        
        addSubview(optionsHoldView)
        optionsHoldView.snp.makeConstraints { make in
            make.top.equalTo(textFieldHoldView.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
            
            make.height.equalTo(20)
            make.bottom.equalToSuperview()
        }
    }
    
    @objc func textFieldChanged(textField: UITextField) {
        printLog(textField.text)
        guard let model = dataModel else {
            return
        }
        model.other_instructions = textField.text ?? ""
        
        updateUI()
        NotificationCenter.default.post(name: Notification.Name(rawValue: "com.yinhe.myCertificate.wechat.otherInfo_remark_notification"), object: model)
    }
    
    func updateUI() {
        guard let model = dataModel else {
            return
        }
        
        if model.options.count > 0 {
            optionsHoldView.snp.removeConstraints()
            optionsHoldView.removeSubviews()
            
            var hasSelectedOneFlag: Bool = false
            for(_, item) in model.options.enumerated() {
                hasSelectedOneFlag = hasSelectedOneFlag || item.select
            }
            
            if model.id == 3 {
                // 其他
                languageTextField.text = model.other_instructions
                textFieldHoldView.isHidden = false
                
                var tagView: UIView = textFieldHoldView
                // 1.输入框 是否有数据
                if needCheckFlag, let txt = languageTextField.text, txt.isEmpty {
                    // 需要检查 且 输入框无数据
                    noTextTipsLable.isHidden = false
                    noTextTipsLable.snp.removeConstraints()
                    noTextTipsLable.snp.remakeConstraints { make in
                        make.top.equalTo(textFieldHoldView.snp.bottom).offset(8)
                        
                        make.left.right.equalToSuperview()
//                            make.bottom.equalToSuperview()
                        
                    }
                    tagView = noTextTipsLable
                } else {
                    noTextTipsLable.isHidden = true
                }
                
                // 2.是否进行了选择
                if needCheckFlag, !hasSelectedOneFlag {
                    // 需要检查 且 未选择
                    
                    optionsHoldView.snp.remakeConstraints { make in
                        make.top.equalTo(tagView.snp.bottom).offset(8)
                        make.left.right.equalToSuperview()
                    }
                    
                    noTextTipsLable2.isHidden = false
                    noTextTipsLable2.snp.removeConstraints()
                    noTextTipsLable2.snp.remakeConstraints { make in
                        make.top.equalTo(optionsHoldView.snp.bottom).offset(8)
                        make.left.right.equalToSuperview()
                        make.bottom.equalToSuperview()
                    }
                    
                } else {
                    noTextTipsLable2.isHidden = true
                    optionsHoldView.snp.remakeConstraints { make in
                        make.top.equalTo(tagView.snp.bottom).offset(8)
                        make.left.right.equalToSuperview()
                        make.bottom.equalToSuperview()
                    }
                }
            } else {
                // 非其他选项
                
                textFieldHoldView.isHidden = true
                noTextTipsLable.isHidden = true
                
                if needCheckFlag, !hasSelectedOneFlag {
                    // 需要检查 且 未选择
                    
                    optionsHoldView.snp.remakeConstraints { make in
                        make.top.equalToSuperview()
                        make.left.right.equalToSuperview()
//                        make.bottom.equalToSuperview()
                    }
                    
                    noTextTipsLable2.snp.removeConstraints()
                    noTextTipsLable2.isHidden = false
                    noTextTipsLable2.snp.remakeConstraints { make in
                        make.top.equalTo(optionsHoldView.snp.bottom).offset(8)
                        make.left.right.equalToSuperview()
                        make.bottom.equalToSuperview().offset(-8)
                    }
                    
                } else {
                    noTextTipsLable2.isHidden = true
                    optionsHoldView.snp.remakeConstraints { make in
                        make.top.equalToSuperview()
                        make.left.right.equalToSuperview()
                        make.bottom.equalToSuperview()
                    }
                }
            }
            
            var lastView: UIView?
            arrHoldView.removeAll()
            
            for(index, item) in model.options.enumerated() {
                let tmpOption = YHOtherSingleChoiceItemView()
                tmpOption.dataModel = item
                optionsHoldView.addSubview(tmpOption)
                
                arrHoldView.append(tmpOption)
                
                tmpOption.tag = index
                let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapItem(gestureRecognizer:)))
                tmpOption.addGestureRecognizer(tap)
                
                if index == 0 {
                    // 第一个
                    tmpOption.snp.makeConstraints { make in
                        make.top.equalToSuperview().offset(kMargin)
                        make.left.equalToSuperview().offset(kMargin)
                        make.right.equalToSuperview().offset(-kMargin)
                    }
                } else if index + 1 == model.options.count {
                    // 最后一个
                    if let tttView = lastView {
                        tmpOption.snp.makeConstraints { make in
                            make.top.equalTo(tttView.snp.bottom).offset(kMargin)
                            make.left.equalToSuperview().offset(kMargin)
                            make.right.equalToSuperview().offset(-kMargin)
                            make.bottom.equalToSuperview().offset(-kMargin)
                        }
                    }
                } else {
                    // 中间
                    if let tttView = lastView {
                        tmpOption.snp.makeConstraints { make in
                            make.top.equalTo(tttView.snp.bottom).offset(kMargin)
                            make.left.equalToSuperview().offset(kMargin)
                            make.right.equalToSuperview().offset(-kMargin)
                        }
                    }
                }
                lastView = tmpOption
            }
        }
    }
    
    @objc func tapItem(gestureRecognizer: UITapGestureRecognizer) {
        guard let model = dataModel else {
            return
        }
        
        let clickIndex = gestureRecognizer.view?.tag
        if clickIndex == 0 {
            // 判断母语
            if !model.options.isEmpty {
                let item = model.options[0]
                if !item.select {
                    // 判断其他 语言是不是选了 母语
                    var hasSelected: Bool = false
                    for (_, item) in arrCompare.enumerated() {
                        if item.id != model.id {
                            
                            for (_, tt) in item.options.enumerated() {
                                if tt.id == 1, tt.select {// 母语
                                    hasSelected = true
                                }
                            }
                        }
                    }
                    
                    if hasSelected {
                        YHHUD.flash(message: "只能选择一种语言为母语")
                        return
                    }
                }
            }
        }
        
        for (index, item) in model.options.enumerated() {
            if clickIndex == index {
                if !item.select {
                    item.select = true
                } else {
                    return
                }
            } else {
                item.select = false
            }
        }
        
        for (index, item) in arrHoldView.enumerated() {
            let data = model.options[index]
            item.dataModel = data
        }
        
        self.block?(model)
    }
}

extension YHSingleOptionalItemsView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.isEmpty == true { // 点击删除
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > 30 {
            return false
        }
        return true
    }
}
