//
//  YHHomePageViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import ESPullToRefresh
import GKNavigationBarSwift
import SmartCodable
import JXSegmentedView

class YHHomePageViewController: YHBaseViewController {
    private var needUpdateMgrItem = false
    private var isTopMostAndVisible = true
    
    lazy var viewModel: YHHomePageViewModel = {
        let viewModel = YHHomePageViewModel()
        return viewModel
    }()
    
    let msgViewModel: YHMsgViewModel = YHMsgViewModel()
    
    let serviceCenterMainReqVM: YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    
    var homeHeaderViewHeight: CGFloat = 0.0
    
    private var isGoYHManagerFlag: Bool = false
    private var didShowFloating: Bool = false
    
    var configModel: YHHomeInfoModel? {
        didSet {
            homeHeaderView.kingModel = configModel?.king_kong_list ?? []
        }
    }
    
    lazy var homeCollectView = {
        // 设置布局方向
        let flowLayout = YHHomeCollectionLayout()
        flowLayout.minimumInteritemSpacing = 7.0
        flowLayout.minimumColumnSpacing = 7.0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        
        let collectinoView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectinoView.backgroundColor = .white
        collectinoView.register(YHHomeCollectionViewCell.self, forCellWithReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier)
        collectinoView.delegate = self
        collectinoView.dataSource = self
        collectinoView.translatesAutoresizingMaskIntoConstraints = false
        collectinoView.alwaysBounceVertical = true
        return collectinoView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 0、
        setupUI()
        
        // 1、加载默认数据
        addDefaultData()
        
        // 2、请求新的数据
        getData()
        // 3、接收七鱼推送通知
        setupNotification()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        isTopMostAndVisible = false
        YHPlayerManager.shared.handlePageChanged(isRecommendPage: false)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        isTopMostAndVisible = true
        YHPlayerManager.shared.handlePageChanged(isRecommendPage: true)
        // 没登录不让展示小窗
        guard YHLoginManager.shared.isLogin() else {
            return
        }
        guard YHPlayerManager.shared.isConfigFloating != false else {
            return
        }
        guard let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open else {
            // 关闭就不让显示直播浮窗
            return
        }
        viewModel.getHomeFloatingLive { [weak self] success, _ in
            guard let self = self else {
                return
            }
            if success {
                if let liveInfo = self.viewModel.liveInfo {
                    self.setupLiveFloating(liveInfo: liveInfo)
                }
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if needUpdateMgrItem {
            needUpdateMgrItem = false
            updateMgrItem()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    lazy var homeHeaderView: YHHomeHeadView = {
        let view = YHHomeHeadView()
        view.orderTipsViewClickEvent = { [weak self] in
            guard let self = self else {
                return
            }
            if YHButlerServiceManager.shared.isUatAllowed(), YHLoginManager.shared.isLogin() {
                self.gotoMgrVC()
            } else {
                goToMessagePage()
            }
        }
        view.galaxyManagerItemClickEvent = { [weak self] in
            guard let self = self else {
                return
            }
            self.gotoMgrVC()
        }
        return view
    }()
}

// MARK: - 私有方法
private extension YHHomePageViewController {
    private func setupLiveFloating(liveInfo: YHHomeLiveInfoModel) {
        printLog("#####setupLiveFloating(liveInfo: YHHomeLiveInfoModel) ")
        if liveInfo.status == 1 {
            let playbackInfo = YHPlayerManager.PlaybackInfo(id: liveInfo.id, token: liveInfo.token, channelId: liveInfo.rtmp_channel, uid: UInt(liveInfo.user_id), isLive: true, scene: .floating, playerType: .main)
            YHPlayerManager.shared.enterFloating(from: nil, playbackInfo: playbackInfo, isConfigured: true)
        } else if YHPlayerManager.shared.floatingWindow?.source == .configured {
            YHPlayerManager.shared.exitFloating()
        }
    }
    
    func gotoMgrVC() {
        if self.isGoYHManagerFlag {
            return
        }
        
        self.isGoYHManagerFlag = true
        YHHUD.show(.progress(message: "加载中..."))
        self.gotoYinHeManager(completion: { [weak self] success in
            self?.isGoYHManagerFlag = false
            guard let self = self else {
                return
            }
            YHHUD.hide()
            if success {
                // 需要回到页面再刷新已读，因为不在当前页
                self.needUpdateMgrItem = true
            }
        })
    }
    
    func updateMgrItem() {
        // 页面已经加载了
        guard isViewLoaded, homeHeaderView.superview != nil else {
            return
        }
        guard YHLoginManager.shared.isLogin() else {
            return
        }
        guard YHButlerServiceManager.shared.isUatAllowed() else {
            self.homeHeaderView.orderTipsView.customerServiceMessage = YHButlerServiceHomeInfoMessage(showButler: false, serviceMessage: nil)
            return
        }
        needUpdateMgrItem = false
        let showButler = true
        // 不获取最新消息内容了
        let serviceMessage = YHButlerServiceMessage()
        
        serviceMessage.content = "一对一专属服务"
        // 因为七鱼的消息有bug，某些消息不处理未读状态，目前根据未读数量unreadCount来处理红点
        serviceMessage.isRead = YHButlerServiceManager.shared.unreadCount == 0
        self.homeHeaderView.orderTipsView.customerServiceMessage = YHButlerServiceHomeInfoMessage(showButler: showButler, serviceMessage: serviceMessage)
    }
    
    // 是否展示订单提示视图
    func updateHomeHeadViewStyle(_ styleType: YHHomeHeadViewStyleType) {
        
        homeHeaderViewHeight = homeHeaderView.getHomeHeadViewH(headStyle: styleType)
        homeHeaderView.frame = CGRect(x: 20, y: -homeHeaderViewHeight, width: KScreenWidth - 40, height: homeHeaderViewHeight)
        homeHeaderView.homeHeadViewStyleType = styleType
        homeCollectView.contentInset = UIEdgeInsets(top: homeHeaderViewHeight, left: 0, bottom: 0, right: 0)
        
        self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: false)
        
        let tmpHeadView = homeCollectView.es.addYHPullToRefresh {
            self.getData()
        }
        
        var r = CGRect.zero
        r.origin.y = -homeHeaderViewHeight - 81
        r.origin.x = 0
        r.size.width = KScreenWidth
        r.size.height = 81.0
        tmpHeadView.frame = r
        
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
        
        self.homeCollectView.es.stopPullToRefresh()
        self.homeCollectView.es.stopLoadingMore()
        if self.viewModel.hasMoreForHomeNews == false {
            self.homeCollectView.es.noticeNoMoreData()
            self.homeCollectView.footer?.alpha = 1
        }
        self.homeCollectView.reloadData()
    }
    
    func addDefaultData() {
        // 关闭就不让显示直播浮窗
        if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
            homeHeaderView.homeBannerView.dataArr = getCacheDataForBanner()
        } else {
            homeHeaderView.homeBannerView.dataArr = getCacheDataForBanner().filter {
                ($0.skip_type != 100) && ($0.skip_type != 101) && ($0.skip_type != 102)
            }
        }
        
        getCacheDataForHomeNewsData()
    }
    
    // 获取缓存的 banner数据
    func getCacheDataForBanner() -> [YHBannerModel] {
        let arrString2 = UserDefaults.standard.value(forKey: "homeBannerData")
        if let tmp = arrString2 as? String, let dic = tmp.toArray() {
            guard let result = [YHBannerModel].deserialize(from: dic) else {
                return [YHBannerModel.localDefaultItem()]
            }
            
            var arrData = result as? [YHBannerModel]
            if let arr = arrData {
                if arr.isEmpty {
                    let model = YHBannerModel.localDefaultItem()
                    arrData = [model]
                    
                } else if arr.count > 10 {
                    arrData = Array(arrData?[0...9] ?? [])
                }
                return arrData!
            }
        }
        
        return [YHBannerModel.localDefaultItem()]
    }
    
    // 获取缓存的 第一页page数据
    func getCacheDataForHomeNewsData() {
        let arrString2 = UserDefaults.standard.value(forKey: "homeFirstPageNewsData")
        if let tmp = arrString2 as? String, let dic = tmp.toArray() {
            guard let result = [YHHomeListModel].deserialize(from: dic) else {
                return
            }
            
            if self.viewModel.hasMoreForHomeNews == false {
                self.homeCollectView.es.noticeNoMoreData()
                self.homeCollectView.footer?.alpha = 1
            }
            
            if let arrData = result as? [YHHomeListModel] {
                for item in arrData {
                    item.calHeightParam()
                }
                
                self.viewModel.arrHomeNewsData = arrData
                self.homeCollectView.reloadData()
            }
            self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: false)
        }
    }
    
    func getHomeBannerData() {
        DispatchQueue.global().async {
            self.viewModel.getHomeBanner(0) {[weak self] _, _ in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.is_integral_open {
                        self.homeHeaderView.homeBannerView.dataArr = self.viewModel.banners ?? self.getCacheDataForBanner()
                    } else {
                        self.homeHeaderView.homeBannerView.dataArr = (self.viewModel.banners ?? self.getCacheDataForBanner()).filter {
                            ($0.skip_type != 100) && ($0.skip_type != 101) && ($0.skip_type != 102)
                        }
                    }
                    
                    if let arrB = self.viewModel.banners, arrB.count > 0 {
                        let arrString = arrB.toJSONString()
                        UserDefaults.standard.set(arrString, forKey: "homeBannerData")
                        UserDefaults.standard.synchronize()
                    }
                }
            }
        }
    }
    
