//
//  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

let kShowAlertOfSuggestLatestVersion =  "show_alert_suggest_latest_version"

class YHHomePageViewController: YHBaseViewController {
    lazy var viewModel : YHHomePageViewModel = {
        let viewModel = YHHomePageViewModel()
        return viewModel
    }()
    
    let serviceCenterMainReqVM : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    var homeHeaderViewHeight = YHHomeHeadView.fixViewH
    
    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()
        setupUI()
        
        //1、加载默认数据
        homeHeaderView.homeBannerView.dataArr = getCacheDataForBanner()
        getCacheDataForHomeNewsData()
        
        
        requestOrder()
        
        //2、请求新的数据
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestAppNewVersion()
        //获取OSS密钥
        YHOSSManager.share.getOSSID()
        updateDefaultSearchKeyWord()
        
    }
    
    lazy var searchView: YHHomeSearchView = {
        let view = YHHomeSearchView()
        let tap = UITapGestureRecognizer(target: self, action: #selector(didSearchBarClicked))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var homeHeaderView: YHHomeHeadView = {
        let view = YHHomeHeadView()
        return view
    }()
    
    var tapTimestamp : CFAbsoluteTime = -10.0
    
    func updateDefaultSearchKeyWord() {
        var placeHolder = "香港身份"
        if isHaveLocalSearchRecords() {
            let latestValidSearchWord = getLatestValidSearchWord()
            if !latestValidSearchWord.isEmpty {
                placeHolder = latestValidSearchWord
            }
        }
        searchView.placeHolder = placeHolder
    }
    
    // 请求订单数据
    func requestOrder() {
        serviceCenterMainReqVM.getContactList {
            [weak self] success, error in
            guard let self = self else { return }
            let isShow = self.serviceCenterMainReqVM.arrContactList.count > 0
            DispatchQueue.main.async {
                self.showOrderTipsView(isShow)
            }
        }
    }
    
    // 是否展示订单提示视图
    func showOrderTipsView(_ show:Bool) {
        homeHeaderViewHeight = show ? YHHomeHeadView.viewHWithOrderTips : 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)
        
        let tmpHeadView = homeCollectView.es.addYHPullToRefresh {
            self.getData()
        }
        var r = tmpHeadView.frame
        r.origin.y = r.origin.y - homeHeaderViewHeight
        tmpHeadView.frame = r
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
        self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: false)
    }
}

private extension YHHomePageViewController {
    
    
    @objc func didSearchBarClicked() {
        let vc = YHSearchInfomationVC()
        vc.searchPlaceHolder = searchView.placeHolder
        printLog("placeHolder: \(searchView.placeHolder)")
        self.navigationController?.pushViewController(vc)
    }
    
    func getData() {
        loadFirstData()
        getHomeBannerData()
    }
    
    //获取缓存的 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()
            }
        }
    }
    
    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(firstPageFlag : 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() {
        DispatchQueue.global().async {
            self.viewModel.getHomeNewsList(firstPageFlag : 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()
                }
                
                DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: {
                    self.homeCollectView.es.stopPullToRefresh()
                })
                DispatchQueue.main.async {
                    if self.viewModel.hasMoreForHomeNews == false {
                        self.homeCollectView.es.noticeNoMoreData()
                        self.homeCollectView.footer?.alpha = 1
                    }
                    
                    CATransaction.setDisableActions(true)
                    self.homeCollectView.reloadData()
                    CATransaction.commit()
                }
            }
        }
    }
    
    func setupUI() {
        gk_navigationBar.isHidden = false
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        
        
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_safeAreaInsetsTop() + 6)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(YHHomeSearchView.viewH)
        }
        
        view.addSubview(homeCollectView)
        homeCollectView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchView.snp.bottom).offset(6+20)
            make.bottom.equalToSuperview().offset(-k_Height_TabBar)
        }
        
        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
        
        homeCollectView.showsHorizontalScrollIndicator = false
        homeCollectView.showsVerticalScrollIndicator = false
        homeCollectView.es.addInfiniteScrolling {
            self.loadMoreData()
        }
    }
    
    @objc func homepageRefresh() {
        loadFirstData()
    }
    
    @objc func loginSuccess() {
        requestOrder()
        getData()
    }
    
    @objc func logoutSuccess() {
        showOrderTipsView(false)
        getData()
    }
}

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("直接播放视频")
        }
    }
}

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

extension YHHomePageViewController : UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let doubleTapInterval : CGFloat = 0.3
        
        if tabBarController.selectedIndex == 0 {
            let timestamp = CFAbsoluteTimeGetCurrent()
            printLog(timestamp - self.tapTimestamp)
            if timestamp - self.tapTimestamp < doubleTapInterval {
                self.homeCollectView.setContentOffset(CGPoint(x: 0, y: -homeHeaderViewHeight), animated: true)
            }
            self.tapTimestamp = timestamp
            
        } else if tabBarController.selectedIndex == 2 {
            // 点击消息tab 清空应用icon未读数
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
    }
    
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard let index = tabBarController.viewControllers?.firstIndex(of: viewController) else {
            return false
        }
        if index == 1 || index == 2 {
            if YHLoginManager.shared.isLogin() {
                return true
            } else {
                YHOneKeyLoginManager.shared.oneKeyLogin()
                YHLoginManager.shared.loginSuccessActionBlock = {[weak self] in
                    guard self != nil else { return }
                    tabBarController.selectedIndex = index
                    YHLoginManager.shared.loginSuccessActionBlock = nil
                }
                return false
            }
        }
        return true
    }
}

extension YHHomePageViewController {
    
    func requestAppNewVersion() {
        if YHConfigManager.shared.loadNewDataFlag == false {
            YHConfigManager.shared.loadConfigData {
                [weak self] in
                guard let self = self else { return }
                self.showNewVersionAlertView()
            }
        } else {
            showNewVersionAlertView()
        }
    }
    
    func showNewVersionAlertView() {
        let isNeedShowAlert =  YHAppVersionManager.shared.needShowAlertViewOfSuggestVersionUpdate()
        if isNeedShowAlert {
            if let configModel = YHConfigManager.shared.reqVM.configModel {
                let alertView = YHFindAppNewVersionView.alertView(version: configModel.max_version)
                let arr = configModel.suggest_updating_msg.components(separatedBy: "$")
                alertView.updateContentArray(arr)
                alertView.show()
            }
        }
    }
}

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)目标不在范围内")
        }
    }
}
