//
//  YHApplyActivityAlert.swift
//  galaxy
//
//  Created by davidhuangA on 2024/6/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import AttributedString


class YHApplyActivityAlert: UIView {
    
    typealias Block = (Bool,String,Int,String) -> ()
    var block: Block?
    var centerView: UIView!
    var titleLabel: UILabel!
    var messageLabel: UILabel!
    var agreeButton: UIButton!
    
    private let contentViewH : CGFloat = 386.0
    private var applyName : String = ""
    private var applyNumber : Int = 1
    private var applyPhone : String = ""
    private var needCheckFlag : Bool = false
    
    
    
    lazy var nameTextField:UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.attributedPlaceholder = NSAttributedString(string: "请输入您的姓名".local, attributes: [NSAttributedString.Key.foregroundColor : UIColor.mainTextColor30])
        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
    }()
    
    
    lazy var subButton:UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        button.contentHorizontalAlignment = .center
        button.setImage(UIImage(named: "activity_sub_0"), for: .normal)
        button.setImage(UIImage(named: "activity_sub_0"), for: .disabled)
        button.setImage(UIImage(named: "activity_sub_1"), for: .selected)
        button.setImage(UIImage(named: "activity_sub_1"), for: .highlighted)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.layer.cornerRadius = kCornerRadius3
        button.addTarget(self, action: #selector(clickSubBtn), for: .touchUpInside)
        return button
    }()
    
    
    lazy var addButton:UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        button.contentHorizontalAlignment = .center

        button.setImage(UIImage(named: "activity_add_0"), for: .normal)
        button.setImage(UIImage(named: "activity_add_0"), for: .disabled)
        button.setImage(UIImage(named: "activity_add_1"), for: .selected)
        button.setImage(UIImage(named: "activity_add_1"), for: .highlighted)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.layer.cornerRadius = kCornerRadius3
        button.addTarget(self, action: #selector(clickAddBtn), for: .touchUpInside)
        return button
    }()
    
    
    lazy var applyNumberTextField:UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.attributedPlaceholder = NSAttributedString(string: "".local, attributes: [NSAttributedString.Key.foregroundColor : UIColor.yhGreyColor])
        textField.font = UIFont.PFSC_M(ofSize: 14)
        textField.tintColor = UIColor.brandMainColor
        textField.textColor = UIColor.mainTextColor
        textField.textAlignment = .center
        textField.text = "1"
        textField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged)
        textField.addTarget(self, action: #selector(textFieldEditEnd(textField:)), for: .editingDidEnd)
        textField.delegate = self
        textField.keyboardType = .numberPad
        return textField
    }()
    
    
    lazy var phoneTextField:UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.attributedPlaceholder = NSAttributedString(string: "请输入".local, attributes: [NSAttributedString.Key.foregroundColor : UIColor.mainTextColor30])
        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
    }()
    
    lazy var phoneTipsLable:UILabel = {
        let lable = UILabel()
        lable.textColor = UIColor.failColor
        lable.textAlignment = .left
        lable.font = UIFont.PFSC_R(ofSize:12)
        lable.text = "手机号不能为空"
        lable.isHidden = true
        return lable
    }()
    
    
    lazy var submitButton:UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.contentHorizontalAlignment = .center
        button.setTitle("提交", for: .normal)
        button.setTitle("提交", for: .highlighted)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.setTitleColor( UIColor(hex:0xffffff), for: .highlighted)
        button.layer.cornerRadius = kCornerRadius3
        button.addTarget(self, action: #selector(clickSubmitBtn), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()
    
    
    lazy var line4 : UIView = {
        let line4 = UIView()
        line4.backgroundColor = UIColor.separatorColor
        return line4
    }()
    
    //类方法 - 展示
    static func showApplyActivityAlertView(name : String = "",callBack: @escaping Block) {
        let view = YHApplyActivityAlert(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        
        var ttt = name
        let tName = ttt.slice(from: 0, length: 10)
        view.applyName = tName
        view.nameTextField.text = tName
        view.block = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if needCheckFlag {
            if applyPhone.isEmpty {
                phoneTipsLable.isHidden = false
                
                line4.snp.remakeConstraints { make in
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.height.equalTo(1)
                    make.top.equalTo(phoneTipsLable.snp.bottom).offset(16)
                }
            } else {
                phoneTipsLable.isHidden = true
                line4.snp.remakeConstraints { make in
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.height.equalTo(1)
                    make.top.equalTo(phoneTextField.snp.bottom).offset(16)
                }
            }
        } else {
            phoneTipsLable.isHidden = true
            line4.snp.remakeConstraints { make in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.height.equalTo(1)
                make.top.equalTo(phoneTextField.snp.bottom).offset(16)
            }
        }
    }
}

extension YHApplyActivityAlert {
    
    func handleSubAndAddButtonUI() {
        if applyNumber > 9 {
            subButton.isEnabled = true
            addButton.isEnabled = false
            
            subButton.isSelected = true
            addButton.isSelected = false
        } else if applyNumber > 1 {
            subButton.isEnabled = true
            addButton.isEnabled = true
            
            subButton.isSelected = true
            addButton.isSelected = true
        }
        else {
            subButton.isEnabled = false
            addButton.isEnabled = true
            
            subButton.isSelected = false
            addButton.isSelected = true
            
        }
        
        setNeedsLayout()
        layoutIfNeeded()
    }
    
    @objc func textFieldChanged(textField:UITextField) {
        
        printLog(textField.text)
        
        if textField == nameTextField {
            applyName = textField.text ?? ""
        } else if textField == applyNumberTextField {
            if let tf = textField.text {
                if tf.isEmpty {
                    applyNumber = 1
                } else {
                    applyNumber = Int(tf) ?? 1
                }
            }
        } else if textField == phoneTextField {
            applyPhone = textField.text ?? ""
        } else {
            
        }
        
        setNeedsLayout()
        layoutIfNeeded()
        
        handleSubAndAddButtonUI()
        updateButtonUI()
        
    }
    
    
    @objc func textFieldEditEnd(textField:UITextField) {
        printLog(textField.text)
        if textField == nameTextField {
            
        } else if textField == applyNumberTextField {
            if let tf = textField.text {
                if tf.isEmpty {
                    textField.text = "1"
                    applyNumber = 1
                }
                
            } else {
                textField.text = "1"
                applyNumber = 1
            }
            
            handleSubAndAddButtonUI()
            
        } else if textField == phoneTextField {
            
        } else {
            
        }
    }
    
    
    
    
    @objc func clickSubBtn() {
        applyNumber = applyNumber - 1
        applyNumberTextField.text = String(applyNumber)
        
        handleSubAndAddButtonUI()
    }
    
    @objc func clickAddBtn() {
        applyNumber = applyNumber + 1
        applyNumberTextField.text = String(applyNumber)
        handleSubAndAddButtonUI()
    }
    
    @objc func clickCloseBtn() {
        dismiss()
    }
    
    @objc func clickSubmitBtn() {
        subButton.isEnabled = false
        DispatchQueue.main.async {
            self.subButton.isEnabled = true
            if self.allDataIsOK() {
                self.block?(true,self.applyName,self.applyNumber,self.applyPhone)
                self.clickCloseBtn()
            }  else {
                self.handleSubAndAddButtonUI()
            }
            
        }
    }
    
    
    @objc func agree() {
        block?(true,"",0,"")
    }
    
    @objc func disagree() {
        block?(false,"",0,"")
        dismiss()
    }
    
    func dismiss() {
        removeNotify()
        removeFromSuperview()
    }
    
    @objc func tapButton(gestureRecognizer:UITapGestureRecognizer) {
        endEditing(true)
    }
    
    func allDataIsOK() -> Bool {
        if applyPhone.isEmpty {
            return false
        }
        return true
    }
    
    
    
    func setView() {
        backgroundColor = UIColor.mainTextColor50
        
        addKeyBoardNotify()
        
        
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(contentViewH)
        }
        centerView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:centerView.bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(kCornerRadius6, kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
        
        
        //1.0
        let titleLable = UILabel()
        titleLable.textColor = UIColor.mainTextColor
        titleLable.textAlignment = .center
        titleLable.font = UIFont.PFSC_M(ofSize:17)
        titleLable.text = "活动报名"
        titleLable.numberOfLines = 0
        
        centerView.addSubview(titleLable)
        titleLable.snp.makeConstraints { make in
            make.top.equalTo(kMargin)
            make.centerX.equalToSuperview()
            make.height.equalTo(24)
        }
        
        
        let line1 = UIView()
        line1.backgroundColor = .separatorColor
        centerView.addSubview(line1)
        line1.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
            make.top.equalTo(titleLable.snp.bottom).offset(12)
        }
        
        
        let closeBtn : UIButton = UIButton(type: .custom)
        closeBtn.setImage(UIImage(named: "person_info_close_btn"), for: .normal)
        closeBtn.setImage(UIImage(named: "person_info_close_btn"), for: .highlighted)
        centerView.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(clickCloseBtn), for: .touchUpInside)
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLable.snp.centerY)
            make.right.equalTo(-21)
            make.width.height.equalTo(24)
        }
        closeBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        
        //1、您的姓名
        let nameLable = UILabel()
        nameLable.textColor = UIColor.mainTextColor
        nameLable.textAlignment = .left
        nameLable.font = UIFont.PFSC_R(ofSize:14)
        nameLable.text = "您的姓名"
        centerView.addSubview(nameLable)
        nameLable.snp.makeConstraints { make in
            make.left.equalTo(28)
            make.height.equalTo(20)
            make.top.equalTo(line1.snp.bottom).offset(36)
        }
        let a: ASAttributedString = .init("*", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.failColor))
        let b: ASAttributedString = .init(" 您的姓名", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor))
        nameLable.attributed.text = a + b
        
        centerView.addSubview(nameTextField)
        nameTextField.text = ""
        nameTextField.snp.makeConstraints { make in
            make.left.equalTo(nameLable.snp.right).offset(48)
            make.centerY.equalTo(nameLable.snp.centerY)
            make.height.equalTo(nameLable.snp.height)
            make.right.equalTo(-kMargin)
        }
        
        let line2 = UIView()
        line2.backgroundColor = .separatorColor
        centerView.addSubview(line2)
        line2.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
            make.top.equalTo(nameTextField.snp.bottom).offset(16)
        }
        
        //2、报名人数
        let numberLable = UILabel()
        numberLable.textColor = UIColor.mainTextColor
        numberLable.textAlignment = .left
        numberLable.font = UIFont.PFSC_R(ofSize:14)
        numberLable.text = "报名人数"
        centerView.addSubview(numberLable)
        numberLable.snp.makeConstraints { make in
            make.left.equalTo(nameLable.snp.left)
            make.height.equalTo(20)
            make.top.equalTo(line2.snp.bottom).offset(20)
        }
        
        
        let aa: ASAttributedString = .init("*", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.failColor))
        let bb: ASAttributedString = .init(" 报名人数", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor))
        numberLable.attributed.text = aa + bb
        
        
        centerView.addSubview(subButton)
        subButton.snp.makeConstraints { make in
            make.left.equalTo(numberLable.snp.right).offset(48)
            make.centerY.equalTo(numberLable.snp.centerY)
            make.width.height.equalTo(28)
        }
        
        
        centerView.addSubview(applyNumberTextField)
        applyNumberTextField.snp.makeConstraints { make in
            make.left.equalTo(subButton.snp.right).offset(2)
            make.centerY.equalTo(numberLable.snp.centerY)
            make.width.equalTo(42)
            make.height.equalTo(28)
        }
        applyNumberTextField.layer.cornerRadius = kCornerRadius6
        applyNumberTextField.backgroundColor = UIColor(hex: 0xf5f5f5, alpha: 1.0)
        
        
        centerView.addSubview(addButton)
        addButton.snp.makeConstraints { make in
            make.left.equalTo(applyNumberTextField.snp.right).offset(2)
            make.centerY.equalTo(numberLable.snp.centerY)
            make.width.height.equalTo(28)
        }
        
        
        
        let line3 = UIView()
        line3.backgroundColor = .separatorColor
        centerView.addSubview(line3)
        line3.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
            make.top.equalTo(addButton.snp.bottom).offset(16)
        }
        
        
        //3、手机号码
        let phoneLable = UILabel()
        phoneLable.textColor = UIColor.mainTextColor
        phoneLable.textAlignment = .left
        phoneLable.font = UIFont.PFSC_R(ofSize:14)
        phoneLable.text = "手机号码"
        centerView.addSubview(phoneLable)
        phoneLable.snp.makeConstraints { make in
            make.left.equalTo(nameLable.snp.left)
            make.height.equalTo(20)
            make.top.equalTo(line3.snp.bottom).offset(20)
        }
        
        let aaa: ASAttributedString = .init("*", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.failColor))
        let bbb: ASAttributedString = .init(" 手机号码", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor))
        phoneLable.attributed.text = aaa + bbb
        
        
        
        centerView.addSubview(phoneTextField)
        phoneTextField.snp.makeConstraints { make in
            make.left.equalTo(subButton.snp.left)
            make.height.equalTo(20)
            make.centerY.equalTo(phoneLable)
            make.right.equalTo(-20)
        }
        phoneTextField.keyboardType = .phonePad
        
        centerView.addSubview(line4)
        line4.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(1)
            make.top.equalTo(phoneTextField.snp.bottom).offset(39)
        }
        
        
        centerView.addSubview(phoneTipsLable)
        phoneTipsLable.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(17)
            make.top.equalTo(phoneTextField.snp.bottom).offset(6)
        }
        
        
        //提交
        centerView.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(48)
            make.bottom.equalToSuperview().offset(-42)
        }
        
        subButton.isEnabled = false
        addButton.isEnabled = true
        addButton.isSelected = true
        
        
        let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapButton(gestureRecognizer:)))
        addGestureRecognizer(tap)
        
        let tap1 : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapButton(gestureRecognizer:)))
        centerView.addGestureRecognizer(tap1)
        
        updateButtonUI()
    }
    
    
    func updateButtonUI() {
        guard let name = nameTextField.text,name.isEmpty == false,let number = applyNumberTextField.text,number.isEmpty == false,let phone = phoneTextField.text,phone.isEmpty == false else {
            
            self.submitButton.isEnabled = false
            self.submitButton.backgroundColor = UIColor.brandMainColor30
            return
        }
        
        
        self.submitButton.isEnabled = true
        self.submitButton.backgroundColor = UIColor.brandMainColor
        
        handleSubAndAddButtonUI()
        
        
    }
}


