//
//  YHMyNewViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/2/13.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SafariServices

enum YHPersonalModuleItemType: Int {
    case none = 0
    case myCard
    case myMessage
    case myProgress
    case myActivity
    case scoreCenter
    case inviteFriends
    case recommend
    case myPoster
    case myTestCode
    case appointGalaxyBay
    case exchangeHistory
    case myCourseVideo
    
    case notifySettings
    case permissionSettings
    case playSettings
    case infoCollectList
    case infoShareList
    case aboutUs
    case deviceInfo
    case version
    case userItems// 用户条款
    case privaceAgreement// 隐私协议
    case myOrder // 我的订单 双十一订单入口
    case mycart // 我的订单 双十一订单入口
    case serviceStep
    case myFriend
    case myEnterprise
    // case liveEntryTest //直播入口
}

class PersonalModuleItem {
    var icon: String?
    var title: String
    var desc: String
    var type: YHPersonalModuleItemType = .none
    var isShowRedPoint: Bool = false
    
    init(icon: String? = nil, title: String, desc: String = "", isShowRedPoint: Bool = false, type: YHPersonalModuleItemType) {
        self.icon = icon
        self.title = title
        self.desc = desc
        self.isShowRedPoint = isShowRedPoint
        self.type = type
    }
}

enum YHFunctionGroupType: Int {
    case none = 0
    case score = 1
    case orderAndService = 2
    case resource = 3
    case others = 4
}

class YHFunctionGroupInfo {
    var type: YHFunctionGroupType = .none
    var title: String = ""
    var arr: [PersonalModuleItem] = []
    init(type: YHFunctionGroupType, title: String, arr: [PersonalModuleItem]) {
        self.type = type
        self.title = title
        self.arr = arr
    }
}

class YHMyNewViewController: YHBaseViewController {
    
    let likeViewModel: YHMyLikeViewModel = YHMyLikeViewModel()
    let msgViewModel: YHMsgViewModel = YHMsgViewModel()
    let friendViewModel = YHMatchUserViewModel()
    let loginViewModel = YHLoginViewModel()
    let userViewModel = YHMatchUserViewModel()
    var functionGroupArr: [YHFunctionGroupInfo] = []
    var isShowVipMemberHeader: Bool = false
    var unreadFriendCount: Int = 0
    
    private lazy var princleVM: YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()
    
    private lazy var resourceViewModel: YHResourceViewModel = {
        return YHResourceViewModel()
    }()
    
    private lazy var messageHandler: YHIMMessageHandler = {
        return YHIMMessageHandler(
            viewController: self,
            navigationController: navigationController
        )
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(YHMySectionGroupCell.self, forCellReuseIdentifier: YHMySectionGroupCell.cellReuseIdentifier)
        tableView.register(YHMyFunctionGroup2Cell.self, forCellReuseIdentifier: YHMyFunctionGroup2Cell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = self.userInfoView
        return tableView
    }()
    
    func enterNewNameCard() {
        if let userId = YHLoginManager.shared.userModel?.id {
            let enterKey = "name_card_first_enter_"+userId
            if let hasEnter = UserDefaults.standard.object(forKey: enterKey) as? Bool, hasEnter == true {
                let vc = YHNewNameCardViewController()
                vc.userId = userId
                self.navigationController?.pushViewController(vc)
            } else {
                // 授权页面
                UserDefaults.standard.set(true, forKey: enterKey)
                UserDefaults.standard.synchronize()
                let vc = YHInformationAuthorizationStepOneViewController()
                self.navigationController?.pushViewController(vc)
            }
        }
    }
    
    lazy var userInfoView: YHMyUserInfoView = {
        let view = YHMyUserInfoView.createView()
        view.enterClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
//            enterUserInfoEditPage()
            enterNewNameCard()
        }
        
        view.avatarClickBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
        }
        
