//
//  YHBasicInfoFillView.swift
//  galaxy
//
//  Created by davidhuangA on 2024/2/3.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHBasicInfoFillView: UIView, UITextViewDelegate {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    typealias Block = () -> ()
    var block: Block?
    
    
    
    private let btnWidth = 70.0
    private let btnHeight = 32.0
    private let btnTitleSelectColor = UIColor.brandMainColor
    private let btnTitleDefaultColor = UIColor.mainTextColor
    private let btnBgDefaultColor = UIColor.contentBkgColor
    private let btnBgSelectColor = UIColor.brandMainColor.withAlphaComponent(0.08)
    private let answerBaseTag  = 9527
    
    
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .mainTextColor
        label.textAlignment = .left
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.lineBreakMode = .byCharWrapping
        return label
    }()
    
    private lazy var answer1Btn: UIButton = {
        
        let btn = UIButton()
        btn.setTitle("否", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(btnTitleDefaultColor, for: .normal)
        btn.backgroundColor = btnBgDefaultColor
        btn.layer.cornerRadius = btnHeight/2.0
        btn.layer.masksToBounds = true
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.clear.cgColor
        btn.tag = answerBaseTag
        btn.addTarget(self, action: #selector(didClickResponseBtn(btn:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var answer2Btn: UIButton = {
        let btn = UIButton()
        btn.setTitle("是", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(btnTitleDefaultColor, for: .normal)
        btn.backgroundColor = btnBgDefaultColor
        btn.layer.cornerRadius = btnHeight/2.0
        btn.layer.masksToBounds = true
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.clear.cgColor
        btn.tag = answerBaseTag+1
        btn.addTarget(self, action: #selector(didClickResponseBtn(btn:)), for: .touchUpInside)
        return btn
    }()
    
    
    private lazy var bottomLine : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0xF0F0F0)
        return view
    }()
    
    
    private lazy var additionHoldView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.contentBkgColor
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        return view
    }()
    
    
    //多选框 holdView
    private lazy var mutilChoiceHoldView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.contentBkgColor
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        return view
    }()
    
    
    var title:String? {
        didSet {
            if let question = title {
                let str = "* "+question
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: UIFont.PFSC_R(ofSize: 14),
                    .foregroundColor: UIColor.mainTextColor
                ]
                let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
                let starRange = NSRange(location: 0, length: 1)
                questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
                titleLabel.attributedText = questionAttrStr
            }
        }
    }
    
    
    
    var model : YHBasicInfoCellModel? {
        didSet {
            updateUI()
        }
    }
    
    
    private var lastSelectedBtn : UIButton?
    private var myTextView : UITextView!
    private var arrCheckBtns : [UIButton] = []
    
    private let kTipsString : String = "如选择“是”，请详细说明"
}


private extension YHBasicInfoFillView {
    func setupUI() {
        backgroundColor = .clear
        title = "1、是否曾在香港或其他地方因任何罪行或违法行为被定罪?"
        addSubview(titleLabel)
        addSubview(answer2Btn)
        addSubview(answer1Btn)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(kMargin)
            make.left.right.equalToSuperview()
        }
        