    func loadMoreData() {
        DispatchQueue.global().async {
            self.viewModel.getHomeNewsList(firstFlag: false) {[weak self] _, _ in
                guard let self = self else { return }
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.35, execute: {
                    CATransaction.setDisableActions(true)
                    self.homeCollectView.reloadData()
                    CATransaction.commit()
                    
                    self.homeCollectView.es.stopLoadingMore()
                    if self.viewModel.hasMoreForHomeNews == false {
                        self.homeCollectView.es.noticeNoMoreData()
                        self.homeCollectView.footer?.alpha = 1
                    }
                })
            }
        }
    }
    
    func loadFirstData() {
            self.viewModel.getHomeNewsList(firstFlag: true) {[weak self] _, _ in
                guard let self = self else { return }
                
                if let arrB = self.viewModel.arrHomeNewsData, arrB.count > 0 {
                    let arrString = arrB.toJSONString()
                    UserDefaults.standard.set(arrString, forKey: "homeFirstPageNewsData")
                    UserDefaults.standard.synchronize()
                }
                
                self.homeCollectView.es.stopPullToRefresh()
                
                if self.viewModel.hasMoreForHomeNews == false {
                    self.homeCollectView.es.noticeNoMoreData()
                    self.homeCollectView.footer?.alpha = 1
                }
                
                self.homeCollectView.reloadData()
                
                DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.25, execute: {
                    self.requestOrder()
                })
            }
    }
    
    func setupUI() {
        gk_navigationBar.isHidden = true
        
        view.addSubview(homeCollectView)
        homeCollectView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        let headViewH: CGFloat = homeHeaderView.getHomeHeadViewH(headStyle: .evaluationA)
        homeHeaderViewHeight = headViewH
        homeHeaderView.homeHeadViewStyleType = .evaluationA
        
        homeHeaderView.frame = CGRect(x: 20, y: -headViewH, width: KScreenWidth - 40, height: headViewH)
        homeCollectView.addSubview(homeHeaderView)
        homeCollectView.contentInset = UIEdgeInsets(top: headViewH, left: 0, bottom: 0, right: 0)
        
        let tmpHeadView = homeCollectView.es.addYHPullToRefresh {
            self.getData()
        }
        
        var r = tmpHeadView.frame
        r.origin.y -= headViewH
        tmpHeadView.frame = r
        
        printLog(tmpHeadView.frame)
        
        homeCollectView.showsHorizontalScrollIndicator = false
        homeCollectView.showsVerticalScrollIndicator = false
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
    }
    
    func needUpdateYinheManager() {
        if !isTopMostAndVisible {
            // 需要回到页面再刷新已读，因为不在当前页
            self.needUpdateMgrItem = true
        } else {
            updateMgrItem()
        }
    }
    
    @objc func didQiYuReceiveNewMsg() {
        needUpdateYinheManager()
    }
    
    @objc private func didRevUatParam() {
        guard serviceCenterMainReqVM.arrContactList.count > 0 else {
            return
        }
        needUpdateYinheManager()
    }
    
    func setupNotification() {
        // 改为不监听消息到来，而是未读消息数量改变
        NotificationCenter.default.addObserver(self, selector: #selector(didQiYuReceiveNewMsg), name: YhConstant.YhNotification.didQiYuUnReadMsgCountChangeNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didRevUatParam), name: YhConstant.YhNotification.didRevUatParam, object: nil)
    }
}

