//
//  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.separatorColor
        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 lazy var noChoiceTipsLable: UILabel = {
        let label = UILabel()
        label.textColor = .failColor
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "请选择"
        return label
    }()
    
    private lazy var noTextTipsLable: UILabel = {
        let label = UILabel()
        label.textColor = .failColor
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "请补充详细说明"
        return label
    }()
}


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()
        }
        
        answer2Btn.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)
        }
        
        answer1Btn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            make.left.equalTo(answer2Btn.snp.right).offset(12)
            make.top.equalTo(answer2Btn.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)
        }
        
        
        
        addSubview(noChoiceTipsLable)
        noChoiceTipsLable.isHidden = true
        noChoiceTipsLable.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(20)
        }
        
        addSubview(noTextTipsLable)
        noTextTipsLable.isHidden = true
        noTextTipsLable.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(20)
        }
    }
    
    @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)
            model?.answer = "N"
            layoutForNO()
        } else {
            answer1Btn.isSelected = false
            updateAnswerButton(answer1Btn, false)
            layoutForYES()
        }
        
        
//        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)
                } else {
                    if model.answer == "N" {
                        didClickResponseBtn(btn: answer1Btn)
                    } else {
                        layoutForMakeNoChoice()
                    }
                }
                return
            }
            
            let tmpHoldView : YHChoiceButtonHoldView = YHChoiceButtonHoldView()
            
            tmpHoldView.targetId = Int(subModel.background_member?.info ?? "0") ?? 0
            tmpHoldView.dataModel = subModel.subset
            tmpHoldView.callBackBlock = { tag in
                self.model?.info = tag
            }
            
            mutilChoiceHoldView.addSubview(tmpHoldView)
            tmpHoldView.snp.makeConstraints { make in
                make.top.equalTo(lable.snp.bottom).offset(kMargin)
                make.left.equalTo(lable.snp.left)
                make.right.equalTo(lable.snp.right)
                make.bottom.equalToSuperview().offset(-kMargin)
            }
            
            title = model.question
            if model.answer == "Y" {
                didClickResponseBtn(btn: answer2Btn)
            } else {
                
                if model.answer == "N" {
                    didClickResponseBtn(btn: answer1Btn)
                } else {
                    layoutForMakeNoChoice()
                }
            }
        } 
        else {
            title = model.question
            if model.answer == "Y" {
                myTextView.text = model.info.count > 0 ? model.info : kTipsString
                didClickResponseBtn(btn: answer2Btn)
            } else {
                if model.answer == "N" {
                    didClickResponseBtn(btn: answer1Btn)
                } else {
                    //没有做选择的情况下
                    layoutForMakeNoChoice()
                }
            }
        }
        
        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
    }
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if !text.isEmpty {
            if textView.text.count > 999 {
                return false
            }
        }
        return true
    }
    
    
    
    
    internal func textViewDidChange(_ textView: UITextView) {
        if textView.text == kTipsString {
            model?.info = ""
        } else {
            model?.info = textView.text
        }
        
        textView.textColor = UIColor.mainTextColor
        layoutForYES()
    }
    
    
    
//    @objc func clickCheckBtn(sender : UIButton) {
//        //修改成单选逻辑
//        if sender.isSelected != true {
//            for item in arrCheckBtns {
//                item.isSelected = false
//            }
//            sender.isSelected = true
//            model?.info = String(sender.tag)
//        }
//        
//        layoutForYES()
//    }
}


//各种情况下的布局
private extension YHBasicInfoFillView {
    