        answer1Btn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            make.left.equalTo(titleLabel.snp.left)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
        }
        
        answer2Btn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            make.left.equalTo(answer1Btn.snp.right).offset(12)
            make.top.equalTo(answer1Btn.snp.top)
        }
        
        addSubview(bottomLine)
        bottomLine.snp.makeConstraints { make in
            make.top.equalTo(answer1Btn.snp.bottom).offset(12)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
        addSubview(additionHoldView)
        additionHoldView.isHidden = true
        
        
        let redDot = UIImageView(image: UIImage(named: "basic_info_red_dot"))
        additionHoldView.addSubview(redDot)
        redDot.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(19)
            make.width.height.equalTo(6)
        }
        
        let textView : UITextView = UITextView()
        textView.backgroundColor = .clear
        textView.font = UIFont.PFSC_R(ofSize: 14)
        additionHoldView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.top.equalTo(redDot.snp.top).offset(-7)
            make.left.equalTo(redDot.snp.right).offset(2)
            make.right.equalTo(-12)
            make.bottom.equalTo(-6)
        }
        myTextView = textView
        myTextView.delegate = self
        textView.contentInset = UIEdgeInsets(top: -8, left: 0, bottom: 0, right: 0)
        
        
        
        addSubview(mutilChoiceHoldView)
        mutilChoiceHoldView.isHidden = true
        mutilChoiceHoldView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
    }
    
    @objc func didClickResponseBtn(btn: UIButton) {
        printLog("点击了按钮哈 \(btn.tag)")
        
        if  lastSelectedBtn == btn {
            printLog("连续点击了同一个按钮......")
            return
        }
        
        lastSelectedBtn = btn
        btn.isSelected = true
        updateAnswerButton(btn, true)
        
        
        if btn == answer1Btn {
            answer2Btn.isSelected = false
            updateAnswerButton(answer2Btn, false)
            
            additionHoldView.snp.removeConstraints()
            mutilChoiceHoldView.snp.removeConstraints()
            
            bottomLine.snp.remakeConstraints { make in
                make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                make.left.right.equalToSuperview()
                make.height.equalTo(0.5)
                make.bottom.equalToSuperview()
            }
            additionHoldView.isHidden = true
            bottomLine.isHidden = false
            mutilChoiceHoldView.isHidden = true
            
            model?.answer = "N"
            
        } else {
            answer1Btn.isSelected = false
            updateAnswerButton(answer1Btn, false)
            bottomLine.snp.removeConstraints()
            
            if model?.type == 0 {
                additionHoldView.snp.removeConstraints()
                additionHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(78)
                    make.bottom.equalToSuperview().offset(-18)
                }
                
                model?.answer = "Y"
                
                
                additionHoldView.isHidden = false
                bottomLine.isHidden = true
                mutilChoiceHoldView.isHidden = true
                
            } else {
                
                
                mutilChoiceHoldView.snp.removeConstraints()
                mutilChoiceHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                    make.bottom.equalToSuperview().offset(-18)
                }
                
                model?.answer = "Y"
                
                
                additionHoldView.isHidden = true
                bottomLine.isHidden = true
                mutilChoiceHoldView.isHidden = false
                
            }
            
        }
        
        
        additionHoldView.layoutIfNeeded()
        bottomLine.layoutIfNeeded()
        mutilChoiceHoldView.layoutIfNeeded()
        
        block?()
    }
    
    
    
    // 更新答案按钮选中状态
    private func updateAnswerButton(_ btn:UIButton, _ isSelect:Bool) {
        btn.layer.borderColor = (isSelect ? btnTitleSelectColor : .clear).cgColor
        btn.setTitleColor((isSelect ? btnTitleSelectColor : btnTitleDefaultColor), for: .normal)
        btn.backgroundColor = (isSelect ? btnBgSelectColor : btnBgDefaultColor)
    }
    
    private func updateUI() {
        guard let model = model else { return }
        arrCheckBtns.removeAll()
        if model.type == 1 {
            additionHoldView.isHidden = true
            mutilChoiceHoldView.isHidden  = false
            
            let lable = UILabel()
            let str = "* 选择成员："
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_R(ofSize: 14),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            let starRange = NSRange(location: 0, length: 1)
            questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
            lable.attributedText = questionAttrStr
            mutilChoiceHoldView.addSubview(lable)
            lable.snp.makeConstraints { make in
                make.top.equalTo(12)
                make.left.equalTo(12)
                make.height.equalTo(20)
                make.right.equalTo(-12)
            }
            
            
            guard let subModel = model.model else {
                printLog("errorr: 数据有问题")
                
                title = model.question
                if model.answer == "Y" {
                    didClickResponseBtn(btn: answer2Btn)
                    mutilChoiceHoldView.isHidden  = false
                } else {
                    
                    if model.answer == "N" {
                        didClickResponseBtn(btn: answer1Btn)
                    } else {
                        answer2Btn.isSelected = false
                        updateAnswerButton(answer2Btn, false)
                        
                        additionHoldView.snp.removeConstraints()
                        mutilChoiceHoldView.snp.removeConstraints()
                        
                        bottomLine.snp.remakeConstraints { make in
                            make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                            make.left.right.equalToSuperview()
                            make.height.equalTo(0.5)
                            make.bottom.equalToSuperview()
                        }
                        additionHoldView.isHidden = true
                        bottomLine.isHidden = false
                        mutilChoiceHoldView.isHidden = true
                    }
                }
                return
            }
            
            
            var targetView : UIView = lable
            
            let targetId = Int(subModel.background_member?.info ?? "0")
            for (index,item) in subModel.subset.enumerated() {
                
                let name = item.subset_name.count > 0 ? item.subset_name : "--"
                let btn = UIButton(type: .custom)
                btn.setTitle(name, for: .normal)
                btn.setTitle(name, for: .selected)
                btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
                btn.setTitleColor(UIColor.mainTextColor, for: .normal)
                btn.setTitleColor(UIColor.brandMainColor, for: .selected)
                btn.setImage(UIImage(named: "basic_info_check_0"), for: .normal)
                btn.setImage(UIImage(named: "basic_info_check_1"), for: .selected)
                btn.iconInLeft(spacing: 6)
                btn.tag = item.id
                btn.addTarget(self, action: #selector(clickCheckBtn(sender:)), for: .touchUpInside)
                mutilChoiceHoldView.addSubview(btn)
                
                if targetId == item.id {
                    btn.isSelected = true
                } else {
                    btn.isSelected = false
                }
                
                
                
                
                if index == subModel.subset.count - 1 {
                    btn.snp.makeConstraints { make in
                        make.top.equalTo(targetView.snp.bottom).offset(kMargin)
                        make.left.equalTo(16)
                        make.height.equalTo(30)
                        make.bottom.equalToSuperview().offset(-kMargin)
                    }
                } else {
                    
                    btn.snp.makeConstraints { make in
                        make.top.equalTo(targetView.snp.bottom).offset(kMargin)
                        make.left.equalTo(16)
                        make.height.equalTo(30)
                    }
                }
                
                targetView = btn
                arrCheckBtns.append(btn)
            }
            
            
            title = model.question
            if model.answer == "Y" {
                didClickResponseBtn(btn: answer2Btn)
                mutilChoiceHoldView.isHidden  = false
            } else {
                
                if model.answer == "N" {
                    didClickResponseBtn(btn: answer1Btn)
                } else {
                    answer2Btn.isSelected = false
                    updateAnswerButton(answer2Btn, false)
                    
                    additionHoldView.snp.removeConstraints()
                    mutilChoiceHoldView.snp.removeConstraints()
                    
                    bottomLine.snp.remakeConstraints { make in
                        make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(0.5)
                        make.bottom.equalToSuperview()
                    }
                    additionHoldView.isHidden = true
                    bottomLine.isHidden = false
                    mutilChoiceHoldView.isHidden = true
                }
            }
        } else {
            additionHoldView.isHidden = false
            mutilChoiceHoldView.isHidden  = true
            
            title = model.question
            if model.answer == "Y" {
                didClickResponseBtn(btn: answer2Btn)
                myTextView.text = model.info.count > 0 ? model.info : kTipsString
            } else {
                if model.answer == "N" {
                    didClickResponseBtn(btn: answer1Btn)
                }
            }
        }
        
        if myTextView.text == kTipsString {
            myTextView.textColor = UIColor(hexString: "#C0C0C0")
        } else {
            myTextView.textColor = UIColor.mainTextColor
        }
    }
}



extension YHBasicInfoFillView : UITextFieldDelegate {
    
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if textView.text == kTipsString {
            textView.text = ""
        }
        textView.textColor = UIColor.mainTextColor
        return true
    }
    
    func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        if textView.text.isEmpty || textView.text == "" {
            textView.textColor = UIColor(hexString: "#C0C0C0")
            textView.text = kTipsString
        }
        textView.textColor = UIColor.mainTextColor
        return true
    }
    
    
    
    
    
    internal func textViewDidChange(_ textView: UITextView) {
        if textView.text == kTipsString {
            model?.info = ""
        } else {
            model?.info = textView.text
        }
        
        textView.textColor = UIColor.mainTextColor
    }
    
    
    
    @objc func clickCheckBtn(sender : UIButton) {
        //修改成单选逻辑
        if sender.isSelected != true {
            for item in arrCheckBtns {
                item.isSelected = false
            }
            sender.isSelected = true
            model?.info = String(sender.tag)
        }
    }
}