extension YHHomePageViewController {
    // MARK: - 跳银河管家
    
    private func gotoYinHeManager(completion: @escaping (Bool) -> Void) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            return
        }
        YHAnalytics.track("APP_HomeTab_IntelligentAssistant")
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { success in
            completion(success)
        })
    }
}

// MARK: - public方法
extension YHHomePageViewController {
    func gotoYinHeMgrVC() {
        self.gotoMgrVC()
    }
    
    func goTop() {
        self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: true)
    }
    
    func getData() {
        loadFirstData()
        getHomeBannerData()
    }
    
    // 请求订单数据
    func requestOrder() {
        if YHLoginManager.shared.isLogin()  == false {
            self.updateHomeHeadViewStyle(.evaluationA)
            return
        }
        self.serviceCenterMainReqVM.getContactList {
            [weak self] success, _ in
            guard let self = self else { return }
            let isShow = self.serviceCenterMainReqVM.arrContactList.count > 0
            if isShow {
                self.viewModel.getBasicInfoForSigner { success, _ in
                    if success {
                        self.homeHeaderView.orderTipsView.dataModelForBasicInfo = self.viewModel.signerModel
                    } else {
                        
                    }
                    
                    // modify by davidhuang  2024.12.23 修改数据源 方便后续再修改回来
                    let showEvaluationB = false// self.viewModel.signerModel?.after_sales_h5_info?.show == true
                    if showEvaluationB {
                        if let url = self.viewModel.signerModel?.after_sales_h5_info?.url, url.count > 0 {
                            self.homeHeaderView.talentEvaluationView.updateUrl(url)
                        }
                    }
                    
                    self.viewModel.getLastTwoMessagesForSigner { success, _ in
                        if success {
                            self.homeHeaderView.orderTipsView.arrLastTwoMessage = self.viewModel.arrLastTwoMessages
                            self.updateMgrItem()
//                            self.homeHeaderView.updateSubViewsConstraints()
                        } else {
                            self.updateMgrItem()
//                            self.homeHeaderView.updateSubViewsConstraints()
                        }
                        if showEvaluationB {
                            self.updateHomeHeadViewStyle(.evaluationBAndOrderTips)
                        } else {
                            self.updateHomeHeadViewStyle(.orderTips)
                        }
                        NotificationCenter.default.post(name: YhConstant.YhNotification.didLoadYhManagerNotification, object: nil)
                    }
                }
            } else {
                self.updateHomeHeadViewStyle(.evaluationA)
            }
        }
    }
    
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension YHHomePageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.arrHomeNewsData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier, for: indexPath) as? YHHomeCollectionViewCell else { return UICollectionViewCell() }
        cell.listModel = self.viewModel.arrHomeNewsData?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = self.viewModel.arrHomeNewsData?[indexPath.row] else { return }
        if model.type == 2 {
            let vc = YHHomeWebViewController()
            vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(model.id)"
            vc.id = model.id
            vc.block = { item in
                if let arr = self.viewModel.arrHomeNewsData {
                    for (index, targetItem) in arr.enumerated() {
                        if targetItem.id == item.id {
                            targetItem.is_like = item.is_like
                            targetItem.like_count = item.like_count
                            self.homeCollectView.reloadItems(at: [IndexPath.SubSequence(item: index, section: 0)])
                        }
                    }
                }
            }
            self.navigationController?.pushViewController(vc)
        } else if model.type == 1 {
            printLog("直接播放视频")
        }
    }
}

