//
//  YHFriendRequestView.swift
//  galaxy
//
//  Created by edy on 2024/6/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHFriendRequestView: UIView {

    var sendBlock: ((String?) -> Void)?
    static let cardHeight = 313.0
    let textMaxCount = 200
    let defaultStr = "在银河相遇，期待与你共话未来，互学互鉴，盼成为好友，谢谢~"
    var userModel: YHContact = YHContact() {
        didSet {
            if let url = URL(string: self.userModel.avatar) {
                self.headImgV.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
            } else {
                self.headImgV.image = UIImage(named: "people_head_default")
            }
            self.nameLabel.text = self.userModel.username
//            self.signImgV.isHidden = !self.userModel.isSign
            
            var text1 = ""
            var text1Arr: [String] = []
            if !self.userModel.position.isEmpty {
                text1Arr.append(self.userModel.position)
            }
            if !self.userModel.industry.isEmpty {
                text1Arr.append(self.userModel.industry)
            }
            if text1Arr.count > 0 {
                text1 = text1Arr.joined(separator: " | ")
            }
            self.professionalLabel.text = text1
        }
    }
    
    var userModel2: YHUserNameCardInfo = YHUserNameCardInfo() {
        didSet {
            if let url = URL(string: self.userModel2.avatar) {
                self.headImgV.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
            } else {
                self.headImgV.image = UIImage(named: "people_head_default")
            }
            self.nameLabel.text = self.userModel2.username
//            self.signImgV.isHidden = !self.userModel.isSign
            
            var text1 = ""
            var text1Arr: [String] = []
            if !self.userModel2.position.isEmpty {
                text1Arr.append(self.userModel2.position)
            }
            if !self.userModel2.industry.isEmpty {
                text1Arr.append(self.userModel2.industry)
            }
            if text1Arr.count > 0 {
                text1 = text1Arr.joined(separator: " | ")
            }
            self.professionalLabel.text = text1
        }
    }
    
    // 底层蒙版
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = .alertMaskColor
        let tap = UITapGestureRecognizer(target: self, action: #selector(didMaskViewClicked))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var cardView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 6.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var headImgV: UIImageView = {
        let view = UIImageView(image: UIImage(named: "people_head_default"))
        view.layer.cornerRadius = 23.0
        view.clipsToBounds = true
        view.contentMode = .scaleAspectFill
        return view
    }()
    
    lazy var nameLabel: UILabel = {
        let nameLabel = UILabel()
        nameLabel.textColor = UIColor.mainTextColor
        nameLabel.textAlignment = .left
        nameLabel.font = UIFont.PFSC_B(ofSize: 16)
        return nameLabel
    }()
    
    lazy var signImgV: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "people_sign")
        view.isHidden = true
        return view
    }()
    
    lazy var professionalLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor70
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 13)
        return label
    }()
    
    lazy var msgContentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0xF8F8F8)
        view.layer.cornerRadius = 3.0
        return view
    }()
    
    lazy var textView: UITextView = {
        let view = UITextView()
        view.textColor = .mainTextColor70
        view.font = UIFont.PFSC_R(ofSize: 14)
        view.backgroundColor = .clear
        view.text = self.defaultStr
        view.delegate = self
        return view
    }()
    
    lazy var textCountLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor30
        label.textAlignment = .right
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.text = "\(self.defaultStr.count)/\(self.textMaxCount)"
        return label
    }()
    
    lazy var cancelBtn: UIButton = {
       let btn = UIButton()
        btn.setTitle("取消", for: .normal)
        btn.backgroundColor = .white
        btn.setTitleColor(.brandGrayColor8, for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 14)
        btn.layer.cornerRadius = 3
        btn.layer.borderWidth = 1.0
        btn.layer.borderColor = UIColor.brandGrayColor8.cgColor
        btn.addTarget(self, action: #selector(didCancelBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var sendBtn: UIButton = {
       let btn = UIButton()
        btn.setTitle("发送申请", for: .normal)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 14)
        btn.layer.cornerRadius = 3
        btn.addTarget(self, action: #selector(didSendBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.placeHolderColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.numberOfLines = 0
        label.isHidden = false
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func createView() -> YHFriendRequestView {
        let view = YHFriendRequestView(frame: UIScreen.main.bounds)
        return view
    }
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func didCancelBtnClicked() {
        dismiss()
    }
    
    @objc func didSendBtnClicked() {
        var text = self.textView.text
        if isEmptyString(text) {
            text = self.defaultStr
        }
        self.sendBlock?(text)
        dismiss()
    }
    
    @objc func didMaskViewClicked() {
        self.endEditing(true)
    }
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func createUI() {
        
        addKeyBoardNotify()
        
        self.addSubview(self.blackMaskView)
        self.addSubview(cardView)
        cardView.addSubview(headImgV)
        cardView.addSubview(nameLabel)
        cardView.addSubview(signImgV)
        cardView.addSubview(professionalLabel)
        
        cardView.addSubview(msgContentView)
        msgContentView.addSubview(textView)
//        msgContentView.addSubview(placeHolderLabel)
        msgContentView.addSubview(textCountLabel)
        
        cardView.addSubview(cancelBtn)
        cardView.addSubview(sendBtn)
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        cardView.snp.makeConstraints { make in
            make.left.equalTo(38)
            make.right.equalTo(-38)
            make.bottom.equalToSuperview().offset(-(KScreenHeight-YHFriendRequestView.cardHeight)/2.0)
            make.height.equalTo(Self.cardHeight)
        }
        
        headImgV.snp.makeConstraints { make in
            make.width.height.equalTo(46.0)
            make.left.equalTo(21)
            make.top.equalTo(30)
        }
        
        self.nameLabel.snp.makeConstraints { make in
            make.left.equalTo(self.headImgV.snp.right).offset(10)
            make.height.equalTo(22.0)
            make.top.equalTo(self.headImgV)
        }
        
        self.signImgV.snp.makeConstraints { make in
            make.width.equalTo(49)
            make.height.equalTo(16)
            make.centerY.equalTo(self.nameLabel)
            make.left.equalTo(self.nameLabel.snp.right).offset(8)
            make.right.lessThanOrEqualToSuperview().offset(-16)
        }
        
        self.professionalLabel.snp.makeConstraints { make in
            make.left.equalTo(self.nameLabel)
            make.right.equalTo(-16)
            make.top.equalTo(self.nameLabel.snp.bottom).offset(6)
            make.height.equalTo(18)
        }
        
        self.msgContentView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(self.headImgV.snp.bottom).offset(16)
            make.height.equalTo(140)
        }
        
        self.textView.snp.makeConstraints { make in
            make.left.top.equalTo(10)
            make.right.equalTo(-10)
        }
        
//        self.placeHolderLabel.snp.makeConstraints { make in
//            make.top.equalTo(self.textView.snp.top).offset(7)
//            make.left.equalTo(self.textView.snp.left).offset(7)
//            make.right.equalTo(self.textView)
//        }
        
        self.textCountLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(self.textView.snp.bottom).offset(10)
            make.height.equalTo(16)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        self.cancelBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(self.msgContentView.snp.bottom).offset(20)
            make.width.equalTo(self.sendBtn)
            make.height.equalTo(45)
        }
        
        self.sendBtn.snp.makeConstraints { make in
            make.left.equalTo(self.cancelBtn.snp.right).offset(10)
            make.right.equalTo(-16)
            make.centerY.equalTo(self.cancelBtn)
            make.height.equalTo(45)
        }
    }
    
    @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+20 : (KScreenHeight-YHFriendRequestView.cardHeight)/2.0)
            self.cardView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(-bottomMargin)
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
}

extension YHFriendRequestView: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        self.textCountLabel.text = "\(textView.text.count)/\(self.textMaxCount)"
        self.placeHolderLabel.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text.isEmpty {
            return true
        }
        let newLength = (textView.text as NSString).length + text.count - range.length
        return newLength <= self.textMaxCount
    }
}