        view.nickNameClickBlock = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
        }
        
        view.likeClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 0
            self.navigationController?.pushViewController(vc)
        }
        
        view.collectClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 1
            self.navigationController?.pushViewController(vc)
            print("收藏")
        }
        
        view.recentScanClick = {
            [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }
            let vc = YHMyLikeActivityViewController()
            vc.myDefaultNavItemIndex = 2
            self.navigationController?.pushViewController(vc)
            print("最近浏览")
        }
        return view
    }()
    
    lazy var vipInfoView: YHUserVipInfoView = {
        let v = YHUserVipInfoView(frame: CGRect(x: 0, y: 0, width: tableView.width, height: 113))
        v.clickEvent = { [weak self] in
            guard let self = self else { return }
            if !checkLogin() { return }

            YHAnalytics.track("APP_member_card_click")
            let vc = YHMemberCenterViewController()
            self.navigationController?.pushViewController(vc)
        }
        return v
    }()
    
    private lazy var settingBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "mine_btn_setting"), for: .normal)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        btn.addTarget(self, action: #selector(didClickSettingBtn(btn:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var settingRedPointView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = kCornerRadius3
        view.backgroundColor = .failColor
        view.isHidden = true
        return view
    }()

    lazy var bgImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "mine_header_backImg"))
        return imgView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        view.backgroundColor = .init(UIColor(hex: 0xF9F9FB))
        view.addSubview(bgImgView)
        view.addSubview(tableView)
        view.addSubview(settingBtn)
        view.addSubview(settingRedPointView)

        bgImgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(bgImgView.snp.width)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalToSuperview().offset(k_Height_StatusBar+44)
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
        
        settingBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24.0)
            make.right.equalToSuperview().offset(-17)
            make.top.equalTo(k_Height_StatusBar+10)
        }
        
        settingRedPointView.snp.makeConstraints { make in
            make.width.height.equalTo(6)
            make.left.equalTo(settingBtn.snp.right).offset(-3)
            make.bottom.equalTo(settingBtn.snp.top).offset(3)
        }
        
        updateUserUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(clearUnreadBadge), name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didRevUatParam), name: YhConstant.YhNotification.didRevUatParam, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadItems()
        requestLikeCollectionCount()
        getTotalUnreadMsgCount()
        checkSettingRedPoint()
        userInfoView.updateAvatar()
        requstUserBasicInfo()
        requestMemberInfo()
        checkVipMemberShowLogic()
        requestFriendRequest()
        showAlert()
    }
    
    func checkLogin() -> Bool {
        if YHLoginManager.shared.isLogin() == false {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return false
        }
        return true
    }
    
    // uat 添加items
    func loadItems() {
        
        var scoreGroupArr: [PersonalModuleItem] = []
        var serviceGroupArr: [PersonalModuleItem] = []
        var resourcesArr: [PersonalModuleItem] = []
        var otherGroupArr: [PersonalModuleItem] = []
                
        // 我的名片
//        userInfoView.arrowImgView.isHidden = (YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_MyCard) != 1)
        
        // 邀请好友和积分商城
        
        do {
            let item = PersonalModuleItem(icon: "mine_item_invite", title: "邀请好友".local, desc: "推荐好友享好礼", type: .inviteFriends)
            scoreGroupArr.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_IntegralCenter) == 1 {
                let item = PersonalModuleItem(icon: "mine_item_score", title: "积分商城".local, desc: "超值商品随心换", type: .scoreCenter)
                scoreGroupArr.append(item)
            }
        }
        
        // 订单与服务
        
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_myOrder", title: "我的订单".local, type: .myOrder)
            serviceGroupArr.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_service_center", title: "服务进度".local, type: .serviceStep)
            serviceGroupArr.append(item)
        }
        
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            let item = PersonalModuleItem(icon: "mine_item_cart", title: "购物车".local, type: .mycart)
            serviceGroupArr.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_MyActivity) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_activity", title: "我的活动".local, type: .myActivity)
            serviceGroupArr.append(item)
        }
        
        if isShowVipMemberHeader {
            let item = PersonalModuleItem(icon: "mine_item_exchange_history", title: "兑换记录".local, type: .exchangeHistory)
            serviceGroupArr.append(item)
        }
        
        if self.loginViewModel.memberInfo.has_education_video_permission {
            let item = PersonalModuleItem(icon: "mine_item_video", title: "我的课程".local, type: .myCourseVideo)
            serviceGroupArr.append(item)
        }
        
        // 社区资源
        do {
            
            let item = PersonalModuleItem(icon: "mine_item_card", title: "我的名片".local, type: .myCard)
            resourcesArr.append(item)
            
            let item2 = PersonalModuleItem(icon: "mine_item_friend", title: "我的好友".local, type: .myFriend)
            resourcesArr.append(item2)
            
            let item3 = PersonalModuleItem(icon: "mine_item_enterprise", title: "我的企业".local, type: .myEnterprise)
            resourcesArr.append(item3)
            
        }
        
        // 其他功能
        do {
            let item = PersonalModuleItem(icon: "mine_item_msg", title: "我的消息".local, type: .myMessage)
            otherGroupArr.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_EvaluationCode) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_code", title: "测评码".local, type: .myTestCode)
            otherGroupArr.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_AboutYinHeHarbour) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_appoint", title: "体验中心".local, type: .appointGalaxyBay)
            otherGroupArr.append(item)
        }
        
        if YHUatHelper.shared.getUatModuleStatusBy(module: .Mine_AboutUS) == 1 {
            let item = PersonalModuleItem(icon: "mine_item_about_us", title: "关于我们".local, type: .aboutUs)
            otherGroupArr.append(item)
        }
        
        let scoreGroup = YHFunctionGroupInfo(type: .score, title: "", arr: scoreGroupArr)
        let serviceGroup = YHFunctionGroupInfo(type: .orderAndService, title: "订单与服务", arr: serviceGroupArr)
        let resourceGroup = YHFunctionGroupInfo(type: .orderAndService, title: "社区资源", arr: resourcesArr)
        let otherGroup = YHFunctionGroupInfo(type: .others, title: "其他功能", arr: otherGroupArr)

        functionGroupArr.removeAll()
        functionGroupArr.append(scoreGroup)
        functionGroupArr.append(serviceGroup)
        functionGroupArr.append(resourceGroup)
        functionGroupArr.append(otherGroup)
        tableView.reloadData()

    }
    
    @objc func didClickSettingBtn(btn: UIButton) {
        if !checkLogin() { return }
        let vc = YHMySettingViewController()
        self.navigationController?.pushViewController(vc)
                
//        let vc = YHH5WebViewVC()
//        vc.isFullScreenFlag = false
//        vc.url = "http://192.168.34.113:10301/superAppBridge.html#/order/antom-pay?id=1864&param=eyJhbGbolyFeciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTc0NzI5MzAsImkiOjQyMzgxNzEzODcwNzAyMSwidSI6IumTtuays-mbhuWboiIsInIiOiJzdXBlcl9hcHAifQ.Phsg13OfN5XJ0cLe759U2W0hH1iTZeneimgTlnouPcg"
//        self.navigationController?.pushViewController(vc)
    }
}

