//
//  YHCommunityViewController.swift
//  galaxy
//
//  Created by EDY on 2024/6/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHCommunityViewController: YHBaseViewController {
    var defaltIndex: Int = 0
    let friendViewModel = YHMatchUserViewModel()
//    let arrItemTitles = ["会话", "人脉","活动"]
    let arrItemTitles = ["会话", "活动"]

    var arrItemVCs: [YHBaseViewController] = []
    
    private lazy var princleVM: YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()
    
    lazy var segmentedView: JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 48))
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSC_M(ofSize: 15)
        dataSource.titleNormalColor = UIColor.yhGreyColor
        
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 21)
        dataSource.titleSelectedColor = .white
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 28.0
        return dataSource
    }()
    
    lazy var bgImgV: UIImageView = {
        let bg = UIImageView(image: UIImage(named: "people_match_bg"))
        return bg
    }()
    
    // 分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        let view = JXSegmentedListContainerView(dataSource: self, type: .scrollView)
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var cleanAllMsgBtn: UIButton = {
        let cleanBtn = UIButton()
        cleanBtn.setImage(UIImage(named: "msg_clean"), for: .normal)
        cleanBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        cleanBtn.addTarget(self, action: #selector(didCleanButtonClicked), for: .touchUpInside)
        return cleanBtn
    }()
    
//    lazy var friendsBtn:UIButton = {
//        let btn = UIButton()
//        btn.setImage(UIImage(named: "people_friends_btn"), for: .normal)
//        btn.setTitle("好友", for: .normal)
//        btn.setTitleColor(UIColor.white, for: .normal)
//        btn.iconInLeft(spacing: 4.0)
//        btn.titleLabel?.font = UIFont.PFSC_R(ofSize:15)
//        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
//        btn.addTarget(self, action: #selector(didFriendsBtnClicked), for: .touchUpInside)
//        return btn
//    }()
//    
    let unreadHeight = 16.0
    lazy var unreadLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.textAlignment = .center
        label.backgroundColor = .failColor
        label.font = .PFSC_M(ofSize: 10)
        label.layer.cornerRadius = unreadHeight/2.0
        label.clipsToBounds = true
        label.isHidden = true
        return label
    }()
    
    var unreadCount: Int = 0 {
        didSet {
//            self.updateUnreadCount(self.unreadCount)
        }
    }
    
