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

import UIKit
import JXSegmentedView

class YHNameCardHomePageViewController: YHBaseViewController {
    
    var userId: String = ""
    var cardInfoArr: [YHUserNameCardInfo] = []
    let viewModel = YHMatchUserViewModel()
    
    var vcCanScroll: Bool = false
    
    var isCurrentUser: Bool {
        get {
           return (!self.userId.isEmpty && self.userId == YHLoginManager.shared.userModel?.id)
        }
    }
    
    lazy var tableView: YHGestureTableView = {
        let tableView = YHGestureTableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHMyNameCardAvatarInfoCell.self, forCellReuseIdentifier: YHMyNameCardAvatarInfoCell.cellReuseIdentifier)
        tableView.register(YHMyIntroductionCell.self, forCellReuseIdentifier: YHMyIntroductionCell.cellReuseIdentifier)
        tableView.register(YHMyEducationCell.self, forCellReuseIdentifier: YHMyEducationCell.cellReuseIdentifier)
        tableView.register(YHMyWorkExperienceCell.self, forCellReuseIdentifier: YHMyWorkExperienceCell.cellReuseIdentifier)
        tableView.register(YHMyInterestTopicCell.self, forCellReuseIdentifier: YHMyInterestTopicCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无内容", kEmptyCommonBgName)
        view.isHidden = true
        return view
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addObserver()
        view.backgroundColor = .white
        gk_navigationBar.isHidden = true
        createUI()
        requestNameCardInfo()
    }
    
    func createUI() {
        view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(72)
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
    }
    
    func addObserver() {
        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() {
        self.viewModel.getUserNameCardInfo(uid: self.userId) {
            _, _ in
            
            self.cardInfoArr.removeAll()
            
            // 个人简介信息
            var isShowIntroduce = true
            if !self.isCurrentUser {
                isShowIntroduce = !self.viewModel.nameCardInfo.bio.isEmpty
            }
            if isShowIntroduce {
                let model2 = YHUserNameCardInfo()
                model2.infoType = .introduce
                model2.isCurrentUser = self.isCurrentUser
                model2.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model2)
            }
           
            // 教育经历信息
            var isShowEducation = true
            if !self.isCurrentUser {
                let isFriend = self.viewModel.nameCardInfo.type == YHContactRelation.friend.rawValue
                isShowEducation = (isFriend && self.viewModel.nameCardInfo.authorization.friend_education_experience == 2) || (!isFriend && self.viewModel.nameCardInfo.authorization.public_education_experience == 2)
                
                if isShowEducation {
                    isShowEducation = (!self.viewModel.nameCardInfo.college.isEmpty || !self.viewModel.nameCardInfo.background.isEmpty || !self.viewModel.nameCardInfo.major.isEmpty)
                }
            }
            if isShowEducation {
                let model3 = YHUserNameCardInfo()
                model3.infoType = .education
                model3.isCurrentUser = self.isCurrentUser
                model3.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model3)
            }
            
            // 工作经历信息
            var isShowWorkExperience = true
            if !self.isCurrentUser {
                let isFriend = self.viewModel.nameCardInfo.type == YHContactRelation.friend.rawValue
                isShowWorkExperience = (isFriend && self.viewModel.nameCardInfo.authorization.friend_work_experience == 2) || (!isFriend && self.viewModel.nameCardInfo.authorization.public_work_experience == 2)
    
                if isShowWorkExperience {
                    isShowWorkExperience = (!self.viewModel.nameCardInfo.companyName.isEmpty || !self.viewModel.nameCardInfo.position.isEmpty || !self.viewModel.nameCardInfo.industry.isEmpty)
                }
            }
            if isShowWorkExperience {
                let model4 = YHUserNameCardInfo()
                model4.infoType = .workExperience
                model4.isCurrentUser = self.isCurrentUser
                model4.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model4)
            }
            
            // 荣誉奖项信息
            var isShowHonor = true
            if !self.isCurrentUser {
                isShowHonor = !self.viewModel.nameCardInfo.honor.isEmpty
            }
            if isShowHonor {
                let model5 = YHUserNameCardInfo()
                model5.infoType = .honor
                model5.isCurrentUser = self.isCurrentUser
                model5.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model5)
            }
            
            // 兴趣话题
            var isShowTopics = true
            if !self.isCurrentUser {
                isShowTopics = self.viewModel.nameCardInfo.topics.count > 0
            }
            if isShowTopics {
                let model6 = YHUserNameCardInfo()
                model6.infoType = .topics
                model6.isCurrentUser = self.isCurrentUser
                model6.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model6)
            }
            self.tableView.reloadData()
            self.noDataView.isHidden = self.cardInfoArr.count > 0
            
        }
    }
}