// MARK: - CollectionViewWaterfallLayoutDelegate
extension YHHomePageViewController: CollectionViewWaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        let count = self.viewModel.arrHomeNewsData?.count ?? 0
        
        if indexPath.row < count {
            guard let model = self.viewModel.arrHomeNewsData?[indexPath.row] else { return CGSize.zero }
            return CGSize(width: model.img_width_cell, height: model.img_height_cell)
        }
        
        let width = (KScreenWidth - 47) / 2
        return CGSize(width: width, height: 140.0)
    }
}

// MARK: - UIScrollViewDelegate
extension YHHomePageViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let itemNumber = viewModel.preloadItemIndex // 你想要检查的item的位置，例如10
        // 首先，计算IndexPath
        let section = 0 // 假设只有一个section
        let itemIndex = itemNumber - 1 // UICollectionView的item索引从0开始
        let indexPathToCheck = IndexPath(item: itemIndex, section: section)
        // 然后，检查这个IndexPath是否在当前可见的item列表中
        if homeCollectView.indexPathsForVisibleItems.contains(indexPathToCheck) {
//            printLog("第\(itemNumber)个item已经展示出来了")
            loadMoreData()
        } else {
//            printLog("\(itemNumber)目标不在范围内")
        }
    }
}

// MARK: - JXSegmentedListContainerViewListDelegate
extension YHHomePageViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