extension YHMyNewViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return functionGroupArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMySectionGroupCell.cellReuseIdentifier, for: indexPath) as? YHMySectionGroupCell else { return UITableViewCell() }
        if 0 <= indexPath.row, indexPath.row < functionGroupArr.count {
            let group: YHFunctionGroupInfo = functionGroupArr[indexPath.row]
            if group.type == .score {
                guard let cell2 = tableView.dequeueReusableCell(withIdentifier: YHMyFunctionGroup2Cell.cellReuseIdentifier, for: indexPath) as? YHMyFunctionGroup2Cell else { return UITableViewCell() }
                cell2.updateGroup(group)
                cell2.clickItem = {
                    [weak self] item in
                    guard let self = self else { return }
                    self.clickItem(item)
                }
                return cell2
            }
            cell.clickItem = {
                [weak self] item in
                guard let self = self else { return }
                self.clickItem(item)
            }
            cell.updateGroup(group)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        
        return isShowVipMemberHeader ? 113.0 : 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if isShowVipMemberHeader {
            return self.vipInfoView
        }
        return UIView()
    }
}

extension YHMyNewViewController {
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        updateUserUI()
    }
    
    @objc func logoutSuccess() {
        updateUserUI()
    }
    
    func updateUserUI() {
        if YHLoginManager.shared.isLogin() {
            let name = self.userViewModel.nameCardInfo.username
            if name.isEmpty {
                userInfoView.userNameLabel.text = "Hi, 银河用户".local
            } else {
                userInfoView.userNameLabel.text = "Hi, \(name)"
            }
            
        } else {
            userInfoView.userNameLabel.text =  "登录/注册"
            userInfoView.vipLevel = .none
        }
        userInfoView.updateAvatar()
        requestLikeCollectionCount()
        getTotalUnreadMsgCount()
        checkSettingRedPoint()
        requstUserBasicInfo()
        requestMemberInfo()
        requestFriendRequest()
    }
    
    func requstUserBasicInfo() {
        if YHLoginManager.shared.isLogin() {
            if isEmptyString(YHLoginManager.shared.userModel?.id) {
                self.loginViewModel.getUserId {
                    [weak self] _ in
                    guard let self = self else { return }
                    requestUserInfo()
                }
            } else {
                requestUserInfo()
            }

        } else {
            userInfoView.updateAvatar()
        }
    }
    
    func requestMemberInfo() {
        if YHLoginManager.shared.isLogin() {
            self.loginViewModel.getMemberInfo {
                [weak self] _, _ in
                guard let self = self else { return }
                let memberInfo = self.loginViewModel.memberInfo
                self.userInfoView.vipLevel = memberInfo.getVipMemberLevel()
                self.vipInfoView.update(growValue: memberInfo.growth_value, vipLevel: memberInfo.getVipMemberLevel())
                self.loadItems()
                
            }
        } else {
            self.userInfoView.vipLevel = .none
            self.vipInfoView.update(growValue: 0, vipLevel: .none)
        }
    }
    
    func requestUserInfo() {
        if let uid = YHLoginManager.shared.userModel?.id, !uid.isEmpty {
            self.userViewModel.getUserNameCardInfo(uid: uid) {
                [weak self] _, _ in
                guard let self = self else { return }
                let url = URL(string: self.userViewModel.nameCardInfo.avatar)
                self.userInfoView.avarImgView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
                if YHLoginManager.shared.isLogin() {
                    let name = self.userViewModel.nameCardInfo.username
                    if name.isEmpty {
                        userInfoView.userNameLabel.text = "Hi, 银河用户".local
                    } else {
                        userInfoView.userNameLabel.text = "Hi, \(name)"
                    }
                    
                } else {
                    userInfoView.userNameLabel.text =  "登录/注册"
                    userInfoView.vipLevel = .none
                }
            }
        }
    }
    
    func requestLikeCollectionCount() {
        self.likeViewModel.getLikeCollectionRecentScanCountInfo {
            [weak self] _, _ in
            guard let self = self else { return }
            self.userInfoView.updateLikeCollectCount(self.likeViewModel.likeCollectCountInfo)
        }
    }
    
    func requestFriendRequest() {
        if YHLoginManager.shared.isLogin() {
            self.friendViewModel.getMyFriendList { _, _ in
                self.unreadFriendCount =  self.friendViewModel.friendListModel.applyFriends.count
                for group in self.functionGroupArr {
                    for item in group.arr {
                        if item.type == .myFriend {
                            item.isShowRedPoint = self.unreadFriendCount > 0
                            break
                        }
                    }
                }
                self.tableView .reloadData()
            }
        } else {
            self.unreadFriendCount = 0
            for group in self.functionGroupArr {
                for item in group.arr {
                    if item.type == .myFriend {
                        item.isShowRedPoint = self.unreadFriendCount > 0
                        break
                    }
                }
            }
            self.tableView .reloadData()
        }
    }
    
    // 请求未读消息总数
    func getTotalUnreadMsgCount() {
        if YHLoginManager.shared.isLogin() {
            self.msgViewModel.requestTotalUnreadMsgCount {
                [weak self] _, _ in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    var unreadCount = self.msgViewModel.unreadTotalCount
                    if YHButlerServiceManager.shared.isUatAllowed() {
                        unreadCount = self.msgViewModel.unreadTotalCount + YHButlerServiceManager.shared.unreadCount
                    }
                    for group in self.functionGroupArr {
                        for item in group.arr {
                            if item.type == .myMessage {
                                item.isShowRedPoint = unreadCount > 0
                                break
                            }
                        }
                    }
                    self.tableView .reloadData()
                }
            }
        }
    }
    
    @objc func didRevUatParam() {
        loadItems()
        checkVipMemberShowLogic()
    }
    
    @objc func clearUnreadBadge() {
        DispatchQueue.main.async {
            for group in self.functionGroupArr {
                for item in group.arr {
                    if item.type == .myMessage {
                        item.isShowRedPoint = false
                        break
                    }
                }
            }
            self.tableView .reloadData()
        }
    }
    
    func checkSettingRedPoint() {
        if YHConfigManager.shared.loadNewDataFlag == false {
            YHConfigManager.shared.loadConfigData {
                [weak self] in
                guard let self = self else { return }
                self.settingRedPointView.isHidden = !YHAppVersionManager.shared.needShowRedPointOfSuggestVersionUpdate()
            }
        } else {
            self.settingRedPointView.isHidden = !YHAppVersionManager.shared.needShowRedPointOfSuggestVersionUpdate()
        }
    }
    
    func checkVipMemberShowLogic() {
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            self.isShowVipMemberHeader = true
        } else {
            self.isShowVipMemberHeader = false
        }
        self.loadItems()
        self.tableView.reloadData()
    }
    
    private func showAlert() {
        guard YHLoginManager.shared.isLogin() else {
            return
        }
        princleVM.getPrincleStatus { [weak self] success, _ in
            if success {
                guard let self = self else {
                    return
                }
                guard let model = self.princleVM.alertStatusModel else {
                    return
                }
                
                if model.type == 20 {
                    self.showYHManagerGuideView(self.navigationController)
                }
            }
        }
    }
    
}

