//
//  YHNewNameCardViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/9/29.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHNewNameCardViewController: YHBaseViewController {
    
    var userId: String = ""
    var defaultIndex = 0
    let viewModel = YHMatchUserViewModel()
    var authorModel: YHInformationAuthorizeViewModel = YHInformationAuthorizeViewModel()

    var headerHeight: CGFloat = 300.0
    let containerCellHeight = KScreenHeight-k_Height_NavigationtBarAndStatuBar-k_Height_safeAreaInsetsBottom()-88
    
    var canScroll: Bool = true
    var isCurrentUser: Bool {
        get {
           return (!self.userId.isEmpty && self.userId == YHLoginManager.shared.userModel?.id)
        }
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        return tableView
    }()
    
    lazy var containerVC: YHNameCardContainerViewController = {
        let vc = YHNameCardContainerViewController()
        return vc
    }()

    lazy var headerView: UIView = {
        let view = UIView()
        view.clipsToBounds = true
        view.backgroundColor = UIColor(hexString: "#E2E3E8")
        let bgImgView = UIImageView()
        bgImgView.image = UIImage(named: "name_card_bg")
        view.addSubview(bgImgView)
        bgImgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(bgImgView.snp.width).multipliedBy(800.0 / 375.0)
        }
        
        view.addSubview(avatarImgView)
        avatarImgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(24 + k_Height_NavigationtBarAndStatuBar)
            make.width.height.equalTo(68)
        }
        view.addSubview(editBtn)
        editBtn.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.centerY.equalTo(avatarImgView)
            make.right.equalTo(-20)
        }
        view.addSubview(nameTextView)
        nameTextView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(avatarImgView.snp.bottom).offset(12)
        }
        view.addSubview(professionalLabel)
        professionalLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(nameTextView.snp.bottom).offset(4)
        }
        view.addSubview(signatureLabel)
        signatureLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(professionalLabel.snp.bottom).offset(6)
            make.bottom.equalTo(-32)
        }
        return view
    }()

    lazy var avatarImgView: UIImageView = {
        let avatarImgV = UIImageView()
//        avatarImgV.backgroundColor = UIColor.brandGrayColor8
        avatarImgV.layer.cornerRadius = 68.0 / 2
        avatarImgV.clipsToBounds = true
        return avatarImgV
    }()

    lazy var editBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage(named: "name_card_edit"), for: .normal)
        btn.addTarget(self, action: #selector(didBasciInfoBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var nameTextView: UITextView = {
        let textView = UITextView()
        textView.textColor = UIColor.brandGrayColor8
        textView.backgroundColor = .clear
        textView.font = UIFont.PFSC_M(ofSize: 21)
        textView.isScrollEnabled = false
        textView.isEditable = false
        textView.isSelectable = false
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets.zero
        textView.showsVerticalScrollIndicator = false
        return textView
    }()

    lazy var professionalLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.brandGrayColor8
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.numberOfLines = 2
        return label
    }()

    lazy var signatureLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.brandGrayColor8
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.numberOfLines = 2
        return label
    }()

    lazy var cityLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.brandGrayColor8
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize: 10)
        label.layer.cornerRadius = 9.0
        label.layer.borderColor = UIColor.brandGrayColor8.cgColor
        label.layer.borderWidth = 0.5
        return label
    }()

    lazy var zodiacLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.brandGrayColor8
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize: 10)
        label.layer.cornerRadius = 9.0
        label.layer.borderColor = UIColor.brandGrayColor8.cgColor
        label.layer.borderWidth = 0.5
        label.frame = CGRect(x: 0, y: 0, width: 42, height: 18)
        return label
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.addSubview(buttonsContentV)
        view.addSubview(sendLabel)
        buttonsContentV.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(64)
        }
        sendLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(16)
            make.top.equalTo(8)
        }
        return view
    }()
    
    lazy var sendLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.brandGrayColor6
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.text = "已为您发送好友申请"
        label.isHidden = true
        return label
    }()
    
    lazy var publishBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("发布动态", for: .normal)
        btn.addTarget(self, action: #selector(publishBtnClicked), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.layer.cornerRadius = 3.0
        btn.masksToBounds = true
        btn.isHidden = true
        return btn
    }()
    
    lazy var cooperationBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("联系合作", for: .normal)
        btn.addTarget(self, action: #selector(cooperationBtnClicked), for: .touchUpInside)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.layer.cornerRadius = 3.0
        btn.masksToBounds = true
        btn.isHidden = true
        return btn
    }()
    
    lazy var addFriendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("添加好友", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
        btn.setTitleColor(.brandGrayColor8, for: .normal)
        btn.backgroundColor = UIColor.brandGrayColor2
        btn.addTarget(self, action: #selector(didAddFriendBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = 3.0
        btn.masksToBounds = true
        btn.isHidden = true
        return btn
    }()
    
    // 消息处理器
        private lazy var messageHandler: YHIMMessageHandler = {
            return YHIMMessageHandler(
                viewController: self,
                navigationController: navigationController
            )
        }()
    
    @objc func publishBtnClicked() {
        YHHUD.show(.progress(message: ""))
        authorModel.requestUserInfo { [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else {
                return
            }
            if self.authorModel.model.username.isEmpty {
                YHGrayCommonAlertView.show("", "请先完善个人信息后再来发布动态", "返回", "前往完善", fullGuestureEnable: false) {
                } callBack: { [weak self] in
                    guard let self = self else {
                        return
                    }
                    let userInfoPage = YHInformationAuthorizationStepOneViewController()
                    self.navigationController?.pushViewController(userInfoPage)
                }
            } else {
                let user = YHCirclePublishViewController.UserInfo()
                user.userName = self.authorModel.model.username
                user.userTitle = self.authorModel.model.position
                user.avatar = self.authorModel.model.avatar
                let publishVC = YHCirclePublishViewController(currentUser: user)
                publishVC.completion = { [weak self] in
                    self?.requestNameCardInfo()
                }
                let nav = YHNavigationController(rootViewController: publishVC)
                nav.modalPresentationStyle = .fullScreen
                present(nav, animated: true)
            }
        }
    }
    
    @objc func cooperationBtnClicked() {
        self.messageHandler.gotoChatVC(senderID: self.userId)
    }
    
    @objc func didAddFriendBtnClicked() {
        let view = YHFriendRequestView.createView()
        view.userModel2 = self.viewModel.nameCardInfo
        view.sendBlock = {
            [weak self] text in
            guard let self = self else { return }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.addFriendWithText(text!, yhId: self.userId) {
                success, error in
                YHHUD.hide()
                if success {
                    self.viewModel.nameCardInfo.type = YHContactRelation.unvalidate.rawValue
                    self.updateBottomButton()
                    
                } else {
                    var msg = "申请失败"
                    if let errMsg = error?.errorMsg, !errMsg.isEmpty {
                        msg = errMsg
                    }
                    YHHUD.flash(message: msg)
                }
            }
        }
        view.show()
    }
    
    lazy var buttonsContentV: UIView = {
        let v = UIView()
        v.addSubview(addFriendBtn)
        v.addSubview(cooperationBtn)
        v.addSubview(publishBtn)
        
        publishBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(46)
            make.top.equalTo(8)
            make.bottom.equalTo(-10)
        }
        
        addFriendBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(cooperationBtn.snp.left).offset(-10)
            make.width.equalTo(116)
            make.height.equalTo(46)
            make.top.equalTo(8)
            make.bottom.equalTo(-10)
        }
        
        cooperationBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.height.equalTo(46)
            make.top.equalTo(8)
            make.bottom.equalTo(-10)
        }
        
        return v
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_navigationBar.backgroundColor = .clear
        
        if isCurrentUser {
            let rightButtonItem = UIBarButtonItem(image: UIImage(named: "name_card_authorize")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(authorizeBtnClicked))
            gk_navRightBarButtonItem = rightButtonItem
            gk_navItemRightSpace = 16
        }
        
        containerVC.userId = self.userId
        createUI()
        if self.isCurrentUser {
            requestAuthorization()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestNameCardInfo()
    }
    
    func requestAuthorization() {
        self.authorModel.requestUserAuthorization { _, _ in
            if self.authorModel.setModel.authorization_basic_information != 2 && self.authorModel.setModel.isclick_card != 2 {
                YHGrayCommonAlertView.show("温馨提示", "是否授权信息在公开的人脉列表中展示", "取消", "确认", fullGuestureEnable: false) {
                    self.authorModel.requestInformationToCardSubmit(agress: 1) { _, _ in
                        self.requestNameCardInfo()
                    }
                } callBack: {
                    self.authorModel.requestInformationToCardSubmit(agress: 2) { _, _ in
                        self.authorModel.requestBusinessCardAuthorize { _, _ in
                            self.requestNameCardInfo()
                        }
                    }
                }
            }
        }
    }
    
    func createUI() {
        addObserver()
        self.editBtn.isHidden = !self.isCurrentUser
        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(bottomView)
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        bottomView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.height.equalTo(64)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
        }
        
        updateBottomButton()
    }
    
    func updateBottomButton() {
        if isCurrentUser {
            publishBtn.isHidden = false
            addFriendBtn.isHidden = true
            cooperationBtn.isHidden = true
            sendLabel.isHidden = true
            bottomView.snp.updateConstraints { make in
                make.height.equalTo(64)
            }
            
        } else {
            if self.viewModel.nameCardInfo.type == YHContactRelation.friend.rawValue { // 是好友
                publishBtn.isHidden = true
                addFriendBtn.isHidden = true
                cooperationBtn.isHidden = false
                sendLabel.isHidden = true
                
                bottomView.snp.updateConstraints { make in
                    make.height.equalTo(64)
                }
                addFriendBtn.snp.updateConstraints { make in
                    make.width.equalTo(0)
                    make.right.equalTo(cooperationBtn.snp.left).offset(0)
                }
                
            } else if self.viewModel.nameCardInfo.type == YHContactRelation.unvalidate.rawValue { // 已发送好友请求
                publishBtn.isHidden = true
                addFriendBtn.isHidden = true
                cooperationBtn.isHidden = false
                sendLabel.isHidden = false
                
                bottomView.snp.updateConstraints { make in
                    make.height.equalTo(88)
                }
                addFriendBtn.snp.updateConstraints { make in
                    make.width.equalTo(0)
                    make.right.equalTo(cooperationBtn.snp.left).offset(0)
                }
                
            } else if self.viewModel.nameCardInfo.type == YHContactRelation.stranger.rawValue { // 非好友
                publishBtn.isHidden = true
                addFriendBtn.isHidden = false
                cooperationBtn.isHidden = false
                sendLabel.isHidden = true
                
                bottomView.snp.updateConstraints { make in
                    make.height.equalTo(64)
                }
                
                addFriendBtn.snp.updateConstraints { make in
                    make.width.equalTo(116)
                    make.right.equalTo(cooperationBtn.snp.left).offset(-10)
                }
            }
        }
    }
    
    @objc func authorizeBtnClicked() {
        let vc = YHInformationAuthorizationStepTwoViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    @objc func didBasciInfoBtnClicked() {
        let vc = YHEditBaseUserInfoViewController()
        vc.model = self.viewModel.nameCardInfo
        self.navigationController?.pushViewController(vc)
    }
    
    func addObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(leaveTopOp), name: Notification.Name(rawValue: "leaveTop0"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(beginDragging), name: Notification.Name(rawValue: "scrollViewWillBeginDragging0"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(endDragging), name: Notification.Name(rawValue: "scrollViewDidEndDragging0"), object: nil)
    }
    
    func requestNameCardInfo() {
        containerVC.refreshData()
        self.viewModel.getUserNameCardInfo(uid: self.userId) {
            _, _ in
            self.updateModel()
            self.tableView.reloadData()
            self.updateBottomButton()
            self.containerVC.userInfo = self.viewModel.nameCardInfo
        }
    }
    
    func updateModel() {
        
        if let url = URL(string: self.viewModel.nameCardInfo.avatar) {
            self.avatarImgView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
        } else {
            self.avatarImgView.image = UIImage(named: "people_head_default")
        }

        // 城市和星座
        let cityText = self.viewModel.nameCardInfo.address.showCity()
        cityLabel.text = cityText
        let cityWidth = getWith(font: cityLabel.font, height: 18, string: cityText)
        cityLabel.frame = CGRect(x: 0, y: 0, width: cityWidth + 8, height: 18)

        let zodiacText = self.viewModel.nameCardInfo.zodiac
        zodiacLabel.text = zodiacText
        let zodiacWidth = getWith(font: zodiacLabel.font, height: 18, string: zodiacText)
        zodiacLabel.frame = CGRect(x: 0, y: 0, width: zodiacWidth + 8, height: 18)

        // 昵称
        var nameText = self.viewModel.nameCardInfo.username
        if self.viewModel.nameCardInfo.username.isEmpty, self.isCurrentUser {
            nameText = "请填写昵称"
        }
        var name: ASAttributedString = .init(string: nameText, .font(UIFont.PFSC_M(ofSize: 21)), .foreground(UIColor.brandGrayColor8))
        let cityTag: ASAttributedString = "  \(.view(cityLabel, .original(.center)))"
        let zodiacTag: ASAttributedString = "  \(.view(zodiacLabel, .original(.center)))"

        if !cityText.isEmpty {
            name += cityTag
        }
        if !zodiacText.isEmpty {
            name += zodiacTag
        }
        nameTextView.attributed.text = name
        
        // 职业行业
        var text1 = ""
        var text1Arr: [String] = []
        if !self.viewModel.nameCardInfo.position.isEmpty {
            text1Arr.append(self.viewModel.nameCardInfo.position)
        }
        if !self.viewModel.nameCardInfo.industry.isEmpty {
            text1Arr.append(self.viewModel.nameCardInfo.industry)
        }
        if text1Arr.count > 0 {
            text1 = text1Arr.joined(separator: " · ")
        }
            
        self.professionalLabel.textColor = UIColor.brandGrayColor8
        if text1.isEmpty {
            if self.isCurrentUser { // 当前用户默认文案
                self.professionalLabel.textColor = UIColor.brandGrayColor8
                text1 = "职位 | 行业"
            }
        }
        self.professionalLabel.text = text1
        
        // 个性签名
        self.signatureLabel.textColor = UIColor.brandGrayColor6
        var text2 = ""
        if !self.viewModel.nameCardInfo.signature.isEmpty {
            text2 = self.viewModel.nameCardInfo.signature
        } else {
            if self.isCurrentUser { // 当前用户默认文案
                self.signatureLabel.textColor = UIColor.brandGrayColor6
                text2 = "填写个性签名，展现真我风采，彰显独特身份"
            }
        }
        self.signatureLabel.text = text2

    }

    func getWith(font: UIFont, height: CGFloat, string: String) -> CGFloat {
        let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        let strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: ceil(strSize.width), height: strSize.height).width
    }
}

extension YHNewNameCardViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return containerCellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        containerVC.view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: containerCellHeight)
        cell.contentView.addSubview(containerVC.view)
        containerVC.view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension YHNewNameCardViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y > 0 {
            var alpha =  scrollView.contentOffset.y / (24)
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = "我的名片"

        } else {
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
        }
        
        // 吸顶
        let containerCellY: CGFloat = tableView.rectForRow(at: IndexPath(row: 0, section: 0)).origin.y
        let fixOffSetY: CGFloat = containerCellY-k_Height_NavigationtBarAndStatuBar
        if scrollView.contentOffset.y >= fixOffSetY {
            scrollView.contentOffset = CGPoint(x: 0, y: fixOffSetY)
            canScroll = false
            containerVC.canScroll = true
        } else {
            if canScroll == false {
                scrollView.contentOffset = CGPoint(x: 0, y: fixOffSetY)
            }
        }
    }
}

extension YHNewNameCardViewController {
    @objc func leaveTopOp() {
        canScroll = true
    }
    
    @objc func beginDragging() {
        tableView.isScrollEnabled = false
        canScroll = false
    }
    
    @objc func endDragging() {
        tableView.isScrollEnabled = true
        canScroll = true
    }
}