extension YHNameCardHomePageViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.cardInfoArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if 0 <= indexPath.section && indexPath.section < self.cardInfoArr.count {
            let cardInfo = self.cardInfoArr[indexPath.section]
            
            if cardInfo.infoType == .honor || cardInfo.infoType == .introduce {
                
                guard let introCell = tableView.dequeueReusableCell(withIdentifier: YHMyIntroductionCell.cellReuseIdentifier, for: indexPath) as? YHMyIntroductionCell else { return UITableViewCell() }
                introCell.userModel = cardInfo
                introCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    if cardInfo.infoType == .honor {
                        let vc = YHEditHonorViewController()
                        vc.model = self.viewModel.nameCardInfo
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    } else if cardInfo.infoType == .introduce {
                        let vc = YHEditPersonalProfileViewController()
                        vc.model = self.viewModel.nameCardInfo
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                }
                return introCell
            }
            
            if cardInfo.infoType == .education {
                guard let eduCell = tableView.dequeueReusableCell(withIdentifier: YHMyEducationCell.cellReuseIdentifier, for: indexPath) as? YHMyEducationCell else { return UITableViewCell() }
                eduCell.userModel = cardInfo
                eduCell.hiddenBtnBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    var targetText = ""
                    if self.viewModel.nameCardInfo.authorization.friend_education_experience != 2 && self.viewModel.nameCardInfo.authorization.public_education_experience != 2 {
                        targetText = "好友与陌生人"
                    } else if self.viewModel.nameCardInfo.authorization.friend_education_experience != 2 {
                        targetText = "好友"
                    } else if self.viewModel.nameCardInfo.authorization.public_education_experience != 2 {
                        targetText = "陌生人"
                    }
                    let tips = "该栏目已对" + targetText + "隐藏，若需重新开启，请前往信息授权处更新设置"
                    YHWholeScreenTipsView.show(message: tips, targetView: eduCell.hiddenBtn)
                }
                eduCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditSchoolViewController()
                    vc.model = self.viewModel.nameCardInfo
                    UIViewController.current?.navigationController?.pushViewController(vc)
                }
                return eduCell
            }
            
            if cardInfo.infoType == .workExperience {
                guard let workCell = tableView.dequeueReusableCell(withIdentifier: YHMyWorkExperienceCell.cellReuseIdentifier, for: indexPath) as? YHMyWorkExperienceCell else { return UITableViewCell() }
                workCell.userModel = cardInfo
                workCell.hiddenBtnBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    
                    var targetText = ""
                    if self.viewModel.nameCardInfo.authorization.friend_work_experience != 2 && self.viewModel.nameCardInfo.authorization.public_work_experience != 2 {
                        targetText = "好友与陌生人"
                    } else if self.viewModel.nameCardInfo.authorization.friend_work_experience != 2 {
                        targetText = "好友"
                    } else if self.viewModel.nameCardInfo.authorization.public_work_experience != 2 {
                        targetText = "陌生人"
                    }
                    let tips = "该栏目已对" + targetText + "隐藏，若需重新开启，请前往信息授权处更新设置"
                    YHWholeScreenTipsView.show(message: tips, targetView: workCell.hiddenBtn)
                }
                workCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditWorkViewController()
                    vc.model = self.viewModel.nameCardInfo
                    UIViewController.current?.navigationController?.pushViewController(vc)
                }
                return workCell
            }
            
            if cardInfo.infoType == .topics {
                guard let topicCell = tableView.dequeueReusableCell(withIdentifier: YHMyInterestTopicCell.cellReuseIdentifier, for: indexPath) as? YHMyInterestTopicCell else { return UITableViewCell() }
                topicCell.userModel = cardInfo
                topicCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditInterestViewController()
                    vc.model = self.viewModel.nameCardInfo
                    UIViewController.current?.navigationController?.pushViewController(vc)
                }
                return topicCell
            }
        }
        
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
}

extension YHNameCardHomePageViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

// **********************************************************************************

extension YHNameCardHomePageViewController: UIScrollViewDelegate {
    // 控制滑动交互
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollViewSet: CGFloat = scrollView.contentOffset.y
        if vcCanScroll == false {// 不能滚动时
            scrollView.contentOffset = CGPoint(x: 0, y: 0)
        } else {
            if scrollViewSet <= 0 {
                scrollView.contentOffset = CGPoint(x: 0, y: 0)
                vcCanScroll = false
                NotificationCenter.default.post(name: Notification.Name(rawValue: "leaveTop0"), object: nil)
            } else {
                scrollView.contentOffset = CGPoint(x: 0, y: scrollViewSet)
            }
        }
    }
}

extension YHNameCardHomePageViewController {
    @objc func beginDragging() {
        tableView.isScrollEnabled = false
        vcCanScroll = false
    }
    
    @objc func endDragging() {
        tableView.isScrollEnabled = true
    }
}