extension YHApplyActivityAlert: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.isEmpty{ // 点击删除
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if textField == nameTextField {
            if newText.count > 20 {
                updateButtonUI()
                return false
            }
        } else if textField == applyNumberTextField {
            if !string.isNumeric {
                YHHUD.flash(message: "请输入数字")
                applyNumber = 1
                updateButtonUI()
                return false
            }
            
            
            if let item = Int(newText),item > 10 {
                textField.text = "10"
                YHHUD.flash(message: "最多添加10人")
                applyNumber = 10
                handleSubAndAddButtonUI()
                updateButtonUI()
                return false
            } else if  let item = Int(newText),item < 1 {
                textField.text = "1"
                applyNumber = 1
                YHHUD.flash(message: "最少添加1人")
                handleSubAndAddButtonUI()
                updateButtonUI()
                return false
            }
            
        } else if textField == phoneTextField {
            if newText.count > 20 {
                updateButtonUI()
                return false
                
            }
            
        } else {
            
        }
        
        return true
    }
}



extension YHApplyActivityAlert {
    
    func addKeyBoardNotify() {
        
        IQKeyboardManager.shared.isEnabled = false
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        IQKeyboardManager.shared.isEnabled = true
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }
            
            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : 0)
            
            centerView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
           handleSubAndAddButtonUI()
        }
    }
}