//    func updateUnreadCount(_ count : Int) {
//        self.unreadLabel.isHidden = (count <= 0)
//        if 0 < count && count < 100 {
//            self.unreadLabel.text = "\(count)"
//        } else if count >= 100 {
//            self.unreadLabel.text = "99+"
//        }
//        var width = unreadHeight
//        var leftMargin = -8
//        if 10 <= count && count < 100 {
//            width = 22.0
//        } else if count >= 100 {
//            width = 30.0
//            leftMargin = -14
//        }
//        self.unreadLabel.snp.updateConstraints { make in
//            make.width.equalTo(width)
//            make.left.equalTo(self.friendsBtn.snp.right).offset(leftMargin)
//        }
//    }

    @objc func didBackBtnClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func didCleanButtonClicked() {
        if arrItemVCs.count > 0, let msgVC = arrItemVCs[0] as? YHMessageListVC {
            msgVC.didCleanButtonClicked()
        }
    }
    
    @objc func didFriendsBtnClicked() {
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        let vc = YHMyGoodFriendsVC()
        self.navigationController?.pushViewController(vc)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = .white
        self.view.addSubview(bgImgV)
        self.bgImgV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        NotificationCenter.default.addObserver(self, selector: #selector(goMessageListVC(_:)), name: YhConstant.YhNotification.goMessageVCNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(goActivityVC), name: YhConstant.YhNotification.goActivityVCNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(goConnectionVC), name: YhConstant.YhNotification.goConnectionVCNotifiction, object: nil)
        
        for i in 0..<arrItemTitles.count {
            if i == 0 { // 消息
                let vc = YHMessageListVC()
                arrItemVCs.append(vc)
            }
//            } else if i == 1 { // 人脉
//                let vc = YHMatchUserViewController()
//                arrItemVCs.append(vc)
//                
//            }
            else if i == 1 { // 活动
                let vc = YHActivityListViewController()
                arrItemVCs.append(vc)
            }
        }
        
        // segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        segmentedView.dataSource = segmentedDataSource
        view.addSubview(segmentedView)

        segmentedView.listContainer = listContainerView
        view.addSubview(listContainerView)
        
        // 分类Title
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        
        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = UIColor.white
        segmentedView.indicators = [indicator]
        segmentedView.defaultSelectedIndex = defaltIndex
        segmentedView(segmentedView, didSelectedItemAt: defaltIndex)
        
        self.view.addSubview(cleanAllMsgBtn)
        cleanAllMsgBtn.snp.makeConstraints { make in
            make.width.height.equalTo(21)
            make.centerY.equalTo(segmentedView)
            make.right.equalToSuperview().offset(-20)
        }

//        self.view.addSubview(friendsBtn)
//        friendsBtn.snp.makeConstraints { make in
//            make.width.equalTo(54.0)
//            make.height.equalTo(21)
//            make.right.equalTo(-20)
//            make.top.equalTo(12+k_Height_safeAreaInsetsTop())
//        }
//        
//        self.friendsBtn.addSubview(self.unreadLabel)
//        self.unreadLabel.snp.makeConstraints { make in
//            make.width.height.equalTo(unreadHeight)
//            make.left.equalTo(self.friendsBtn.snp.right).offset(-8)
//            make.top.equalTo(self.friendsBtn.snp.top).offset(-8)
//        }
        
        segmentedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_safeAreaInsetsTop())
            make.height.equalTo(48.0)
        }
        
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_safeAreaInsetsTop() + 48.0)
            make.bottom.equalTo(-k_Height_TabBar)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestFriendRequest()
        // 处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        showAlert()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // 离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    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)
                }
            }
        }
    }
    
    func requestFriendRequest() {
        if YHLoginManager.shared.isLogin() {
            self.friendViewModel.getMyFriendList { _, _ in
                let unreadCount =  self.friendViewModel.friendListModel.applyFriends.count
                self.unreadCount = unreadCount
//                self.friendsBtn.isHidden = self.segmentedView.selectedIndex != 1
            }
        } else {
            self.unreadCount = 0
        }
    }
    
    @objc func goMessageListVC(_ notification: Notification) {
        segmentedView.selectItemAt(index: 0)
        guard let userInfo = notification.userInfo else {
            return
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
            guard let messageListVC = self.arrItemVCs[0] as? YHMessageListVC else {
                return
            }
            messageListVC.handleRemoteNotification(userInfo)
        }
    }
    
    @objc func goActivityVC() {
        segmentedView.selectItemAt(index: 2)
    }
    
    @objc func goConnectionVC() {
        segmentedView.selectItemAt(index: 1)
    }
}

extension YHCommunityViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
//        if segmentedView.selectedIndex == 1 { // 人脉
//            bgImgV.isHidden = false
//            friendsBtn.isHidden = false
//            cleanAllMsgBtn.isHidden = true
//            segmentedDataSource.titleNormalColor = UIColor(hex: 0xFFFFFF, alpha: 0.6)
//            segmentedDataSource.titleSelectedColor = .white
//            let indicator = JXSegmentedIndicatorLineView()
//            indicator.indicatorWidth = 16
//            indicator.indicatorHeight = 2
//            indicator.indicatorCornerRadius = 0.0
//            indicator.indicatorColor = UIColor.white
//            segmentedView.indicators = [indicator]
//            
//        } else { // 非人脉tab
            bgImgV.isHidden = true
//            friendsBtn.isHidden = true
            cleanAllMsgBtn.isHidden = segmentedView.selectedIndex != 0
            segmentedDataSource.titleNormalColor = UIColor.yhGreyColor
            segmentedDataSource.titleSelectedColor = UIColor.mainTextColor
            let indicator = JXSegmentedIndicatorLineView()
            indicator.indicatorWidth = 16
            indicator.indicatorHeight = 2
            indicator.indicatorCornerRadius = 0.0
            indicator.indicatorColor = UIColor.brandMainColor
            segmentedView.indicators = [indicator]
//        }
        segmentedView.dataSource = segmentedDataSource
        self.segmentedView.reloadDataWithoutListContainer()
    }
}

extension YHCommunityViewController {
    func jumpToItemIndex(itemIndex: Int) {
        self.segmentedView.selectItemAt(index: itemIndex)
    }
}

extension YHCommunityViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        guard let vc = arrItemVCs[index] as? JXSegmentedListContainerViewListDelegate else {
            return YHMessageListVC()
        }
        return vc
    }
}

extension YHCommunityViewController {
    // 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()
        })
    }
}
