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

import UIKit

class YHMemberCenterViewController: YHBaseViewController, UIGestureRecognizerDelegate {
    enum TableRow {
        case currentPrivilege(_ curLevel: YHMembershipLevel, _ count: Int, _ isOverLevel: Bool, _ myLevel: YHMembershipLevel)
        case myPrivilege(_ myLevel: YHMembershipLevel, _ count: Int, _ redeemCount: Int, _ redeemedCount: Int, _ needShowBottom: Bool)
        case action(_ title: String, _ detail: String, _ imageStr: String, _ ratio: CGFloat, _ buttonStr: String, _ buttonState: YHMemberCenterActionButton.ButtonState, _ id: String, _ contentType: YHMemberCenterCellContent)
    }

    private var currentLevel: YHMembershipLevel? // = .normal

    private var viewModel = YHMemberCenterViewModel()

    private var firstEnter = true

    var datas: [TableRow] = []

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight), style: .grouped)
        view.estimatedSectionHeaderHeight = 0.01
        view.estimatedSectionFooterHeight = 16
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHMemberCenterCurrentPrivilegeCell.self, forCellReuseIdentifier: YHMemberCenterCurrentPrivilegeCell.cellReuseIdentifier)
        view.register(YHMemberCenterMyPrivilegeCell.self, forCellReuseIdentifier: YHMemberCenterMyPrivilegeCell.cellReuseIdentifier)
        view.register(YHMemberCenterActionCell.self, forCellReuseIdentifier: YHMemberCenterActionCell.cellReuseIdentifier)
        return view
    }()

    private lazy var bgIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "member_center_bg_normal")
        return view
    }()

    private lazy var headerView: YHMemberCenterHeaderView = {
        let view = YHMemberCenterHeaderView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: YHMemberCenterHeaderView.viewHeight))
        view.scrollToIndexEvent = { [weak self] level in
            guard let self = self else {
                return
            }
            switchCard(level)
        }
        view.levelButtonEvent = { [weak self] _ in
            self?.gotoGuideView()
        }
        view.upgradeButtonEvent = { [weak self] level in
            guard let self = self else {
                return
            }
            if let memberCenterInfo = self.viewModel.memberCenterInfo, level.rawValue > memberCenterInfo.currentLevel {
                self.gotoYinheStore()
            }
        }
        return view
    }()

    private lazy var footerView: YHMemberCenterFooterView = {
        let view = YHMemberCenterFooterView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: YHMemberCenterFooterView.viewHeight))
        return view
    }()
    
    private func switchCard(_ level: YHMembershipLevel) {
        bgIcon.image = UIImage(named: level.bgIconTitle())
        if let currentLevel = currentLevel {
            YHAnalytics.timeEnd(currentLevel.logKey)
        }
        currentLevel = level
        YHAnalytics.timeStrat(level.logKey)
        if let info = viewModel.memberCenterInfo {
            updateDatas(info)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let isFirstPage = headerView.bannerView.scrollOffset <= 0
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = isFirstPage
        if firstEnter {
            firstEnter = false
            requestData(isNeedLoading: true)
        } else {
            requestData(isNeedLoading: false)
            if let currentLevel = currentLevel {
                YHAnalytics.timeStrat(currentLevel.logKey)
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        if let currentLevel = currentLevel {
            YHAnalytics.timeEnd(currentLevel.logKey)
        }
    }
    
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == navigationController?.interactivePopGestureRecognizer {
            return headerView.bannerView.scrollOffset <= 0
        }
        return true
    }

    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navBackgroundColor = .clear
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(bgIcon)
        view.addSubview(tableView)

        // 兑换记录
        let historyItem = UIBarButtonItem(title: "兑换记录", style: .plain, target: self, action: #selector(didHistoryButtonClicked))
        historyItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.mainTextColor, NSAttributedString.Key.font: UIFont.PFSC_R(ofSize: 14)], for: .normal)
        // 分享
        let shareItem = UIBarButtonItem.gk_item(image: UIImage(named: "share_item"), target: self, action: #selector(didShareButtonClicked))

        gk_navigationItem.rightBarButtonItems = [shareItem, historyItem]

        let ratio = 375.0 / 375.0
        bgIcon.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(bgIcon.snp.width).multipliedBy(ratio)
        }

        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview()
        }
        tableView.tableHeaderView = headerView
        tableView.tableFooterView = footerView
    }

    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getMemberInfo { [weak self] success, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            if success, let memberCenterInfo = viewModel.memberCenterInfo {
                self.headerView.updateDatas(memberCenterInfo)
                if isNeedLoading, let index = YHMembershipLevel.allCases.firstIndex(where: { data in
                    data.rawValue == memberCenterInfo.currentLevel
                }) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
                        self.headerView.bannerView.scrollToItem(at: index, animated: false)
                        self.switchCard(YHMembershipLevel.allCases[index])
                    }
                } else {
                    self.updateDatas(memberCenterInfo)
                }
            } else {
                var errorMsg = "获取会员信息失败，请重试！"
                if let error = error, error.errorMsg.count > 0 {
                    errorMsg = error.errorMsg
                }
                YHHUD.flash(message: errorMsg)
                self.navigationController?.popViewController(animated: true)
            }
        }
    }

    private func updateDatas(_ memberCenterInfo: YHMemberCenterInfo) {
        datas.removeAll()
        var details: [String] = []
        var buttonTitles: [String] = []
        var buttonStates: [YHMemberCenterActionButton.ButtonState] = []
        func appendMenu(_ giftModel: YHMemberGiftModel) {
            if memberCenterInfo.currentLevel < giftModel.minLevel {
                let minLevel = YHMembershipLevel(rawValue: giftModel.minLevel) ?? .normal
                details.append("可供兑换剩余库存：\(giftModel.num)")
                buttonTitles.append("\(minLevel.description)可兑")
                buttonStates.append(.memberOnly)
            } else if giftModel.num <= 0 {
                details.append("本月已无库存，次月更新")
                buttonTitles.append("暂无库存")
                buttonStates.append(.outOfStock)
            } else {
                details.append("可供兑换剩余库存：\(giftModel.num)")
                buttonTitles.append("了解更多")
                buttonStates.append(.redeemable)
            }
        }
        let myLevel = YHMembershipLevel(rawValue: memberCenterInfo.currentLevel) ?? .normal
        guard let currentLevel = currentLevel else {
            return
        }
        switch currentLevel {
        case .normal:
            datas.append(.myPrivilege(myLevel, myLevel.privilegeCount, memberCenterInfo.exchangeCount, memberCenterInfo.exchangedCount, memberCenterInfo.currentLevel > YHMembershipLevel.normal.rawValue))
            let services: [YHMemberCenterCellContent] = [.customerService, .pointsConsumption, .afternoonTea, .offlineSalons, .onSiteConsultation]
            let ids: [String] = [memberCenterInfo.dedicatedAdviser.giftId, memberCenterInfo.specialIntegralConsumption.giftId, memberCenterInfo.luxuryTea.giftId, memberCenterInfo.offlineSalon.giftId, memberCenterInfo.answerConsult.giftId]
            details = ["", "", "", "", ""]
            buttonTitles = ["立即联系", "了解更多", "立即兑换", "了解更多", "了解更多"]
            buttonStates = [.redeemable, .redeemable, .redeemable, .redeemable, .redeemable]
            services.enumerated().forEach { index, service in
                let row: TableRow = .action(service.rawValue, details[index], service.imageUrl(), service.imageRatio(), buttonTitles[index], buttonStates[index], ids[index], service)
                datas.append(row)
            }
        case .gold:
            if memberCenterInfo.currentLevel < currentLevel.rawValue {
                datas.append(.currentPrivilege(currentLevel, currentLevel.privilegeCount, memberCenterInfo.currentLevel >= currentLevel.rawValue, myLevel))
            }
            
            datas.append(.myPrivilege(myLevel, myLevel.privilegeCount, memberCenterInfo.exchangeCount, memberCenterInfo.exchangedCount, memberCenterInfo.currentLevel > YHMembershipLevel.normal.rawValue))
            let services: [YHMemberCenterCellContent] = [.kidsBay, .luxury, .afternoonTea, .offlineSalons, .onSiteConsultation, .customerService, .pointsConsumption]
            let ids: [String] = [memberCenterInfo.highTeaBox.giftId, memberCenterInfo.experienceCenter.giftId,
                                 memberCenterInfo.luxuryTea.giftId,
                                 memberCenterInfo.offlineSalon.giftId, memberCenterInfo.answerConsult.giftId, memberCenterInfo.dedicatedAdviser.giftId,
                                 memberCenterInfo.specialIntegralConsumption.giftId]
            appendMenu(memberCenterInfo.highTeaBox)
            appendMenu(memberCenterInfo.experienceCenter)
            
            details.append(contentsOf: ["", "", "", "", ""])
            buttonTitles.append(contentsOf: ["立即兑换", "了解更多", "了解更多", "立即联系", "了解更多"])
            buttonStates.append(contentsOf: [.redeemable, .redeemable, .redeemable, .redeemable, .redeemable])
            
            services.enumerated().forEach { index, service in
                let row: TableRow = .action(service.rawValue, details[index], service.imageUrl(), service.imageRatio(), buttonTitles[index], buttonStates[index], ids[index], service)
                datas.append(row)
            }
        case .platinum:
            if memberCenterInfo.currentLevel < currentLevel.rawValue {
                datas.append(.currentPrivilege(currentLevel, currentLevel.privilegeCount, memberCenterInfo.currentLevel >= currentLevel.rawValue, myLevel))
            }
            
            datas.append(.myPrivilege(myLevel, myLevel.privilegeCount, memberCenterInfo.exchangeCount, memberCenterInfo.exchangedCount, memberCenterInfo.currentLevel > YHMembershipLevel.normal.rawValue))
            let services: [YHMemberCenterCellContent] = [.crossBorder, .kidsBay, .luxury, .afternoonTea, .offlineSalons, .onSiteConsultation, .customerService, .pointsConsumption]
            let ids: [String] = [memberCenterInfo.carTransfer.giftId,
                                 memberCenterInfo.highTeaBox.giftId, memberCenterInfo.experienceCenter.giftId,
                                 memberCenterInfo.luxuryTea.giftId,
                                 memberCenterInfo.offlineSalon.giftId, memberCenterInfo.answerConsult.giftId, memberCenterInfo.dedicatedAdviser.giftId,
                                 memberCenterInfo.specialIntegralConsumption.giftId]
            appendMenu(memberCenterInfo.carTransfer)
            appendMenu(memberCenterInfo.highTeaBox)
            appendMenu(memberCenterInfo.experienceCenter)
            
            details.append(contentsOf: ["", "", "", "", ""])
            buttonTitles.append(contentsOf: ["立即兑换", "了解更多", "了解更多", "立即联系", "了解更多"])
            buttonStates.append(contentsOf: [.redeemable, .redeemable, .redeemable, .redeemable, .redeemable])

            services.enumerated().forEach { index, service in
                let row: TableRow = .action(service.rawValue, details[index], service.imageUrl(), service.imageRatio(), buttonTitles[index], buttonStates[index], ids[index], service)
                datas.append(row)
            }
        case .diamond:
            if memberCenterInfo.currentLevel < currentLevel.rawValue {
                datas.append(.currentPrivilege(currentLevel, currentLevel.privilegeCount, memberCenterInfo.currentLevel >= currentLevel.rawValue, myLevel))
            }
            
            datas.append(.myPrivilege(myLevel, myLevel.privilegeCount, memberCenterInfo.exchangeCount, memberCenterInfo.exchangedCount, memberCenterInfo.currentLevel > YHMembershipLevel.normal.rawValue))
            let services: [YHMemberCenterCellContent] = [.highEndMeeting, .crossBorder, .hkTravel, .drivingLicense, .schoolSelection, .brandPlanning, .kidsBay, .luxury, .afternoonTea, .offlineSalons, .onSiteConsultation, .customerService, .pointsConsumption]
            let ids: [String] = [memberCenterInfo.highEndPrivilege.giftId,
                                 memberCenterInfo.carTransfer.giftId,
                                 memberCenterInfo.hkCarTransfer.giftId,
                                 memberCenterInfo.internationalDrivingLicense.giftId,
                                 memberCenterInfo.hongkongSchoolPlanning.giftId,
                                 memberCenterInfo.brandStrategy.giftId,
                                 memberCenterInfo.highTeaBox.giftId,
                                 memberCenterInfo.experienceCenter.giftId,
                                 memberCenterInfo.luxuryTea.giftId,
                                 memberCenterInfo.offlineSalon.giftId, memberCenterInfo.answerConsult.giftId, memberCenterInfo.dedicatedAdviser.giftId,
                                 memberCenterInfo.specialIntegralConsumption.giftId]
            appendMenu(memberCenterInfo.highEndPrivilege)
            appendMenu(memberCenterInfo.carTransfer)
            appendMenu(memberCenterInfo.hkCarTransfer)
            appendMenu(memberCenterInfo.internationalDrivingLicense)
            appendMenu(memberCenterInfo.hongkongSchoolPlanning)
            appendMenu(memberCenterInfo.brandStrategy)
            appendMenu(memberCenterInfo.highTeaBox)
            appendMenu(memberCenterInfo.experienceCenter)
            
            details.append(contentsOf: ["", "", "", "", ""])
            buttonTitles.append(contentsOf: ["立即兑换", "了解更多", "了解更多", "立即联系", "了解更多"])
            buttonStates.append(contentsOf: [.redeemable, .redeemable, .redeemable, .redeemable, .redeemable])
            services.enumerated().forEach { index, service in
                let row: TableRow = .action(service.rawValue, details[index], service.imageUrl(), service.imageRatio(), buttonTitles[index], buttonStates[index], ids[index], service)
                datas.append(row)
            }
        }
        tableView.reloadData()
    }

    @objc private func didHistoryButtonClicked() {
        Self.goExchangeHistory()
    }
    
    static func goExchangeHistory() {
        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/vip/order"
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        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
        UIViewController.current?.navigationController?.pushViewController(vc)
    }

    @objc private func didShareButtonClicked() {
        YHAnalytics.track("Membership_Privileges_Page_Share")
        let url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/vip/center"
        YHShareManager.shared.sendLinkContent("银河会员等级", "查看特色福利，享会员特权", UIImage(named: "member_share_icon") ?? UIImage(), link: url)
    }

    private func gotoYinheStore() {
        let vc = YHSelectViewController()
        vc.hideFlag = false
        navigationController?.pushViewController(vc)
    }

    private func serviceDidClick(id: String, contentType: YHMemberCenterCellContent) {
        switch contentType {
        case .kidsBay:
            YHAnalytics.track("Membership_Privileges_Page_KidsbayBox")
            gotoService(id)
        case .luxury:
            YHAnalytics.track("Membership_Privileges_Page_ExperienceCenter")
            gotoService(id)
        case .crossBorder:
            YHAnalytics.track("Membership_Privileges_Page_ChinaHongKongCar")
            gotoService(id)
        case .hkTravel:
            YHAnalytics.track("Membership_Privileges_Page_HongKongCar")
            gotoService(id)
        case .drivingLicense:
            YHAnalytics.track("Membership_Privileges_Page_InternationalDriving")
            gotoService(id)
        case .schoolSelection:
            YHAnalytics.track("Membership_Privileges_Page_HongKongSchoolPlanning")
            gotoService(id)
        case .brandPlanning:
            YHAnalytics.track("Membership_Privileges_Page_Brand_Planning_Proposal")
            gotoService(id)
        case .highEndMeeting:
            YHAnalytics.track("Membership_Privileges_Page_Private_DirectorsClub")
            gotoService(id)
        case .afternoonTea:
            YHAnalytics.track("Membership_Privileges_Page_Exquisite_Afternoontea")
            gotoService(id)
        case .onSiteConsultation:
            YHAnalytics.track("Membership_Privileges_Page_OnsiteConsultation")
            gotoService(id)
        case .offlineSalons:
            YHAnalytics.track("Membership_Privileges_Page_OfflineSalon")
            gotoService(id)
            // gotoCommunity()
        case .customerService:
            YHAnalytics.track("Membership_Privileges_Page_Exclusive_Advisor")
            goQiyuService()
        case .pointsConsumption:
            YHAnalytics.track("Membership_Privileges_Page_Exclusive_ConsumptionPoints")
            gotoScoreCenter()
        }
    }

