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

import UIKit

class YHNameCardViewController: YHBaseViewController {

    var userId: String = ""
    var cardInfoArr: [YHUserNameCardInfo] = []
    let viewModel = YHMatchUserViewModel()
    let authorModel = YHInformationAuthorizeViewModel()
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 100
        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)
        tableView.contentInset = UIEdgeInsets(top: 41, left: 0, bottom: 0, right: 0)
        return tableView
    }()
    
    var isCurrentUser: Bool {
        get {
           return (!self.userId.isEmpty && self.userId == YHLoginManager.shared.userModel?.id)
        }
    }
    
    lazy var bgImgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "people_card_bg"))
        return view
    }()
    
    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .clear
        bar.title = self.isCurrentUser ? "我的名片" : "好友名片"
        bar.titleColor = .white
        bar.rightButton.setImage(UIImage(named: "people_card_authorized"), for: .normal)
        bar.rightButton.setTitle("授权", for: .normal)
        bar.rightButton.setTitleColor(UIColor.white, for: .normal)
        bar.rightButton.titleLabel?.font = UIFont.PFSC_R(ofSize: 15)
        bar.rightButton.snp.updateConstraints { make in
            make.width.equalTo(55)
            make.height.equalTo(44)
        }
        bar.backButton.setImage(UIImage(named: "back_icon_white"), for: .normal)
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        bar.rightBtnClick = {
            [weak self] in
            guard let self = self else { return }
            let vc = YHInformationAuthorizationStepTwoViewController()
            vc.stepFlag = false
            self.navigationController?.pushViewController(vc)
        }
        bar.rightButton.isHidden = !self.isCurrentUser
        return bar
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isCurrentUser {
            requestAuthorization()
        } else {
            requestNameCardInfo()
        }
    }
    
    func createUI() {
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = UIColor.init(hex: 0xF8FAFB)
        self.view.addSubview(bgImgView)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.navBar)
        self.navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_StatusBar)
            make.height.equalTo(k_Height_NavContentBar)
        }
        self.bgImgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(self.bgImgView.snp.width).multipliedBy(834.0/750.0)
        }
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(16+k_Height_NavigationtBarAndStatuBar)
        }
    }
}

extension YHNameCardViewController: 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.type == .avatar {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMyNameCardAvatarInfoCell.cellReuseIdentifier, for: indexPath) as? YHMyNameCardAvatarInfoCell else { return UITableViewCell() }
                cell.userModel = cardInfo
                cell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditBaseUserInfoViewController()
                    vc.model = self.viewModel.nameCardInfo
                    self.navigationController?.pushViewController(vc)
                }
                return cell
            }
            
            if cardInfo.type == .honor || cardInfo.type == .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.type == .honor {
                        let vc = YHEditHonorViewController()
                        vc.model = self.viewModel.nameCardInfo
                        self.navigationController?.pushViewController(vc)
                    } else if cardInfo.type == .introduce {
                        let vc = YHEditPersonalProfileViewController()
                        vc.model = self.viewModel.nameCardInfo
                        self.navigationController?.pushViewController(vc)
                    }
                }
                return introCell
            }
            
            if cardInfo.type == .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 }
                    YHWholeScreenTipsView.show(type: .nameCardEducation, targetView: eduCell.hiddenBtn)
                }
                eduCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditSchoolViewController()
                    vc.model = self.viewModel.nameCardInfo
                    self.navigationController?.pushViewController(vc)
                }
                return eduCell
            }
            
            if cardInfo.type == .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 }
                    YHWholeScreenTipsView.show(type: .nameCardWorkExperience, targetView: workCell.hiddenBtn)
                }
                workCell.editBlock = { [weak self] in
                    guard let self = self else { return }
                    let vc = YHEditWorkViewController()
                    vc.model = self.viewModel.nameCardInfo
                    self.navigationController?.pushViewController(vc)
                }
                return workCell
            }
            
            if cardInfo.type == .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
                    self.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 16.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 YHNameCardViewController {
    
    func requestAuthorization() {
        self.authorModel.requestUserAuthorization { _, _ in
            if self.authorModel.setModel.isclick_card != 2 && self.authorModel.setModel.information_to_card != 2 {
                YHCommonAlertView.show("", "授权信息同步至您的名片并对您的好友可见", "取消", "确认", fullGuestureEnable: false) {
                    self.authorModel.requestInformationToCardSubmit(agress: 1) { _, _ in
                        self.requestNameCardInfo()
                    }
                } callBack: {
                    self.authorModel.requestInformationToCardSubmit(agress: 2) { _, _ in
                        self.authorModel.requestBusinessCardAuthorize { _, _ in
                            self.requestNameCardInfo()
                        }
                    }
                }
            } else {
                self.requestNameCardInfo()
            }
        }
    }
    
    func requestNameCardInfo() {
        self.viewModel.getUserNameCardInfo(uid: self.userId) {
            _, _ in
            
            self.cardInfoArr.removeAll()
            
            // 姓名头像信息
            let model1 = YHUserNameCardInfo()
            model1.type = .avatar
            model1.isCurrentUser = self.isCurrentUser
            model1.updateModel(self.viewModel.nameCardInfo)
            self.cardInfoArr.append(model1)
            
            // 个人简介信息
            var isShowIntroduce = true
            if !self.isCurrentUser {
                isShowIntroduce = !self.viewModel.nameCardInfo.bio.isEmpty
            }
            if isShowIntroduce {
                let model2 = YHUserNameCardInfo()
                model2.type = .introduce
                model2.isCurrentUser = self.isCurrentUser
                model2.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model2)
            }
           
            // 教育经历信息
            var isShowEducation = true
            if !self.isCurrentUser {
                isShowEducation = !self.viewModel.nameCardInfo.isHiddenEducation
                if isShowEducation {
                    isShowEducation = (!self.viewModel.nameCardInfo.college.isEmpty || !self.viewModel.nameCardInfo.background.isEmpty || !self.viewModel.nameCardInfo.major.isEmpty)
                }
            }
            if isShowEducation {
                let model3 = YHUserNameCardInfo()
                model3.type = .education
                model3.isCurrentUser = self.isCurrentUser
                model3.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model3)
            }
            
            // 工作经历信息
            var isShowWorkExperience = true
            if !self.isCurrentUser {
                isShowWorkExperience = !self.viewModel.nameCardInfo.isHiddenWorkExperience
                if isShowWorkExperience {
                    isShowWorkExperience = (!self.viewModel.nameCardInfo.companyName.isEmpty || !self.viewModel.nameCardInfo.position.isEmpty || !self.viewModel.nameCardInfo.industry.isEmpty)
                }
            }
            if isShowWorkExperience {
                let model4 = YHUserNameCardInfo()
                model4.type = .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.type = .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.type = .topics
                model6.isCurrentUser = self.isCurrentUser
                model6.updateModel(self.viewModel.nameCardInfo)
                self.cardInfoArr.append(model6)
            }
            
            self.tableView.reloadData()
            
        }
    }
}