extension YHMyNewViewController {
    // MARK: - 跳银河管家
    
    private func showYHManagerGuideView(_ navigationController: UINavigationController?) {
        if YHUatHelper.shared.getUatModuleStatusBy(module: .QiYu_Service) != 1 {
            printLog("非目标用户")
            return
        }
        if let key = YHButlerServiceManager.shared.guideWindowShowedKey, YHButlerServiceManager.shared.didShowWindowDict[key] == true {
            return
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
            if let key = YHButlerServiceManager.shared.guideWindowShowedKey {
                YHButlerServiceManager.shared.didShowWindowDict[key] = true
            }
            let view = YHConversationGuideView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
            view.checkButtonEvent = { [weak self] in
                guard let self = self else {
                    return
                }
                self.princleVM.postAlertStatus(20) { _, _ in
                }
                self.gotoYinHeManager(navigationController)
            }
            view.show()
        }
    }
    
    private func gotoYinHeManager(_ navigationController: UINavigationController?) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            return
        }
        // YHAnalytics.track("APP_HomeTab_IntelligentAssistant")
        YHHUD.show(.progress(message: "加载中..."))
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { _ in
            YHHUD.hide()
        })
    }
}

extension YHMyNewViewController {
    
    func enterUserInfoEditPage() {
        let vc = YHEditBaseUserInfoViewController()
        vc.model = self.userViewModel.nameCardInfo
        self.navigationController?.pushViewController(vc)
        
    }
    