//    private func gotoCommunity() {
//        goTabBarBy(tabType: .community)
//        DispatchQueue.main.async {
//            NotificationCenter.default.post(name: YhConstant.YhNotification.goActivityVCNotifiction, object: nil)
//        }
//    }
    
    private func gotoGuideView() {
        let view = YHMembershipGrowthGuideView.sheetView()
        view.closeButtonEvent = {
            
        }
        view.show()
    }
    
    private func gotoScoreCenter() {
        if let param = YHLoginManager.shared.userModel?.token, param.count > 5 {
            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
            navigationController?.pushViewController(vc)
        }
    }

    private func gotoService(_ id: String) {
        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/vip/detail?exchange_support_type=2&source=vip&id=\(id)"
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        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 = true
        navigationController?.pushViewController(vc)
    }

    private func goQiyuService() {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0, let navigationController = UIViewController.current?.navigationController else {
            return
        }
        YHHUD.show(.progress(message: "加载中..."))
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { _ in
            YHHUD.hide()
        })
    }

    private func gotoPrivilegePage(_ level: YHMembershipLevel) {
        let vc = YHVipLevelRightViewController()
        vc.level = level
        navigationController?.pushViewController(vc)
    }
}

extension YHMemberCenterViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if datas.count > section {
            return 1
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let section = datas[indexPath.section]
        switch section {
        case let .currentPrivilege(level, count, isOverLevel, _):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHMemberCenterCurrentPrivilegeCell.cellReuseIdentifier) as? YHMemberCenterCurrentPrivilegeCell {
                cell.setupCell(mid: "\(level.description)拥有特权\(count)项", isOverLevel: isOverLevel)
                return cell
            }
        case let .myPrivilege(level, count, redeemCount, redeemedCount, isShowBottom):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHMemberCenterMyPrivilegeCell.cellReuseIdentifier) as? YHMemberCenterMyPrivilegeCell {
                cell.setupCell(mid: "我的\(level.description)特权", right: "\(count)项", redeemCount: redeemCount, redeemedCount: redeemedCount, needShowBottom: isShowBottom)
                return cell
            }
        case let .action(title, detail, imageStr, ratio, buttonStr, buttonState, id, service):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHMemberCenterActionCell.cellReuseIdentifier) as? YHMemberCenterActionCell {
                cell.setupCell(title: title, detail: detail, imgStr: imageStr, imageRatio: ratio, buttonStr: buttonStr, buttonState: buttonState)
                cell.actionButtonEvent = { [weak self] in
                    self?.serviceDidClick(id: id, contentType: service)
                }
                return cell
            }
        }
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard datas.count > indexPath.section else {
            return 0
        }
        let section = datas[indexPath.section]
        switch section {
        case .currentPrivilege:
            return 74.0
        case .myPrivilege, .action:
            return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard datas.count > indexPath.section else {
            return
        }
        let section = datas[indexPath.section]
        switch section {
        case let .currentPrivilege(_, _, _, myLevel):
            // 跳特权页
            gotoPrivilegePage(myLevel)
        case let .myPrivilege(myLevel, _, _, _, _):
            // 跳特权页
            gotoPrivilegePage(myLevel)
        case .action:
            break
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard datas.count > section else {
            return 0.01
        }
        if section == 0 {
            if case .myPrivilege = datas[0] {
                return 32
            } else {
                return 0.01
            }
        }
        return 0.01
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        guard datas.count > section else {
            return 0.01
        }
        if section == 0 {
            if case .myPrivilege = datas[0] {
                return 16
            } else {
                return 0
            }
        }
        return 16
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            var alpha =  scrollView.contentOffset.y / (k_Height_NavigationtBarAndStatuBar)
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = "银河会员中心"
            bgIcon.isHidden = true
        } else {
            bgIcon.isHidden = false
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
        }
    }
}
