//
//  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 = ["人脉","活动"]
    
    var arrItemVCs : [YHBaseViewController] = []
    
    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 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 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(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 = YHActivityListViewController()
                arrItemVCs.append(vc)
            } else {
                let vc = YHMatchUserViewController()
                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
        
        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)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestFriendRequest()
        //处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
    }

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

        //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        segmentedView.frame = CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: view.bounds.size.width, height: 48)
        listContainerView.frame = CGRect(x: 0, y: k_Height_safeAreaInsetsTop() + 48, width: view.bounds.size.width, height: view.bounds.size.height - 48 - k_Height_safeAreaInsetsTop())
    }
    
    func requestFriendRequest() {
        if YHLoginManager.shared.isLogin() {
            self.friendViewModel.getMyFriendList { success, error in
                let unreadCount =  self.friendViewModel.friendListModel.applyFriends.count
                self.unreadCount = unreadCount
                self.friendsBtn.isHidden = self.segmentedView.selectedIndex != 0
            }
        } else {
            self.unreadCount = 0
        }
    }
    
    @objc func goActivityVC() {
        segmentedView.selectItemAt(index: 1)
    }
    
    
    @objc func goConnectionVC() {
        segmentedView.selectItemAt(index: 0)
    }
    
}

extension YHCommunityViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        if segmentedView.selectedIndex == 0 {
            bgImgV.isHidden = false
            friendsBtn.isHidden = false
            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 {
            bgImgV.isHidden = true
            friendsBtn.isHidden = true
            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 {
        return arrItemVCs[index] as! JXSegmentedListContainerViewListDelegate
    }
}