    func inviteFriends() {
            // 判断是否登录成功
            if YHLoginManager.shared.isLogin() {
                let vc = YHInvitationWithGiftsViewController()
                self.navigationController?.pushViewController(vc)
                
            } else {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                YHLoginManager.shared.loginSuccessActionBlock = {[weak self] in
                    guard self != nil else { return }
                    let vc = YHInvitationWithGiftsViewController()
                    self?.navigationController?.pushViewController(vc)
                    YHLoginManager.shared.loginSuccessActionBlock = nil
                }
            }
        }
    
    func clickItem(_ item: PersonalModuleItem) {
        if !checkLogin() {
            return
        }

        switch item.type {
        case .myCard:// 我的名片
            enterNewNameCard()
        case .myMessage:// 我的消息
            printLog("我的消息")
            goToMessagePage()
            
        case .scoreCenter://// 积分中心
            printLog("积分中心")
            if let param = YHLoginManager.shared.userModel?.token, param.count>5 {
                printLog(param)
                var url = YHBaseUrlManager.shared.curH5URL() + "superApp/integral"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                
                let vc = YHH5WebViewVC()
                vc.title = "积分中心"
                vc.navTitle = "积分中心"
                vc.url = url
                vc.isFullScreenFlag = true
                vc.isSupportWebviewInterBackFlag = true
                self.navigationController?.pushViewController(vc)
            }
        case .myTestCode:// 我的测评码
            printLog("我的测评码")
            let vc = YHHomeWebViewController()
            vc.title = "香港身份测评码"
            vc.vcTitle = "香港身份测评码"
            vc.showSavePicBottomFlag = true
            vc.url = "https://cdn-public.galaxy-immi.com/app/cepingma.png"
            self.navigationController?.pushViewController(vc)
        case .appointGalaxyBay:// 预约银河湾
            printLog("预约银河湾")
            let vc = YHListViewController()
            self.navigationController?.pushViewController(vc)
        case .myActivity:
            printLog("我的活动")
            let vc = YHActivityListViewController()
            vc.type = 1
            self.navigationController?.pushViewController(vc)
        case .exchangeHistory:
            YHMemberCenterViewController.goExchangeHistory()
        case .aboutUs:
            let vc = YHAboutGalaxyViewController()
            self.navigationController?.pushViewController(vc)
        case .myOrder:
//            我的订单
            if let token = YHLoginManager.shared.userModel?.token, token.count > 5 {
                var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/order/my"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                printLog("URL: \(url)")
                let vc = YHH5WebViewVC()
                vc.url = url
                vc.isFullScreenFlag = false
                vc.navTitle = "我的订单"
                vc.isSupportWebviewInterBackFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        case .mycart:
//            我的订单
            if let token = YHLoginManager.shared.userModel?.token, token.count > 5 {
                var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/cart"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                printLog("URL: \(url)")
                var tUrl = url
                if !url.contains("navigationH=") {
                    tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    if url.contains("?") {
                        tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    }
                }
                let vc = YHH5WebViewVC()
                vc.url = tUrl
                vc.isFullScreenFlag = false
                vc.navTitle = "购物车"
                vc.isSupportWebviewInterBackFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        case .serviceStep:
            UIViewController.current?.tabBarController?.selectedIndex = 1
        case .inviteFriends:
            inviteFriends()
        case .myCourseVideo:
            if let token = YHLoginManager.shared.userModel?.token, token.count > 5 {
                var url = YHBaseUrlManager.shared.supportH5URL() + "articleDetail.html#/video-list"
                url = url + "?param=" + YHLoginManager.shared.h5Token
                printLog("URL: \(url)")
                var tUrl = url
                if !url.contains("navigationH=") {
                    tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    if url.contains("?") {
                        tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                    }
                }
                if !url.contains("statusBarH=") {
                    tUrl = url + "?statusBarH=\(k_Height_StatusBar)"
                    if url.contains("?") {
                        tUrl = url + "&statusBarH=\(k_Height_StatusBar)"
                    }
                }
                let vc = YHH5WebViewVC()
                vc.url = tUrl
                vc.isFullScreenFlag = true
//                vc.navTitle = "我的课程"
                vc.isSupportWebviewInterBackFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
                
            }
        case .myFriend:
            let vc = YHMyGoodFriendsVC()
            self.navigationController?.pushViewController(vc)
        case .myEnterprise:
            YHHUD.show(.progress(message: ""))
            resourceViewModel.getMyCompanyDetail { [weak self] resourceDetailModel, errorModel in
                guard let self = self else {
                    return
                }
                YHHUD.hide()
                guard let resourceDetailModel = resourceDetailModel else {
                    if let errorModel = errorModel, errorModel.errorCode == 10005 {
                        self.showContactManagerDialog()
                    } else {
                        YHHUD.flash(message: errorModel?.errorMsg ?? "请稍候")
                    }
                    return
                }
                self.gotoMyCompany(resourceDetailModel)
            }
        default:
            printLog("不需要响应")
        }
    }
    
    private func gotoMyCompany(_ detailModel: YHResourceDetailModel) {
        // 跳转到详情页
        let vc = YHResourceDetailViewController()
        vc.isMyCompany = true
        vc.detailModel = detailModel
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func showContactManagerDialog() {
        YHGrayCommonAlertView.show("暂未绑定企业", "请您联系银河管家进行企业绑定，快来与我们联系吧~", "返回", "去联系", fullGuestureEnable: false) {
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: ""))
            self.resourceViewModel.getDemandYhId { [weak self] id in
                guard let self = self else {
                    return
                }
                YHHUD.hide()
                if id.isEmpty {
                    YHHUD.flash(message: "获取银河ID失败")
                    return
                }
                self.messageHandler.gotoChatVC(senderID: id)
            }
        }
    }
}