    //选择 是 的布局
    func layoutForYES() {
        guard let model = model else {
            printLog("error :  有问题 需要处理。。。。")
            return
        }
        
        model.answer = "Y"
        
        additionHoldView.isHidden = true
        bottomLine.isHidden = true
        mutilChoiceHoldView.isHidden = true
        noChoiceTipsLable.isHidden = true
        noTextTipsLable.isHidden = true
        
        additionHoldView.snp.removeConstraints()
        bottomLine.snp.removeConstraints()
        mutilChoiceHoldView.snp.removeConstraints()
        noChoiceTipsLable.snp.removeConstraints()
        additionHoldView.snp.removeConstraints()
        noTextTipsLable.snp.removeConstraints()
        
        
        if model.needCheckFlag == false {
            //不需要展示 提示的情况
            if model.type == 0 {
                additionHoldView.isHidden = false
                bottomLine.isHidden = false
                
                additionHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(78)
                }
                
                bottomLine.snp.remakeConstraints { make in
                    make.top.equalTo(additionHoldView.snp.bottom).offset(kMargin)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(0.5)
                    
                    make.bottom.equalToSuperview()
                }
                
            } else {
                bottomLine.isHidden = false
                mutilChoiceHoldView.isHidden = false
                
                mutilChoiceHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                }
                
                bottomLine.snp.remakeConstraints { make in
                    make.top.equalTo(mutilChoiceHoldView.snp.bottom).offset(kMargin)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(0.5)
                    make.bottom.equalToSuperview()
                }
            }
        } 
        else {
            //需要展示提示的情况
            if model.type == 0 {
                additionHoldView.isHidden = false
                bottomLine.isHidden = false
                
                additionHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(78)
                }
                
                if model.info.count < 1 {
                    noTextTipsLable.isHidden = false
                    noTextTipsLable.snp.remakeConstraints { make in
                        make.top.equalTo(additionHoldView.snp.bottom).offset(6)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(20)
                    }
                    
                    bottomLine.snp.remakeConstraints { make in
                        make.top.equalTo(noTextTipsLable.snp.bottom).offset(kMargin)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(0.5)
                        
                        make.bottom.equalToSuperview()
                    }
                } else {
                    bottomLine.snp.remakeConstraints { make in
                        make.top.equalTo(additionHoldView.snp.bottom).offset(kMargin)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(0.5)
                        
                        make.bottom.equalToSuperview()
                    }
                }
                
            } else {
                mutilChoiceHoldView.isHidden = false
                bottomLine.isHidden = false
                
                mutilChoiceHoldView.snp.remakeConstraints { make in
                    make.top.equalTo(answer1Btn.snp.bottom).offset(12)
                    make.left.right.equalToSuperview()
                }
                
                if model.info.count < 1 {
                    noChoiceTipsLable.isHidden = false
                    noChoiceTipsLable.snp.remakeConstraints { make in
                        make.top.equalTo(mutilChoiceHoldView.snp.bottom).offset(6)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(20)
                    }
                    
                    bottomLine.snp.remakeConstraints { make in
                        make.top.equalTo(noChoiceTipsLable.snp.bottom).offset(kMargin)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(0.5)
                        
                        make.bottom.equalToSuperview()
                    }
                } else {
                    bottomLine.snp.remakeConstraints { make in
                        make.top.equalTo(mutilChoiceHoldView.snp.bottom).offset(kMargin)
                        make.left.right.equalToSuperview()
                        make.height.equalTo(0.5)
                        
                        make.bottom.equalToSuperview()
                    }
                }
            }
        }
    }
    
    
    //选择 否 的布局
    func layoutForNO() {
        guard model != nil else {
            printLog("error :  有问题 需要处理。。。。")
            return
        }
        
        //隐藏提示
        bottomLine.isHidden = false
        noChoiceTipsLable.isHidden = true
        additionHoldView.isHidden = true
        mutilChoiceHoldView.isHidden = true
        noTextTipsLable.isHidden = true
        
        additionHoldView.snp.removeConstraints()
        mutilChoiceHoldView.snp.removeConstraints()
        noChoiceTipsLable.snp.removeConstraints()
        noTextTipsLable.snp.removeConstraints()
        
        bottomLine.snp.removeConstraints()
        bottomLine.snp.makeConstraints { make in
            make.top.equalTo(answer1Btn.snp.bottom).offset(kMargin)
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
    }
    
    //没有选择 是和否的情况
    func layoutForMakeNoChoice() {
        guard let model = model else {
            printLog("error :  有问题 需要处理。。。。")
            return
        }
        
        if model.needCheckFlag == true {
            //展示提示
            bottomLine.isHidden = false
            noChoiceTipsLable.isHidden = false
            additionHoldView.isHidden = true
            mutilChoiceHoldView.isHidden = true
            noTextTipsLable.isHidden = true
            
            additionHoldView.snp.removeConstraints()
            mutilChoiceHoldView.snp.removeConstraints()
            
            noChoiceTipsLable.snp.remakeConstraints { make in
                make.top.equalTo(answer1Btn.snp.bottom).offset(18)
                make.left.right.equalToSuperview()
                make.height.equalTo(20)
            }
            
            bottomLine.snp.removeConstraints()
            bottomLine.snp.makeConstraints { make in
                make.top.equalTo(noChoiceTipsLable.snp.bottom).offset(kMargin)
                make.left.right.equalToSuperview()
                make.height.equalTo(0.5)
                make.bottom.equalToSuperview()
            }
            
        } else {
            //隐藏提示
            bottomLine.isHidden = false
            noChoiceTipsLable.isHidden = true
            additionHoldView.isHidden = true
            mutilChoiceHoldView.isHidden = true
            noTextTipsLable.isHidden = true
            
            additionHoldView.snp.removeConstraints()
            mutilChoiceHoldView.snp.removeConstraints()
            noChoiceTipsLable.snp.removeConstraints()
            
            bottomLine.snp.removeConstraints()
            bottomLine.snp.makeConstraints { make in
                make.top.equalTo(answer1Btn.snp.bottom).offset(kMargin)
                make.left.right.equalToSuperview()
                make.height.equalTo(0.5)
                make.bottom.equalToSuperview()
            }
        }
    }
}

