//
//  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 {
    
    lazy var viewModel : YHHomePageViewModel = {
        let viewModel = YHHomePageViewModel()
        return viewModel
    }()
    
    let msgViewModel: YHMsgViewModel = YHMsgViewModel()
    
    let serviceCenterMainReqVM : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    
    var homeHeaderViewHeight = YHHomeHeadView.fixViewH
    
    var needReloadDataFlag : Bool = false
    
    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()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if needReloadDataFlag {
            needReloadDataFlag = false
            requestOrder()
        }
    }
    
    lazy var homeHeaderView: YHHomeHeadView = {
        let view = YHHomeHeadView()
        return view
    }()
}

//MARK: - 私有方法
private extension YHHomePageViewController {
    // 是否展示订单提示视图
    func showOrderTipsView(_ show:Bool) {
        
        homeHeaderViewHeight = show ? homeHeaderView.homeHeadViewH : YHHomeHeadView.fixViewH
        homeHeaderView.frame = CGRect(x: 20, y: -homeHeaderViewHeight, width: KScreenWidth - 40, height: homeHeaderViewHeight)
        homeHeaderView.isNeedHideOrderTipsView = !show
        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 = CGRectZero
        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() {
        homeHeaderView.homeBannerView.dataArr = getCacheDataForBanner()
        getCacheDataForHomeNewsData()
    }
    
    @objc func clickMsgitem() {
        needReloadDataFlag = true
    }
    
    //获取缓存的 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] success, error in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    self.homeHeaderView.homeBannerView.dataArr = self.viewModel.banners ?? self.getCacheDataForBanner()
                    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] success, error 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] success, error 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
        NotificationCenter.default.addObserver(self, selector: #selector(clickMsgitem), name: YhConstant.YhNotification.clickHomeMsgNotifiction, object: nil)
        
        view.addSubview(homeCollectView)
        homeCollectView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        homeHeaderView.frame = CGRect(x: 20, y: -YHHomeHeadView.fixViewH, width: KScreenWidth - 40, height: YHHomeHeadView.fixViewH)
        homeCollectView.addSubview(homeHeaderView)
        homeCollectView.contentInset = UIEdgeInsets(top: YHHomeHeadView.fixViewH, left: 0, bottom: 0, right: 0)
        
        let tmpHeadView = homeCollectView.es.addYHPullToRefresh {
            self.getData()
        }
        
        var r = tmpHeadView.frame
        r.origin.y = r.origin.y - YHHomeHeadView.fixViewH
        tmpHeadView.frame = r
        
        printLog(tmpHeadView.frame)
        
        homeCollectView.showsHorizontalScrollIndicator = false
        homeCollectView.showsVerticalScrollIndicator = false
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
    }
}

//MARK: - public方法
extension YHHomePageViewController {
    func goTop() {
        self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: true)
    }
    
    
    func getData() {
        loadFirstData()
        getHomeBannerData()
    }
    
    
    // 请求订单数据
    func requestOrder() {
        if YHLoginManager.shared.isLogin()  == false {
            self.showOrderTipsView(false)
            return
        }
        self.serviceCenterMainReqVM.getContactList {
            [weak self] success, error in
            guard let self = self else { return }
            let isShow = self.serviceCenterMainReqVM.arrContactList.count > 0
            if isShow {
                
                self.viewModel.getBasicInfoForSigner { success, error in
                    if success {
                        self.homeHeaderView.orderTipsView.dataModelForBasicInfo = self.viewModel.signerModel
                    } else {
                        
                    }
                    
                    self.viewModel.getLastTwoMessagesForSigner { success, error in
                        if success {
                            self.homeHeaderView.orderTipsView.arrLastTwoMessage = self.viewModel.arrLastTwoMessages
                            self.homeHeaderView.updateSubViewsConstraints()
                        } else {
                            
                        }
                        self.showOrderTipsView(isShow)
                    }
                }
            } else {
                self.showOrderTipsView(isShow)
            }
        }
    }
    
}

//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 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHHomeCollectionViewCell.cellReuseIdentifier, for: indexPath) as! YHHomeCollectionViewCell
        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
    }
}
